const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-DyEh5ETv.js","assets/useLeadSiteSearchSuggestions-DNWRfMk7.js","assets/CityPagesModule-CF3ebwIs.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-CYLm3nO3.js","assets/LeadSiteLandRanchHome-gZ_LYj5Z.js","assets/LeadSiteSearch-BiwQJhqB.js","assets/LeadSiteListingCardImage-BK4r2yy-.js","assets/LeadSiteMap-BGlJHfyS.js","assets/LeadSiteLuxurySearch-Dgrs2eXR.js","assets/LeadSiteListingDetail-BcGvlSS_.js","assets/ListingVideoTour-CO45P3cd.js","assets/useListingVideos-y24MeUp9.js","assets/LeadSiteLuxuryListingDetail-lVETchFg.js","assets/LeadSiteCityPage-BlUkEbR9.js","assets/LeadSiteSubdivisionPage-KALPAyHL.js","assets/PostcardManager-Jk1KUcRQ.js","assets/usePostcardZones-vW981CvR.js","assets/DirectMail-QU7fHX-V.js","assets/jspdf.es.min-BJ7jppbC.js","assets/LeadSiteEditor-CK1HDQiR.js","assets/ImageUrlField-DQ3ZsTv6.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-D_-SJiGQ.js","assets/MLSListingDetail-D27RjZnE.js","assets/EmailCampaignComposer-DgyameH5.js","assets/EditorModeSelector-BwEYnnpp.js","assets/SharedCampaignTemplates-w6Etkp6C.js","assets/TemplateEditorDialog-B4Sy_l9D.js","assets/AgentTemplates-CRZnctM5.js","assets/TheLocalMoveHome-B7M8XF5y.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-BP2o66FP.js"])))=>i.map(i=>d[i]); var Dkt=Object.defineProperty;var uRe=s=>{throw TypeError(s)};var Rkt=(s,t,r)=>t in s?Dkt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r;var _a=(s,t,r)=>Rkt(s,typeof t!="symbol"?t+"":t,r),$1e=(s,t,r)=>t.has(s)||uRe("Cannot "+r);var Vs=(s,t,r)=>($1e(s,t,"read from private field"),r?r.call(s):t.get(s)),Mi=(s,t,r)=>t.has(s)?uRe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,r),Da=(s,t,r,n)=>($1e(s,t,"write to private field"),n?n.call(s,r):t.set(s,r),r),Lo=(s,t,r)=>($1e(s,t,"access private method"),r);var AU=(s,t,r,n)=>({set _(a){Da(s,t,a,r)},get _(){return Vs(s,t,n)}});function Okt(s,t){for(var r=0;rn[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();const Fkt="modulepreload",zkt=function(s){return"/"+s},hRe={},vi=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(r.map(c=>{if(c=zkt(c),c in hRe)return;hRe[c]=!0;const d=c.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":Fkt,d||(m.as="script"),m.crossOrigin="",m.href=c,o&&m.setAttribute("nonce",o),document.head.appendChild(m),d)return new Promise((f,x)=>{m.addEventListener("load",f),m.addEventListener("error",()=>x(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 lh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function gl(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Bkt(s){if(s.__esModule)return s;var t=s.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(s).forEach(function(n){var a=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(r,n,a.get?a:{enumerable:!0,get:function(){return s[n]}})}),r}var xXe={exports:{}},rxe={},gXe={exports:{}},ul={};/** * @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 Yz=Symbol.for("react.element"),$kt=Symbol.for("react.portal"),Ukt=Symbol.for("react.fragment"),qkt=Symbol.for("react.strict_mode"),Vkt=Symbol.for("react.profiler"),Hkt=Symbol.for("react.provider"),Gkt=Symbol.for("react.context"),Wkt=Symbol.for("react.forward_ref"),Kkt=Symbol.for("react.suspense"),Ykt=Symbol.for("react.memo"),Zkt=Symbol.for("react.lazy"),mRe=Symbol.iterator;function Xkt(s){return s===null||typeof s!="object"?null:(s=mRe&&s[mRe]||s["@@iterator"],typeof s=="function"?s:null)}var yXe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},vXe=Object.assign,bXe={};function c8(s,t,r){this.props=s,this.context=t,this.refs=bXe,this.updater=r||yXe}c8.prototype.isReactComponent={};c8.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")};c8.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function _Xe(){}_Xe.prototype=c8.prototype;function d3e(s,t,r){this.props=s,this.context=t,this.refs=bXe,this.updater=r||yXe}var u3e=d3e.prototype=new _Xe;u3e.constructor=d3e;vXe(u3e,c8.prototype);u3e.isPureReactComponent=!0;var fRe=Array.isArray,wXe=Object.prototype.hasOwnProperty,h3e={current:null},jXe={key:!0,ref:!0,__self:!0,__source:!0};function NXe(s,t,r){var n,a={},i=null,l=null;if(t!=null)for(n in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)wXe.call(t,n)&&!jXe.hasOwnProperty(n)&&(a[n]=t[n]);var o=arguments.length-2;if(o===1)a.children=r;else if(1>>1,je=ue[fe];if(0>>1;fea(Me,de))Oea(Ie,Me)?(ue[fe]=Ie,ue[Oe]=de,fe=Oe):(ue[fe]=Me,ue[Ee]=de,fe=Ee);else if(Oea(Ie,de))ue[fe]=Ie,ue[Oe]=de,fe=Oe;else break e}}return me}function a(ue,me){var de=ue.sortIndex-me.sortIndex;return de!==0?de:ue.id-me.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,m=null,f=3,x=!1,y=!1,_=!1,b=typeof setTimeout=="function"?setTimeout:null,j=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(ue){for(var me=r(d);me!==null;){if(me.callback===null)n(d);else if(me.startTime<=ue)n(d),me.sortIndex=me.expirationTime,t(c,me);else break;me=r(d)}}function A(ue){if(_=!1,C(ue),!y)if(r(c)!==null)y=!0,ne(E);else{var me=r(d);me!==null&&ae(A,me.startTime-ue)}}function E(ue,me){y=!1,_&&(_=!1,j(F),F=-1),x=!0;var de=f;try{for(C(me),m=r(c);m!==null&&(!(m.expirationTime>me)||ue&&!K());){var fe=m.callback;if(typeof fe=="function"){m.callback=null,f=m.priorityLevel;var je=fe(m.expirationTime<=me);me=s.unstable_now(),typeof je=="function"?m.callback=je:m===r(c)&&n(c),C(me)}else n(c);m=r(c)}if(m!==null)var xe=!0;else{var Ee=r(d);Ee!==null&&ae(A,Ee.startTime-me),xe=!1}return xe}finally{m=null,f=de,x=!1}}var D=!1,R=null,F=-1,O=5,B=-1;function K(){return!(s.unstable_now()-Bue||125fe?(ue.sortIndex=de,t(d,ue),r(c)===null&&ue===r(d)&&(_?(j(F),F=-1):_=!0,ae(A,de-fe))):(ue.sortIndex=je,t(c,ue),y||x||(y=!0,ne(E))),ue},s.unstable_shouldYield=K,s.unstable_wrapCallback=function(ue){var me=f;return function(){var de=f;f=me;try{return ue.apply(this,arguments)}finally{f=de}}}})(EXe);TXe.exports=EXe;var QO=TXe.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 lSt=k,F0=QO;function $n(s){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+s,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),r2e=Object.prototype.hasOwnProperty,cSt=/^[: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]*$/,xRe={},gRe={};function dSt(s){return r2e.call(gRe,s)?!0:r2e.call(xRe,s)?!1:cSt.test(s)?gRe[s]=!0:(xRe[s]=!0,!1)}function uSt(s,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function hSt(s,t,r,n){if(t===null||typeof t>"u"||uSt(s,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Lx(s,t,r,n,a,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=s,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var Jf={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){Jf[s]=new Lx(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];Jf[t]=new Lx(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){Jf[s]=new Lx(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){Jf[s]=new Lx(s,2,!1,s,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(s){Jf[s]=new Lx(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){Jf[s]=new Lx(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){Jf[s]=new Lx(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){Jf[s]=new Lx(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){Jf[s]=new Lx(s,5,!1,s.toLowerCase(),null,!1,!1)});var p3e=/[\-:]([a-z])/g;function x3e(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(p3e,x3e);Jf[t]=new Lx(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(p3e,x3e);Jf[t]=new Lx(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(p3e,x3e);Jf[t]=new Lx(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){Jf[s]=new Lx(s,1,!1,s.toLowerCase(),null,!1,!1)});Jf.xlinkHref=new Lx("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){Jf[s]=new Lx(s,1,!1,s.toLowerCase(),null,!0,!0)});function g3e(s,t,r,n){var a=Jf.hasOwnProperty(t)?Jf[t]:null;(a!==null?a.type!==0:n||!(2o||a[l]!==i[o]){var c=` `+a[l].replace(" at new "," at ");return s.displayName&&c.includes("")&&(c=c.replace("",s.displayName)),c}while(1<=l&&0<=o);break}}}finally{V1e=!1,Error.prepareStackTrace=r}return(s=s?s.displayName||s.name:"")?jO(s):""}function mSt(s){switch(s.tag){case 5:return jO(s.type);case 16:return jO("Lazy");case 13:return jO("Suspense");case 19:return jO("SuspenseList");case 0:case 2:case 15:return s=H1e(s.type,!1),s;case 11:return s=H1e(s.type.render,!1),s;case 1:return s=H1e(s.type,!0),s;default:return""}}function o2e(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 lI:return"Fragment";case oI:return"Portal";case n2e:return"Profiler";case y3e:return"StrictMode";case a2e:return"Suspense";case i2e:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case IXe:return(s.displayName||"Context")+".Consumer";case MXe:return(s._context.displayName||"Context")+".Provider";case v3e:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case b3e:return t=s.displayName||null,t!==null?t:o2e(s.type)||"Memo";case tk:t=s._payload,s=s._init;try{return o2e(s(t))}catch{}}return null}function fSt(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 o2e(t);case 8:return t===y3e?"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 CS(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function LXe(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function pSt(s){var t=LXe(s)?"checked":"value",r=Object.getOwnPropertyDescriptor(s.constructor.prototype,t),n=""+s[t];if(!s.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var a=r.get,i=r.set;return Object.defineProperty(s,t,{configurable:!0,get:function(){return a.call(this)},set:function(l){n=""+l,i.call(this,l)}}),Object.defineProperty(s,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(l){n=""+l},stopTracking:function(){s._valueTracker=null,delete s[t]}}}}function PU(s){s._valueTracker||(s._valueTracker=pSt(s))}function DXe(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return s&&(n=LXe(s)?s.checked?"true":"false":s.value),s=n,s!==r?(t.setValue(s),!0):!1}function _he(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 l2e(s,t){var r=t.checked;return vu({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??s._wrapperState.initialChecked})}function vRe(s,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=CS(t.value!=null?t.value:r),s._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function RXe(s,t){t=t.checked,t!=null&&g3e(s,"checked",t,!1)}function c2e(s,t){RXe(s,t);var r=CS(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&s.value===""||s.value!=r)&&(s.value=""+r):s.value!==""+r&&(s.value=""+r);else if(n==="submit"||n==="reset"){s.removeAttribute("value");return}t.hasOwnProperty("value")?d2e(s,t.type,r):t.hasOwnProperty("defaultValue")&&d2e(s,t.type,CS(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function bRe(s,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+s._wrapperState.initialValue,r||t===s.value||(s.value=t),s.defaultValue=t}r=s.name,r!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,r!==""&&(s.name=r)}function d2e(s,t,r){(t!=="number"||_he(s.ownerDocument)!==s)&&(r==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+r&&(s.defaultValue=""+r))}var NO=Array.isArray;function OI(s,t,r,n){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=LU.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function e9(s,t){if(t){var r=s.firstChild;if(r&&r===s.lastChild&&r.nodeType===3){r.nodeValue=t;return}}s.textContent=t}var JO={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},xSt=["Webkit","ms","Moz","O"];Object.keys(JO).forEach(function(s){xSt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),JO[t]=JO[s]})});function BXe(s,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||JO.hasOwnProperty(s)&&JO[s]?(""+t).trim():t+"px"}function $Xe(s,t){s=s.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,a=BXe(r,t[r],n);r==="float"&&(r="cssFloat"),n?s.setProperty(r,a):s[r]=a}}var gSt=vu({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 m2e(s,t){if(t){if(gSt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error($n(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error($n(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error($n(61))}if(t.style!=null&&typeof t.style!="object")throw Error($n(62))}}function f2e(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 p2e=null;function _3e(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var x2e=null,FI=null,zI=null;function jRe(s){if(s=Qz(s)){if(typeof x2e!="function")throw Error($n(280));var t=s.stateNode;t&&(t=lxe(t),x2e(s.stateNode,s.type,t))}}function UXe(s){FI?zI?zI.push(s):zI=[s]:FI=s}function qXe(){if(FI){var s=FI,t=zI;if(zI=FI=null,jRe(s),t)for(s=0;s>>=0,s===0?32:31-(TSt(s)/ESt|0)|0}var DU=64,RU=4194304;function kO(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 khe(s,t){var r=s.pendingLanes;if(r===0)return 0;var n=0,a=s.suspendedLanes,i=s.pingedLanes,l=r&268435455;if(l!==0){var o=l&~a;o!==0?n=kO(o):(i&=l,i!==0&&(n=kO(i)))}else l=r&~a,l!==0?n=kO(l):i!==0&&(n=kO(i));if(n===0)return 0;if(t!==0&&t!==n&&!(t&a)&&(a=n&-n,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(n&4&&(n|=r&16),t=s.entangledLanes,t!==0)for(s=s.entanglements,t&=n;0r;r++)t.push(s);return t}function Zz(s,t,r){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-j1(t),s[t]=r}function PSt(s,t){var r=s.pendingLanes&~t;s.pendingLanes=t,s.suspendedLanes=0,s.pingedLanes=0,s.expiredLanes&=t,s.mutableReadLanes&=t,s.entangledLanes&=t,t=s.entanglements;var n=s.eventTimes;for(s=s.expirationTimes;0=tF),IRe=" ",PRe=!1;function cQe(s,t){switch(s){case"keyup":return o4t.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dQe(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var cI=!1;function c4t(s,t){switch(s){case"compositionend":return dQe(t);case"keypress":return t.which!==32?null:(PRe=!0,IRe);case"textInput":return s=t.data,s===IRe&&PRe?null:s;default:return null}}function d4t(s,t){if(cI)return s==="compositionend"||!E3e&&cQe(s,t)?(s=oQe(),aH=S3e=Lk=null,cI=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:r,offset:t-s};s=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=ORe(r)}}function fQe(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?fQe(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function pQe(){for(var s=window,t=_he();t instanceof s.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)s=t.contentWindow;else break;t=_he(s.document)}return t}function A3e(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 v4t(s){var t=pQe(),r=s.focusedElem,n=s.selectionRange;if(t!==r&&r&&r.ownerDocument&&fQe(r.ownerDocument.documentElement,r)){if(n!==null&&A3e(r)){if(t=n.start,s=n.end,s===void 0&&(s=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(s,r.value.length);else if(s=(t=r.ownerDocument||document)&&t.defaultView||window,s.getSelection){s=s.getSelection();var a=r.textContent.length,i=Math.min(n.start,a);n=n.end===void 0?i:Math.min(n.end,a),!s.extend&&i>n&&(a=n,n=i,i=a),a=FRe(r,i);var l=FRe(r,n);a&&l&&(s.rangeCount!==1||s.anchorNode!==a.node||s.anchorOffset!==a.offset||s.focusNode!==l.node||s.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),s.removeAllRanges(),i>n?(s.addRange(t),s.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),s.addRange(t)))}}for(t=[],s=r;s=s.parentNode;)s.nodeType===1&&t.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,dI=null,w2e=null,rF=null,j2e=!1;function zRe(s,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;j2e||dI==null||dI!==_he(n)||(n=dI,"selectionStart"in n&&A3e(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),rF&&i9(rF,n)||(rF=n,n=The(w2e,"onSelect"),0mI||(s.current=E2e[mI],E2e[mI]=null,mI--)}function id(s,t){mI++,E2e[mI]=s.current,s.current=t}var TS={},Ap=HS(TS),hg=HS(!1),dA=TS;function JP(s,t){var r=s.type.contextTypes;if(!r)return TS;var n=s.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in r)a[i]=t[i];return n&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=t,s.__reactInternalMemoizedMaskedChildContext=a),a}function mg(s){return s=s.childContextTypes,s!=null}function Ahe(){kd(hg),kd(Ap)}function GRe(s,t,r){if(Ap.current!==TS)throw Error($n(168));id(Ap,t),id(hg,r)}function NQe(s,t,r){var n=s.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var a in n)if(!(a in t))throw Error($n(108,fSt(s)||"Unknown",a));return vu({},r,n)}function Mhe(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||TS,dA=Ap.current,id(Ap,s),id(hg,hg.current),!0}function WRe(s,t,r){var n=s.stateNode;if(!n)throw Error($n(169));r?(s=NQe(s,t,dA),n.__reactInternalMemoizedMergedChildContext=s,kd(hg),kd(Ap),id(Ap,s)):kd(hg),id(hg,r)}var Dj=null,cxe=!1,abe=!1;function kQe(s){Dj===null?Dj=[s]:Dj.push(s)}function M4t(s){cxe=!0,kQe(s)}function GS(){if(!abe&&Dj!==null){abe=!0;var s=0,t=xc;try{var r=Dj;for(xc=1;s>=l,a-=l,Vj=1<<32-j1(t)+a|r<F?(O=R,R=null):O=R.sibling;var B=f(j,R,C[F],A);if(B===null){R===null&&(R=O);break}s&&R&&B.alternate===null&&t(j,R),N=i(B,N,F),D===null?E=B:D.sibling=B,D=B,R=O}if(F===C.length)return r(j,R),Vd&&jC(j,F),E;if(R===null){for(;FF?(O=R,R=null):O=R.sibling;var K=f(j,R,B.value,A);if(K===null){R===null&&(R=O);break}s&&R&&K.alternate===null&&t(j,R),N=i(K,N,F),D===null?E=K:D.sibling=K,D=K,R=O}if(B.done)return r(j,R),Vd&&jC(j,F),E;if(R===null){for(;!B.done;F++,B=C.next())B=m(j,B.value,A),B!==null&&(N=i(B,N,F),D===null?E=B:D.sibling=B,D=B);return Vd&&jC(j,F),E}for(R=n(j,R);!B.done;F++,B=C.next())B=x(R,j,F,B.value,A),B!==null&&(s&&B.alternate!==null&&R.delete(B.key===null?F:B.key),N=i(B,N,F),D===null?E=B:D.sibling=B,D=B);return s&&R.forEach(function(Z){return t(j,Z)}),Vd&&jC(j,F),E}function b(j,N,C,A){if(typeof C=="object"&&C!==null&&C.type===lI&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case IU:e:{for(var E=C.key,D=N;D!==null;){if(D.key===E){if(E=C.type,E===lI){if(D.tag===7){r(j,D.sibling),N=a(D,C.props.children),N.return=j,j=N;break e}}else if(D.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===tk&&ZRe(E)===D.type){r(j,D.sibling),N=a(D,C.props),N.ref=TR(j,D,C),N.return=j,j=N;break e}r(j,D);break}else t(j,D);D=D.sibling}C.type===lI?(N=wE(C.props.children,j.mode,A,C.key),N.return=j,j=N):(A=mH(C.type,C.key,C.props,null,j.mode,A),A.ref=TR(j,N,C),A.return=j,j=A)}return l(j);case oI:e:{for(D=C.key;N!==null;){if(N.key===D)if(N.tag===4&&N.stateNode.containerInfo===C.containerInfo&&N.stateNode.implementation===C.implementation){r(j,N.sibling),N=a(N,C.children||[]),N.return=j,j=N;break e}else{r(j,N);break}else t(j,N);N=N.sibling}N=mbe(C,j.mode,A),N.return=j,j=N}return l(j);case tk:return D=C._init,b(j,N,D(C._payload),A)}if(NO(C))return y(j,N,C,A);if(jR(C))return _(j,N,C,A);qU(j,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,N!==null&&N.tag===6?(r(j,N.sibling),N=a(N,C),N.return=j,j=N):(r(j,N),N=hbe(C,j.mode,A),N.return=j,j=N),l(j)):r(j,N)}return b}var tL=EQe(!0),AQe=EQe(!1),Lhe=HS(null),Dhe=null,xI=null,L3e=null;function D3e(){L3e=xI=Dhe=null}function R3e(s){var t=Lhe.current;kd(Lhe),s._currentValue=t}function I2e(s,t,r){for(;s!==null;){var n=s.alternate;if((s.childLanes&t)!==t?(s.childLanes|=t,n!==null&&(n.childLanes|=t)):n!==null&&(n.childLanes&t)!==t&&(n.childLanes|=t),s===r)break;s=s.return}}function $I(s,t){Dhe=s,L3e=xI=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(og=!0),s.firstContext=null)}function iv(s){var t=s._currentValue;if(L3e!==s)if(s={context:s,memoizedValue:t,next:null},xI===null){if(Dhe===null)throw Error($n(308));xI=s,Dhe.dependencies={lanes:0,firstContext:s}}else xI=xI.next=s;return t}var GT=null;function O3e(s){GT===null?GT=[s]:GT.push(s)}function MQe(s,t,r,n){var a=t.interleaved;return a===null?(r.next=r,O3e(t)):(r.next=a.next,a.next=r),t.interleaved=r,w2(s,n)}function w2(s,t){s.lanes|=t;var r=s.alternate;for(r!==null&&(r.lanes|=t),r=s,s=s.return;s!==null;)s.childLanes|=t,r=s.alternate,r!==null&&(r.childLanes|=t),r=s,s=s.return;return r.tag===3?r.stateNode:null}var sk=!1;function F3e(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function IQe(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 Qj(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function Kk(s,t,r){var n=s.updateQueue;if(n===null)return null;if(n=n.shared,Ol&2){var a=n.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),n.pending=t,w2(s,r)}return a=n.interleaved,a===null?(t.next=t,O3e(n)):(t.next=a.next,a.next=t),n.interleaved=t,w2(s,r)}function oH(s,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var n=t.lanes;n&=s.pendingLanes,r|=n,t.lanes=r,j3e(s,r)}}function XRe(s,t){var r=s.updateQueue,n=s.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var a=null,i=null;if(r=r.firstBaseUpdate,r!==null){do{var l={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};i===null?a=i=l:i=i.next=l,r=r.next}while(r!==null);i===null?a=i=t:i=i.next=t}else a=i=t;r={baseState:n.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:n.shared,effects:n.effects},s.updateQueue=r;return}s=r.lastBaseUpdate,s===null?r.firstBaseUpdate=t:s.next=t,r.lastBaseUpdate=t}function Rhe(s,t,r,n){var a=s.updateQueue;sk=!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 m=a.baseState;l=0,u=d=c=null,o=i;do{var f=o.lane,x=o.eventTime;if((n&f)===f){u!==null&&(u=u.next={eventTime:x,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var y=s,_=o;switch(f=t,x=r,_.tag){case 1:if(y=_.payload,typeof y=="function"){m=y.call(x,m,f);break e}m=y;break e;case 3:y.flags=y.flags&-65537|128;case 0:if(y=_.payload,f=typeof y=="function"?y.call(x,m,f):y,f==null)break e;m=vu({},m,f);break e;case 2:sk=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,f=a.effects,f===null?a.effects=[o]:f.push(o))}else x={eventTime:x,lane:f,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=x,c=m):u=u.next=x,l|=f;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;f=o,o=f.next,f.next=null,a.lastBaseUpdate=f,a.shared.pending=null}}while(!0);if(u===null&&(c=m),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);mA|=l,s.lanes=l,s.memoizedState=m}}function QRe(s,t,r){if(s=t.effects,t.effects=null,s!==null)for(t=0;tr?r:4,s(!0);var n=obe.transition;obe.transition={};try{s(!1),t()}finally{xc=r,obe.transition=n}}function YQe(){return ov().memoizedState}function D4t(s,t,r){var n=Zk(s);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},ZQe(s))XQe(t,r);else if(r=MQe(s,t,r,n),r!==null){var a=Tx();N1(r,s,n,a),QQe(r,t,n)}}function R4t(s,t,r){var n=Zk(s),a={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(ZQe(s))XQe(t,a);else{var i=s.alternate;if(s.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,o=i(l,r);if(a.hasEagerState=!0,a.eagerState=o,D1(o,l)){var c=t.interleaved;c===null?(a.next=a,O3e(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}r=MQe(s,t,a,n),r!==null&&(a=Tx(),N1(r,s,n,a),QQe(r,t,n))}}function ZQe(s){var t=s.alternate;return s===pu||t!==null&&t===pu}function XQe(s,t){nF=Fhe=!0;var r=s.pending;r===null?t.next=t:(t.next=r.next,r.next=t),s.pending=t}function QQe(s,t,r){if(r&4194240){var n=t.lanes;n&=s.pendingLanes,r|=n,t.lanes=r,j3e(s,r)}}var zhe={readContext:iv,useCallback:yp,useContext:yp,useEffect:yp,useImperativeHandle:yp,useInsertionEffect:yp,useLayoutEffect:yp,useMemo:yp,useReducer:yp,useRef:yp,useState:yp,useDebugValue:yp,useDeferredValue:yp,useTransition:yp,useMutableSource:yp,useSyncExternalStore:yp,useId:yp,unstable_isNewReconciler:!1},O4t={readContext:iv,useCallback:function(s,t){return Vb().memoizedState=[s,t===void 0?null:t],s},useContext:iv,useEffect:eOe,useImperativeHandle:function(s,t,r){return r=r!=null?r.concat([s]):null,cH(4194308,4,VQe.bind(null,t,s),r)},useLayoutEffect:function(s,t){return cH(4194308,4,s,t)},useInsertionEffect:function(s,t){return cH(4,2,s,t)},useMemo:function(s,t){var r=Vb();return t=t===void 0?null:t,s=s(),r.memoizedState=[s,t],s},useReducer:function(s,t,r){var n=Vb();return t=r!==void 0?r(t):t,n.memoizedState=n.baseState=t,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:t},n.queue=s,s=s.dispatch=D4t.bind(null,pu,s),[n.memoizedState,s]},useRef:function(s){var t=Vb();return s={current:s},t.memoizedState=s},useState:JRe,useDebugValue:G3e,useDeferredValue:function(s){return Vb().memoizedState=s},useTransition:function(){var s=JRe(!1),t=s[0];return s=L4t.bind(null,s[1]),Vb().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,r){var n=pu,a=Vb();if(Vd){if(r===void 0)throw Error($n(407));r=r()}else{if(r=t(),af===null)throw Error($n(349));hA&30||RQe(n,t,r)}a.memoizedState=r;var i={value:r,getSnapshot:t};return a.queue=i,eOe(FQe.bind(null,n,i,s),[s]),n.flags|=2048,f9(9,OQe.bind(null,n,i,r,t),void 0,null),r},useId:function(){var s=Vb(),t=af.identifierPrefix;if(Vd){var r=Hj,n=Vj;r=(n&~(1<<32-j1(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=h9++,0<\/script>",s=s.removeChild(s.firstChild)):typeof n.is=="string"?s=l.createElement(r,{is:n.is}):(s=l.createElement(r),r==="select"&&(l=s,n.multiple?l.multiple=!0:n.size&&(l.size=n.size))):s=l.createElementNS(s,r),s[n_]=t,s[c9]=n,lJe(s,t,!1,!1),t.stateNode=s;e:{switch(l=f2e(r,n),r){case"dialog":bd("cancel",s),bd("close",s),a=n;break;case"iframe":case"object":case"embed":bd("load",s),a=n;break;case"video":case"audio":for(a=0;anL&&(t.flags|=128,n=!0,ER(i,!1),t.lanes=4194304)}else{if(!n)if(s=Ohe(l),s!==null){if(t.flags|=128,n=!0,r=s.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),ER(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Vd)return vp(t),null}else 2*ih()-i.renderingStartTime>nL&&r!==1073741824&&(t.flags|=128,n=!0,ER(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(r=i.last,r!==null?r.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=ih(),t.sibling=null,r=cu.current,id(cu,n?r&1|2:r&1),t):(vp(t),null);case 22:case 23:return Q3e(),n=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?u0&1073741824&&(vp(t),t.subtreeFlags&6&&(t.flags|=8192)):vp(t),null;case 24:return null;case 25:return null}throw Error($n(156,t.tag))}function H4t(s,t){switch(I3e(t),t.tag){case 1:return mg(t.type)&&Ahe(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return sL(),kd(hg),kd(Ap),$3e(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return B3e(t),null;case 13:if(kd(cu),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error($n(340));eL()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return kd(cu),null;case 4:return sL(),null;case 10:return R3e(t.type._context),null;case 22:case 23:return Q3e(),null;case 24:return null;default:return null}}var HU=!1,Np=!1,G4t=typeof WeakSet=="function"?WeakSet:Set,Ya=null;function gI(s,t){var r=s.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Ru(s,t,n)}else r.current=null}function $2e(s,t,r){try{r()}catch(n){Ru(s,t,n)}}var uOe=!1;function W4t(s,t){if(N2e=She,s=pQe(),A3e(s)){if("selectionStart"in s)var r={start:s.selectionStart,end:s.selectionEnd};else e:{r=(r=s.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var a=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{r.nodeType,i.nodeType}catch{r=null;break e}var l=0,o=-1,c=-1,d=0,u=0,m=s,f=null;t:for(;;){for(var x;m!==r||a!==0&&m.nodeType!==3||(o=l+a),m!==i||n!==0&&m.nodeType!==3||(c=l+n),m.nodeType===3&&(l+=m.nodeValue.length),(x=m.firstChild)!==null;)f=m,m=x;for(;;){if(m===s)break t;if(f===r&&++d===a&&(o=l),f===i&&++u===n&&(c=l),(x=m.nextSibling)!==null)break;m=f,f=m.parentNode}m=x}r=o===-1||c===-1?null:{start:o,end:c}}else r=null}r=r||{start:0,end:0}}else r=null;for(k2e={focusedElem:s,selectionRange:r},She=!1,Ya=t;Ya!==null;)if(t=Ya,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,Ya=s;else for(;Ya!==null;){t=Ya;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,b=y.memoizedState,j=t.stateNode,N=j.getSnapshotBeforeUpdate(t.elementType===t.type?_:a1(t.type,_),b);j.__reactInternalSnapshotBeforeUpdate=N}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error($n(163))}}catch(A){Ru(t,t.return,A)}if(s=t.sibling,s!==null){s.return=t.return,Ya=s;break}Ya=t.return}return y=uOe,uOe=!1,y}function aF(s,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var a=n=n.next;do{if((a.tag&s)===s){var i=a.destroy;a.destroy=void 0,i!==void 0&&$2e(t,r,i)}a=a.next}while(a!==n)}}function hxe(s,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&s)===s){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function U2e(s){var t=s.ref;if(t!==null){var r=s.stateNode;switch(s.tag){case 5:s=r;break;default:s=r}typeof t=="function"?t(s):t.current=s}}function uJe(s){var t=s.alternate;t!==null&&(s.alternate=null,uJe(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[n_],delete t[c9],delete t[T2e],delete t[E4t],delete t[A4t])),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 hJe(s){return s.tag===5||s.tag===3||s.tag===4}function hOe(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||hJe(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 q2e(s,t,r){var n=s.tag;if(n===5||n===6)s=s.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(s,t):r.insertBefore(s,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(s,r)):(t=r,t.appendChild(s)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=Ehe));else if(n!==4&&(s=s.child,s!==null))for(q2e(s,t,r),s=s.sibling;s!==null;)q2e(s,t,r),s=s.sibling}function V2e(s,t,r){var n=s.tag;if(n===5||n===6)s=s.stateNode,t?r.insertBefore(s,t):r.appendChild(s);else if(n!==4&&(s=s.child,s!==null))for(V2e(s,t,r),s=s.sibling;s!==null;)V2e(s,t,r),s=s.sibling}var Pf=null,l1=!1;function IN(s,t,r){for(r=r.child;r!==null;)mJe(s,t,r),r=r.sibling}function mJe(s,t,r){if(y_&&typeof y_.onCommitFiberUnmount=="function")try{y_.onCommitFiberUnmount(nxe,r)}catch{}switch(r.tag){case 5:Np||gI(r,t);case 6:var n=Pf,a=l1;Pf=null,IN(s,t,r),Pf=n,l1=a,Pf!==null&&(l1?(s=Pf,r=r.stateNode,s.nodeType===8?s.parentNode.removeChild(r):s.removeChild(r)):Pf.removeChild(r.stateNode));break;case 18:Pf!==null&&(l1?(s=Pf,r=r.stateNode,s.nodeType===8?nbe(s.parentNode,r):s.nodeType===1&&nbe(s,r),n9(s)):nbe(Pf,r.stateNode));break;case 4:n=Pf,a=l1,Pf=r.stateNode.containerInfo,l1=!0,IN(s,t,r),Pf=n,l1=a;break;case 0:case 11:case 14:case 15:if(!Np&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){a=n=n.next;do{var i=a,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&$2e(r,t,l),a=a.next}while(a!==n)}IN(s,t,r);break;case 1:if(!Np&&(gI(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(o){Ru(r,t,o)}IN(s,t,r);break;case 21:IN(s,t,r);break;case 22:r.mode&1?(Np=(n=Np)||r.memoizedState!==null,IN(s,t,r),Np=n):IN(s,t,r);break;default:IN(s,t,r)}}function mOe(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var r=s.stateNode;r===null&&(r=s.stateNode=new G4t),t.forEach(function(n){var a=sCt.bind(null,s,n);r.has(n)||(r.add(n),n.then(a,a))})}}function Zv(s,t){var r=t.deletions;if(r!==null)for(var n=0;na&&(a=l),n&=~i}if(n=a,n=ih()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*Y4t(n/1960))-n,10s?16:s,Dk===null)var n=!1;else{if(s=Dk,Dk=null,Uhe=0,Ol&6)throw Error($n(331));var a=Ol;for(Ol|=4,Ya=s.current;Ya!==null;){var i=Ya,l=i.child;if(Ya.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cih()-Z3e?_E(s,0):Y3e|=r),fg(s,t)}function _Je(s,t){t===0&&(s.mode&1?(t=RU,RU<<=1,!(RU&130023424)&&(RU=4194304)):t=1);var r=Tx();s=w2(s,t),s!==null&&(Zz(s,t,r),fg(s,r))}function tCt(s){var t=s.memoizedState,r=0;t!==null&&(r=t.retryLane),_Je(s,r)}function sCt(s,t){var r=0;switch(s.tag){case 13:var n=s.stateNode,a=s.memoizedState;a!==null&&(r=a.retryLane);break;case 19:n=s.stateNode;break;default:throw Error($n(314))}n!==null&&n.delete(t),_Je(s,r)}var wJe;wJe=function(s,t,r){if(s!==null)if(s.memoizedProps!==t.pendingProps||hg.current)og=!0;else{if(!(s.lanes&r)&&!(t.flags&128))return og=!1,q4t(s,t,r);og=!!(s.flags&131072)}else og=!1,Vd&&t.flags&1048576&&SQe(t,Phe,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;dH(s,t),s=t.pendingProps;var a=JP(t,Ap.current);$I(t,r),a=q3e(null,t,n,s,a,r);var i=V3e();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,mg(n)?(i=!0,Mhe(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,F3e(t),a.updater=uxe,t.stateNode=a,a._reactInternals=t,L2e(t,n,s,r),t=O2e(null,t,n,!0,i,r)):(t.tag=0,Vd&&i&&M3e(t),px(null,t,a,r),t=t.child),t;case 16:n=t.elementType;e:{switch(dH(s,t),s=t.pendingProps,a=n._init,n=a(n._payload),t.type=n,a=t.tag=nCt(n),s=a1(n,s),a){case 0:t=R2e(null,t,n,s,r);break e;case 1:t=lOe(null,t,n,s,r);break e;case 11:t=iOe(null,t,n,s,r);break e;case 14:t=oOe(null,t,n,a1(n.type,s),r);break e}throw Error($n(306,n,""))}return t;case 0:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:a1(n,a),R2e(s,t,n,a,r);case 1:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:a1(n,a),lOe(s,t,n,a,r);case 3:e:{if(aJe(t),s===null)throw Error($n(387));n=t.pendingProps,i=t.memoizedState,a=i.element,IQe(s,t),Rhe(t,n,null,r);var l=t.memoizedState;if(n=l.element,i.isDehydrated)if(i={element:n,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=rL(Error($n(423)),t),t=cOe(s,t,n,r,a);break e}else if(n!==a){a=rL(Error($n(424)),t),t=cOe(s,t,n,r,a);break e}else for(j0=Wk(t.stateNode.containerInfo.firstChild),N0=t,Vd=!0,f1=null,r=AQe(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(eL(),n===a){t=j2(s,t,r);break e}px(s,t,n,r)}t=t.child}return t;case 5:return PQe(t),s===null&&M2e(t),n=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,S2e(n,a)?l=null:i!==null&&S2e(n,i)&&(t.flags|=32),nJe(s,t),px(s,t,l,r),t.child;case 6:return s===null&&M2e(t),null;case 13:return iJe(s,t,r);case 4:return z3e(t,t.stateNode.containerInfo),n=t.pendingProps,s===null?t.child=tL(t,null,n,r):px(s,t,n,r),t.child;case 11:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:a1(n,a),iOe(s,t,n,a,r);case 7:return px(s,t,t.pendingProps,r),t.child;case 8:return px(s,t,t.pendingProps.children,r),t.child;case 12:return px(s,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=a.value,id(Lhe,n._currentValue),n._currentValue=l,i!==null)if(D1(i.value,l)){if(i.children===a.children&&!hg.current){t=j2(s,t,r);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){l=i.child;for(var c=o.firstContext;c!==null;){if(c.context===n){if(i.tag===1){c=Qj(-1,r&-r),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|=r,c=i.alternate,c!==null&&(c.lanes|=r),I2e(i.return,r,t),o.lanes|=r;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error($n(341));l.lanes|=r,o=l.alternate,o!==null&&(o.lanes|=r),I2e(l,r,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}px(s,t,a.children,r),t=t.child}return t;case 9:return a=t.type,n=t.pendingProps.children,$I(t,r),a=iv(a),n=n(a),t.flags|=1,px(s,t,n,r),t.child;case 14:return n=t.type,a=a1(n,t.pendingProps),a=a1(n.type,a),oOe(s,t,n,a,r);case 15:return sJe(s,t,t.type,t.pendingProps,r);case 17:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:a1(n,a),dH(s,t),t.tag=1,mg(n)?(s=!0,Mhe(t)):s=!1,$I(t,r),JQe(t,n,a),L2e(t,n,a,r),O2e(null,t,n,!0,s,r);case 19:return oJe(s,t,r);case 22:return rJe(s,t,r)}throw Error($n(156,t.tag))};function jJe(s,t){return ZXe(s,t)}function rCt(s,t,r,n){this.tag=s,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Hy(s,t,r,n){return new rCt(s,t,r,n)}function e5e(s){return s=s.prototype,!(!s||!s.isReactComponent)}function nCt(s){if(typeof s=="function")return e5e(s)?1:0;if(s!=null){if(s=s.$$typeof,s===v3e)return 11;if(s===b3e)return 14}return 2}function Xk(s,t){var r=s.alternate;return r===null?(r=Hy(s.tag,t,s.key,s.mode),r.elementType=s.elementType,r.type=s.type,r.stateNode=s.stateNode,r.alternate=s,s.alternate=r):(r.pendingProps=t,r.type=s.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=s.flags&14680064,r.childLanes=s.childLanes,r.lanes=s.lanes,r.child=s.child,r.memoizedProps=s.memoizedProps,r.memoizedState=s.memoizedState,r.updateQueue=s.updateQueue,t=s.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=s.sibling,r.index=s.index,r.ref=s.ref,r}function mH(s,t,r,n,a,i){var l=2;if(n=s,typeof s=="function")e5e(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case lI:return wE(r.children,a,i,t);case y3e:l=8,a|=8;break;case n2e:return s=Hy(12,r,t,a|2),s.elementType=n2e,s.lanes=i,s;case a2e:return s=Hy(13,r,t,a),s.elementType=a2e,s.lanes=i,s;case i2e:return s=Hy(19,r,t,a),s.elementType=i2e,s.lanes=i,s;case PXe:return fxe(r,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case MXe:l=10;break e;case IXe:l=9;break e;case v3e:l=11;break e;case b3e:l=14;break e;case tk:l=16,n=null;break e}throw Error($n(130,s==null?s:typeof s,""))}return t=Hy(l,r,t,a),t.elementType=s,t.type=n,t.lanes=i,t}function wE(s,t,r,n){return s=Hy(7,s,n,t),s.lanes=r,s}function fxe(s,t,r,n){return s=Hy(22,s,n,t),s.elementType=PXe,s.lanes=r,s.stateNode={isHidden:!1},s}function hbe(s,t,r){return s=Hy(6,s,null,t),s.lanes=r,s}function mbe(s,t,r){return t=Hy(4,s.children!==null?s.children:[],s.key,t),t.lanes=r,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function aCt(s,t,r,n,a){this.tag=t,this.containerInfo=s,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=W1e(0),this.expirationTimes=W1e(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=W1e(0),this.identifierPrefix=n,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function t5e(s,t,r,n,a,i,l,o,c){return s=new aCt(s,t,r,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Hy(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},F3e(i),s}function iCt(s,t,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(CJe)}catch(s){console.error(s)}}CJe(),CXe.exports=q0;var vx=CXe.exports;const a5e=gl(vx);var TJe,_Oe=vx;TJe=_Oe.createRoot,_Oe.hydrateRoot;const uCt=1,hCt=1e6;let fbe=0;function mCt(){return fbe=(fbe+1)%Number.MAX_SAFE_INTEGER,fbe.toString()}const pbe=new Map,wOe=s=>{if(pbe.has(s))return;const t=setTimeout(()=>{pbe.delete(s),lF({type:"REMOVE_TOAST",toastId:s})},hCt);pbe.set(s,t)},fCt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,uCt)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(r=>r.id===t.toast.id?{...r,...t.toast}:r)};case"DISMISS_TOAST":{const{toastId:r}=t;return r?wOe(r):s.toasts.forEach(n=>{wOe(n.id)}),{...s,toasts:s.toasts.map(n=>n.id===r||r===void 0?{...n,open:!1}:n)}}case"REMOVE_TOAST":return t.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(r=>r.id!==t.toastId)}}},fH=[];let pH={toasts:[]};function lF(s){pH=fCt(pH,s),fH.forEach(t=>{t(pH)})}function Dn({...s}){const t=mCt(),r=a=>lF({type:"UPDATE_TOAST",toast:{...a,id:t}}),n=()=>lF({type:"DISMISS_TOAST",toastId:t});return lF({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||n()}}}),{id:t,dismiss:n,update:r}}function Ba(){const[s,t]=k.useState(pH);return k.useEffect(()=>(fH.push(t),()=>{const r=fH.indexOf(t);r>-1&&fH.splice(r,1)}),[s]),{...s,toast:Dn,dismiss:r=>lF({type:"DISMISS_TOAST",toastId:r})}}function dn(s,t,{checkForDefaultPrevented:r=!0}={}){return function(a){if(s==null||s(a),r===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}function jOe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function N2(...s){return t=>{let r=!1;const n=s.map(a=>{const i=jOe(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a{const{children:l,...o}=i,c=k.useMemo(()=>o,Object.values(o));return e.jsx(r.Provider,{value:c,children:l})};n.displayName=s+"Provider";function a(i){const l=k.useContext(r);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${s}\``)}return[n,a]}function bu(s,t=[]){let r=[];function n(i,l){const o=k.createContext(l),c=r.length;r=[...r,l];const d=m=>{var j;const{scope:f,children:x,...y}=m,_=((j=f==null?void 0:f[s])==null?void 0:j[c])||o,b=k.useMemo(()=>y,Object.values(y));return e.jsx(_.Provider,{value:b,children:x})};d.displayName=i+"Provider";function u(m,f){var _;const x=((_=f==null?void 0:f[s])==null?void 0:_[c])||o,y=k.useContext(x);if(y)return y;if(l!==void 0)return l;throw new Error(`\`${m}\` must be used within \`${i}\``)}return[d,u]}const a=()=>{const i=r.map(l=>k.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return k.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[n,xCt(a,...t)]}function xCt(...s){const t=s[0];if(s.length===1)return t;const r=()=>{const n=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const l=n.reduce((o,{useScope:c,scopeName:d})=>{const m=c(i)[`__scope${d}`];return{...o,...m}},{});return k.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return r.scopeName=t.scopeName,r}function ES(s){const t=gCt(s),r=k.forwardRef((n,a)=>{const{children:i,...l}=n,o=k.Children.toArray(i),c=o.find(yCt);if(c){const d=c.props.children,u=o.map(m=>m===c?k.Children.count(d)>1?k.Children.only(null):k.isValidElement(d)?d.props.children:null:m);return e.jsx(t,{...l,ref:a,children:k.isValidElement(d)?k.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return r.displayName=`${s}.Slot`,r}var i5e=ES("Slot");function gCt(s){const t=k.forwardRef((r,n)=>{const{children:a,...i}=r;if(k.isValidElement(a)){const l=bCt(a),o=vCt(i,a.props);return a.type!==k.Fragment&&(o.ref=n?N2(n,l):l),k.cloneElement(a,o)}return k.Children.count(a)>1?k.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var EJe=Symbol("radix.slottable");function AJe(s){const t=({children:r})=>e.jsx(e.Fragment,{children:r});return t.displayName=`${s}.Slottable`,t.__radixId=EJe,t}function yCt(s){return k.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===EJe}function vCt(s,t){const r={...t};for(const n in t){const a=s[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const c=i(...o);return a(...o),c}:a&&(r[n]=a):n==="style"?r[n]={...a,...i}:n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return{...s,...r}}function bCt(s){var n,a;let t=(n=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?s.props.ref:s.props.ref||s.ref)}function eB(s){const t=s+"CollectionProvider",[r,n]=bu(t),[a,i]=r(t,{collectionRef:{current:null},itemMap:new Map}),l=_=>{const{scope:b,children:j}=_,N=Ct.useRef(null),C=Ct.useRef(new Map).current;return e.jsx(a,{scope:b,itemMap:C,collectionRef:N,children:j})};l.displayName=t;const o=s+"CollectionSlot",c=ES(o),d=Ct.forwardRef((_,b)=>{const{scope:j,children:N}=_,C=i(o,j),A=_i(b,C.collectionRef);return e.jsx(c,{ref:A,children:N})});d.displayName=o;const u=s+"CollectionItemSlot",m="data-radix-collection-item",f=ES(u),x=Ct.forwardRef((_,b)=>{const{scope:j,children:N,...C}=_,A=Ct.useRef(null),E=_i(b,A),D=i(u,j);return Ct.useEffect(()=>(D.itemMap.set(A,{ref:A,...C}),()=>void D.itemMap.delete(A))),e.jsx(f,{[m]:"",ref:E,children:N})});x.displayName=u;function y(_){const b=i(s+"CollectionConsumer",_);return Ct.useCallback(()=>{const N=b.collectionRef.current;if(!N)return[];const C=Array.from(N.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((D,R)=>C.indexOf(D.ref.current)-C.indexOf(R.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:l,Slot:d,ItemSlot:x},y,n]}var _Ct=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Yn=_Ct.reduce((s,t)=>{const r=ES(`Primitive.${t}`),n=k.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return n.displayName=`Primitive.${t}`,{...s,[t]:n}},{});function o5e(s,t){s&&vx.flushSync(()=>s.dispatchEvent(t))}function $u(s){const t=k.useRef(s);return k.useEffect(()=>{t.current=s}),k.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}function wCt(s,t=globalThis==null?void 0:globalThis.document){const r=$u(s);k.useEffect(()=>{const n=a=>{a.key==="Escape"&&r(a)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var jCt="DismissableLayer",Y2e="dismissableLayer.update",NCt="dismissableLayer.pointerDownOutside",kCt="dismissableLayer.focusOutside",NOe,MJe=k.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),WS=k.forwardRef((s,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=k.useContext(MJe),[u,m]=k.useState(null),f=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,x]=k.useState({}),y=_i(t,R=>m(R)),_=Array.from(d.layers),[b]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),j=_.indexOf(b),N=u?_.indexOf(u):-1,C=d.layersWithOutsidePointerEventsDisabled.size>0,A=N>=j,E=CCt(R=>{const F=R.target,O=[...d.branches].some(B=>B.contains(F));!A||O||(a==null||a(R),l==null||l(R),R.defaultPrevented||o==null||o())},f),D=TCt(R=>{const F=R.target;[...d.branches].some(B=>B.contains(F))||(i==null||i(R),l==null||l(R),R.defaultPrevented||o==null||o())},f);return wCt(R=>{N===d.layers.size-1&&(n==null||n(R),!R.defaultPrevented&&o&&(R.preventDefault(),o()))},f),k.useEffect(()=>{if(u)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(NOe=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),kOe(),()=>{r&&d.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=NOe)}},[u,f,r,d]),k.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),kOe())},[u,d]),k.useEffect(()=>{const R=()=>x({});return document.addEventListener(Y2e,R),()=>document.removeEventListener(Y2e,R)},[]),e.jsx(Yn.div,{...c,ref:y,style:{pointerEvents:C?A?"auto":"none":void 0,...s.style},onFocusCapture:dn(s.onFocusCapture,D.onFocusCapture),onBlurCapture:dn(s.onBlurCapture,D.onBlurCapture),onPointerDownCapture:dn(s.onPointerDownCapture,E.onPointerDownCapture)})});WS.displayName=jCt;var SCt="DismissableLayerBranch",IJe=k.forwardRef((s,t)=>{const r=k.useContext(MJe),n=k.useRef(null),a=_i(t,n);return k.useEffect(()=>{const i=n.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),e.jsx(Yn.div,{...s,ref:a})});IJe.displayName=SCt;function CCt(s,t=globalThis==null?void 0:globalThis.document){const r=$u(s),n=k.useRef(!1),a=k.useRef(()=>{});return k.useEffect(()=>{const i=o=>{if(o.target&&!n.current){let c=function(){PJe(NCt,r,d,{discrete:!0})};const d={originalEvent:o};o.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:!0})):c()}else t.removeEventListener("click",a.current);n.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}function TCt(s,t=globalThis==null?void 0:globalThis.document){const r=$u(s),n=k.useRef(!1);return k.useEffect(()=>{const a=i=>{i.target&&!n.current&&PJe(kCt,r,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function kOe(){const s=new CustomEvent(Y2e);document.dispatchEvent(s)}function PJe(s,t,r,{discrete:n}){const a=r.originalEvent.target,i=new CustomEvent(s,{bubbles:!1,cancelable:!0,detail:r});t&&a.addEventListener(s,t,{once:!0}),n?o5e(a,i):a.dispatchEvent(i)}var ECt=WS,ACt=IJe,Gu=globalThis!=null&&globalThis.document?k.useLayoutEffect:()=>{},MCt="Portal",h8=k.forwardRef((s,t)=>{var o;const{container:r,...n}=s,[a,i]=k.useState(!1);Gu(()=>i(!0),[]);const l=r||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?a5e.createPortal(e.jsx(Yn.div,{...n,ref:t}),l):null});h8.displayName=MCt;function ICt(s,t){return k.useReducer((r,n)=>t[r][n]??r,s)}var yh=s=>{const{present:t,children:r}=s,n=PCt(t),a=typeof r=="function"?r({present:n.isPresent}):k.Children.only(r),i=_i(n.ref,LCt(a));return typeof r=="function"||n.isPresent?k.cloneElement(a,{ref:i}):null};yh.displayName="Presence";function PCt(s){const[t,r]=k.useState(),n=k.useRef(null),a=k.useRef(s),i=k.useRef("none"),l=s?"mounted":"unmounted",[o,c]=ICt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return k.useEffect(()=>{const d=KU(n.current);i.current=o==="mounted"?d:"none"},[o]),Gu(()=>{const d=n.current,u=a.current;if(u!==s){const f=i.current,x=KU(d);s?c("MOUNT"):x==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&f!==x?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),Gu(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,m=x=>{const _=KU(n.current).includes(x.animationName);if(x.target===t&&_&&(c("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},f=x=>{x.target===t&&(i.current=KU(n.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",m),t.addEventListener("animationend",m),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",m),t.removeEventListener("animationend",m)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:k.useCallback(d=>{n.current=d?getComputedStyle(d):null,r(d)},[])}}function KU(s){return(s==null?void 0:s.animationName)||"none"}function LCt(s){var n,a;let t=(n=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?s.props.ref:s.props.ref||s.ref)}var DCt=f3e[" useInsertionEffect ".trim().toString()]||Gu;function df({prop:s,defaultProp:t,onChange:r=()=>{},caller:n}){const[a,i,l]=RCt({defaultProp:t,onChange:r}),o=s!==void 0,c=o?s:a;{const u=k.useRef(s!==void 0);k.useEffect(()=>{const m=u.current;m!==o&&console.warn(`${n} is changing from ${m?"controlled":"uncontrolled"} to ${o?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=o},[o,n])}const d=k.useCallback(u=>{var m;if(o){const f=OCt(u)?u(s):u;f!==s&&((m=l.current)==null||m.call(l,f))}else i(u)},[o,s,i,l]);return[c,d]}function RCt({defaultProp:s,onChange:t}){const[r,n]=k.useState(s),a=k.useRef(r),i=k.useRef(t);return DCt(()=>{i.current=t},[t]),k.useEffect(()=>{var l;a.current!==r&&((l=i.current)==null||l.call(i,r),a.current=r)},[r,a]),[r,n,i]}function OCt(s){return typeof s=="function"}var LJe=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"}),FCt="VisuallyHidden",vxe=k.forwardRef((s,t)=>e.jsx(Yn.span,{...s,ref:t,style:{...LJe,...s.style}}));vxe.displayName=FCt;var zCt=vxe,l5e="ToastProvider",[c5e,BCt,$Ct]=eB("Toast"),[DJe,fnr]=bu("Toast",[$Ct]),[UCt,bxe]=DJe(l5e),RJe=s=>{const{__scopeToast:t,label:r="Notification",duration:n=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=k.useState(null),[d,u]=k.useState(0),m=k.useRef(!1),f=k.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${l5e}\`. Expected non-empty \`string\`.`),e.jsx(c5e.Provider,{scope:t,children:e.jsx(UCt,{scope:t,label:r,duration:n,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:k.useCallback(()=>u(x=>x+1),[]),onToastRemove:k.useCallback(()=>u(x=>x-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:f,children:l})})};RJe.displayName=l5e;var OJe="ToastViewport",qCt=["F8"],Z2e="toast.viewportPause",X2e="toast.viewportResume",FJe=k.forwardRef((s,t)=>{const{__scopeToast:r,hotkey:n=qCt,label:a="Notifications ({hotkey})",...i}=s,l=bxe(OJe,r),o=BCt(r),c=k.useRef(null),d=k.useRef(null),u=k.useRef(null),m=k.useRef(null),f=_i(t,m,l.onViewportChange),x=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),y=l.toastCount>0;k.useEffect(()=>{const b=j=>{var C;n.length!==0&&n.every(A=>j[A]||j.code===A)&&((C=m.current)==null||C.focus())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[n]),k.useEffect(()=>{const b=c.current,j=m.current;if(y&&b&&j){const N=()=>{if(!l.isClosePausedRef.current){const D=new CustomEvent(Z2e);j.dispatchEvent(D),l.isClosePausedRef.current=!0}},C=()=>{if(l.isClosePausedRef.current){const D=new CustomEvent(X2e);j.dispatchEvent(D),l.isClosePausedRef.current=!1}},A=D=>{!b.contains(D.relatedTarget)&&C()},E=()=>{b.contains(document.activeElement)||C()};return b.addEventListener("focusin",N),b.addEventListener("focusout",A),b.addEventListener("pointermove",N),b.addEventListener("pointerleave",E),window.addEventListener("blur",N),window.addEventListener("focus",C),()=>{b.removeEventListener("focusin",N),b.removeEventListener("focusout",A),b.removeEventListener("pointermove",N),b.removeEventListener("pointerleave",E),window.removeEventListener("blur",N),window.removeEventListener("focus",C)}}},[y,l.isClosePausedRef]);const _=k.useCallback(({tabbingDirection:b})=>{const N=o().map(C=>{const A=C.ref.current,E=[A,...s3t(A)];return b==="forwards"?E:E.reverse()});return(b==="forwards"?N.reverse():N).flat()},[o]);return k.useEffect(()=>{const b=m.current;if(b){const j=N=>{var E,D,R;const C=N.altKey||N.ctrlKey||N.metaKey;if(N.key==="Tab"&&!C){const F=document.activeElement,O=N.shiftKey;if(N.target===b&&O){(E=d.current)==null||E.focus();return}const Z=_({tabbingDirection:O?"backwards":"forwards"}),Q=Z.findIndex(W=>W===F);xbe(Z.slice(Q+1))?N.preventDefault():O?(D=d.current)==null||D.focus():(R=u.current)==null||R.focus()}};return b.addEventListener("keydown",j),()=>b.removeEventListener("keydown",j)}},[o,_]),e.jsxs(ACt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",x),tabIndex:-1,style:{pointerEvents:y?void 0:"none"},children:[y&&e.jsx(Q2e,{ref:d,onFocusFromOutsideViewport:()=>{const b=_({tabbingDirection:"forwards"});xbe(b)}}),e.jsx(c5e.Slot,{scope:r,children:e.jsx(Yn.ol,{tabIndex:-1,...i,ref:f})}),y&&e.jsx(Q2e,{ref:u,onFocusFromOutsideViewport:()=>{const b=_({tabbingDirection:"backwards"});xbe(b)}})]})});FJe.displayName=OJe;var zJe="ToastFocusProxy",Q2e=k.forwardRef((s,t)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...a}=s,i=bxe(zJe,r);return e.jsx(vxe,{"aria-hidden":!0,tabIndex:0,...a,ref:t,style:{position:"fixed"},onFocus:l=>{var d;const o=l.relatedTarget;!((d=i.viewport)!=null&&d.contains(o))&&n()}})});Q2e.displayName=zJe;var tB="Toast",VCt="toast.swipeStart",HCt="toast.swipeMove",GCt="toast.swipeCancel",WCt="toast.swipeEnd",BJe=k.forwardRef((s,t)=>{const{forceMount:r,open:n,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=df({prop:n,defaultProp:a??!0,onChange:i,caller:tB});return e.jsx(yh,{present:r||o,children:e.jsx(ZCt,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:$u(s.onPause),onResume:$u(s.onResume),onSwipeStart:dn(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:dn(s.onSwipeMove,d=>{const{x:u,y:m}=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",`${m}px`)}),onSwipeCancel:dn(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:dn(s.onSwipeEnd,d=>{const{x:u,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),c(!1)})})})});BJe.displayName=tB;var[KCt,YCt]=DJe(tB,{onClose(){}}),ZCt=k.forwardRef((s,t)=>{const{__scopeToast:r,type:n="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:u,onSwipeMove:m,onSwipeCancel:f,onSwipeEnd:x,...y}=s,_=bxe(tB,r),[b,j]=k.useState(null),N=_i(t,W=>j(W)),C=k.useRef(null),A=k.useRef(null),E=a||_.duration,D=k.useRef(0),R=k.useRef(E),F=k.useRef(0),{onToastAdd:O,onToastRemove:B}=_,K=$u(()=>{var te;(b==null?void 0:b.contains(document.activeElement))&&((te=_.viewport)==null||te.focus()),l()}),Z=k.useCallback(W=>{!W||W===1/0||(window.clearTimeout(F.current),D.current=new Date().getTime(),F.current=window.setTimeout(K,W))},[K]);k.useEffect(()=>{const W=_.viewport;if(W){const te=()=>{Z(R.current),d==null||d()},ne=()=>{const ae=new Date().getTime()-D.current;R.current=R.current-ae,window.clearTimeout(F.current),c==null||c()};return W.addEventListener(Z2e,ne),W.addEventListener(X2e,te),()=>{W.removeEventListener(Z2e,ne),W.removeEventListener(X2e,te)}}},[_.viewport,E,c,d,Z]),k.useEffect(()=>{i&&!_.isClosePausedRef.current&&Z(E)},[i,E,_.isClosePausedRef,Z]),k.useEffect(()=>(O(),()=>B()),[O,B]);const Q=k.useMemo(()=>b?WJe(b):null,[b]);return _.viewport?e.jsxs(e.Fragment,{children:[Q&&e.jsx(XCt,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite","aria-atomic":!0,children:Q}),e.jsx(KCt,{scope:r,onClose:K,children:vx.createPortal(e.jsx(c5e.ItemSlot,{scope:r,children:e.jsx(ECt,{asChild:!0,onEscapeKeyDown:dn(o,()=>{_.isFocusedToastEscapeKeyDownRef.current||K(),_.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(Yn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection,...y,ref:N,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:dn(s.onKeyDown,W=>{W.key==="Escape"&&(o==null||o(W.nativeEvent),W.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,K()))}),onPointerDown:dn(s.onPointerDown,W=>{W.button===0&&(C.current={x:W.clientX,y:W.clientY})}),onPointerMove:dn(s.onPointerMove,W=>{if(!C.current)return;const te=W.clientX-C.current.x,ne=W.clientY-C.current.y,ae=!!A.current,ue=["left","right"].includes(_.swipeDirection),me=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,de=ue?me(0,te):0,fe=ue?0:me(0,ne),je=W.pointerType==="touch"?10:2,xe={x:de,y:fe},Ee={originalEvent:W,delta:xe};ae?(A.current=xe,YU(HCt,m,Ee,{discrete:!1})):SOe(xe,_.swipeDirection,je)?(A.current=xe,YU(VCt,u,Ee,{discrete:!1}),W.target.setPointerCapture(W.pointerId)):(Math.abs(te)>je||Math.abs(ne)>je)&&(C.current=null)}),onPointerUp:dn(s.onPointerUp,W=>{const te=A.current,ne=W.target;if(ne.hasPointerCapture(W.pointerId)&&ne.releasePointerCapture(W.pointerId),A.current=null,C.current=null,te){const ae=W.currentTarget,ue={originalEvent:W,delta:te};SOe(te,_.swipeDirection,_.swipeThreshold)?YU(WCt,x,ue,{discrete:!0}):YU(GCt,f,ue,{discrete:!0}),ae.addEventListener("click",me=>me.preventDefault(),{once:!0})}})})})}),_.viewport)})]}):null}),XCt=s=>{const{__scopeToast:t,children:r,...n}=s,a=bxe(tB,t),[i,l]=k.useState(!1),[o,c]=k.useState(!1);return e3t(()=>l(!0)),k.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(h8,{asChild:!0,children:e.jsx(vxe,{...n,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",r]})})})},QCt="ToastTitle",$Je=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s;return e.jsx(Yn.div,{...n,ref:t})});$Je.displayName=QCt;var JCt="ToastDescription",UJe=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s;return e.jsx(Yn.div,{...n,ref:t})});UJe.displayName=JCt;var qJe="ToastAction",VJe=k.forwardRef((s,t)=>{const{altText:r,...n}=s;return r.trim()?e.jsx(GJe,{altText:r,asChild:!0,children:e.jsx(d5e,{...n,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${qJe}\`. Expected non-empty \`string\`.`),null)});VJe.displayName=qJe;var HJe="ToastClose",d5e=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s,a=YCt(HJe,r);return e.jsx(GJe,{asChild:!0,children:e.jsx(Yn.button,{type:"button",...n,ref:t,onClick:dn(s.onClick,a.onClose)})})});d5e.displayName=HJe;var GJe=k.forwardRef((s,t)=>{const{__scopeToast:r,altText:n,...a}=s;return e.jsx(Yn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...a,ref:t})});function WJe(s){const t=[];return Array.from(s.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),t3t(n)){const a=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!a)if(i){const l=n.dataset.radixToastAnnounceAlt;l&&t.push(l)}else t.push(...WJe(n))}}),t}function YU(s,t,r,{discrete:n}){const a=r.originalEvent.currentTarget,i=new CustomEvent(s,{bubbles:!0,cancelable:!0,detail:r});t&&a.addEventListener(s,t,{once:!0}),n?o5e(a,i):a.dispatchEvent(i)}var SOe=(s,t,r=0)=>{const n=Math.abs(s.x),a=Math.abs(s.y),i=n>a;return t==="left"||t==="right"?i&&n>r:!i&&a>r};function e3t(s=()=>{}){const t=$u(s);Gu(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[t])}function t3t(s){return s.nodeType===s.ELEMENT_NODE}function s3t(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function xbe(s){const t=document.activeElement;return s.some(r=>r===t?!0:(r.focus(),document.activeElement!==t))}var r3t=RJe,KJe=FJe,YJe=BJe,ZJe=$Je,XJe=UJe,QJe=VJe,JJe=d5e;function eet(s){var t,r,n="";if(typeof s=="string"||typeof s=="number")n+=s;else if(typeof s=="object")if(Array.isArray(s)){var a=s.length;for(t=0;ttypeof s=="boolean"?`${s}`:s===0?"0":s,TOe=_o,WA=(s,t)=>r=>{var n;if((t==null?void 0:t.variants)==null)return TOe(s,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const u=r==null?void 0:r[d],m=i==null?void 0:i[d];if(u===null)return null;const f=COe(u)||COe(m);return a[d][f]}),o=r&&Object.entries(r).reduce((d,u)=>{let[m,f]=u;return f===void 0||(d[m]=f),d},{}),c=t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((d,u)=>{let{class:m,className:f,...x}=u;return Object.entries(x).every(y=>{let[_,b]=y;return Array.isArray(b)?b.includes({...i,...o}[_]):{...i,...o}[_]===b})?[...d,m,f]:d},[]);return TOe(s,l,c,r==null?void 0:r.class,r==null?void 0:r.className)};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n3t=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),tet=(...s)=>s.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim();/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var a3t={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 set=k.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:i,iconNode:l,...o},c)=>k.createElement("svg",{ref:c,...a3t,width:t,height:t,stroke:s,strokeWidth:n?Number(r)*24/Number(t):r,className:tet("lucide",a),...o},[...l.map(([d,u])=>k.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 se=(s,t)=>{const r=k.forwardRef(({className:n,...a},i)=>k.createElement(set,{ref:i,iconNode:t,className:tet(`lucide-${n3t(s)}`,n),...a}));return r.displayName=`${s}`,r};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xH=se("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 gH=se("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 yH=se("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 vH=se("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 xm=se("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 bH=se("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 _H=se("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 kC=se("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 SC=se("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 wH=se("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 CC=se("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 jH=se("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 NH=se("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 kH=se("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 SH=se("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 CH=se("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 jE=se("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 TH=se("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 EH=se("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 AH=se("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 MH=se("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 IH=se("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 PH=se("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 LH=se("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 DH=se("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 RH=se("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 OH=se("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 FH=se("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 NE=se("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 kE=se("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 zH=se("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 BH=se("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 $H=se("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 UH=se("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 qH=se("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 VH=se("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 HH=se("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 GH=se("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 WH=se("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 KH=se("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 YH=se("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 ZH=se("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 XH=se("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 QH=se("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 JH=se("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 eG=se("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 tG=se("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 sG=se("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 rG=se("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 nG=se("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 aG=se("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 iG=se("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 oG=se("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 qI=se("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 lG=se("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 Qk=se("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 cG=se("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 dG=se("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 uG=se("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 hG=se("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 mG=se("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 fG=se("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 pG=se("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 xG=se("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 gG=se("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 yG=se("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 vG=se("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 TC=se("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 bG=se("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 _G=se("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 wG=se("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 cF=se("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 jG=se("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 NG=se("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 kG=se("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 EC=se("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 AC=se("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 gm=se("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 SG=se("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 CG=se("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 TG=se("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 Aa=se("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 EG=se("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 Jj=se("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 AG=se("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 ci=se("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 MG=se("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 IG=se("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 MC=se("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 Uu=se("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 PG=se("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 LG=se("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 DG=se("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 IC=se("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 dF=se("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 RG=se("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 OG=se("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 PC=se("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 qu=se("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 FG=se("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 zG=se("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 BG=se("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 $G=se("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 UG=se("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 qG=se("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 Uc=se("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 VG=se("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 LC=se("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 HG=se("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 GG=se("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 WG=se("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 KG=se("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 DC=se("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 YG=se("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 ZG=se("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 XG=se("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 QG=se("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 JG=se("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 eW=se("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 tW=se("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 sW=se("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 rW=se("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 nW=se("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 aW=se("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 iW=se("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 oW=se("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 lW=se("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 cW=se("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 uF=se("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 dW=se("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 uW=se("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 hW=se("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 mW=se("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 fW=se("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 of=se("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 pW=se("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 xW=se("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 gW=se("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 yW=se("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 vW=se("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 bW=se("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 _W=se("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 wW=se("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 jW=se("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 e2=se("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 NW=se("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 k0=se("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 kW=se("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 SW=se("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 CW=se("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 TW=se("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 EW=se("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 AW=se("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 b_=se("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 MW=se("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 hF=se("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 ym=se("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 RC=se("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 OC=se("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 IW=se("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 PW=se("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 LW=se("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 DW=se("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 RW=se("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 OW=se("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 FW=se("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 zW=se("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 BW=se("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 $W=se("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 UW=se("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 qW=se("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 VW=se("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 HW=se("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 GW=se("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 WW=se("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 Jk=se("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 KW=se("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 YW=se("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 ZW=se("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 XW=se("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 QW=se("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 JW=se("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 eK=se("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 FC=se("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 tK=se("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 sK=se("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 rK=se("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 nK=se("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 aK=se("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 iK=se("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 oK=se("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 lK=se("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 cK=se("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 dK=se("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 vm=se("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 uK=se("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 hK=se("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 mK=se("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 fK=se("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 pK=se("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 xK=se("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 gK=se("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 yK=se("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 vK=se("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 bK=se("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 mF=se("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 _K=se("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 Zy=se("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 wK=se("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 jK=se("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 NK=se("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 eS=se("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 fF=se("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 kK=se("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 zC=se("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 SK=se("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 CK=se("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 TK=se("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 pF=se("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 EK=se("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 AK=se("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 MK=se("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 IK=se("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 bm=se("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 PK=se("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 LK=se("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 DK=se("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 RK=se("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 OK=se("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 Ga=se("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 SE=se("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 FK=se("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 zK=se("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 BK=se("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 $K=se("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 UK=se("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 _m=se("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 __=se("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 qK=se("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 VK=se("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 HK=se("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 GK=se("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 xF=se("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 Xy=se("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 WK=se("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 xu=se("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 KK=se("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 gF=se("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 YK=se("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 ZK=se("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 yF=se("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 XK=se("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 Gj=se("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 QK=se("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 JK=se("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 eY=se("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 tY=se("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 sY=se("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 vn=se("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 rY=se("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 Tp=se("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 nY=se("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 aY=se("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 iY=se("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 oY=se("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 lY=se("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 BC=se("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 cY=se("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 dY=se("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 uY=se("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 hY=se("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 mY=se("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 fY=se("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 pY=se("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 xY=se("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 gY=se("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 yY=se("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 vY=se("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 bY=se("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 _Y=se("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 $C=se("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 UC=se("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 wY=se("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 jY=se("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 NY=se("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 qC=se("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 VC=se("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 HC=se("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 kY=se("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 GC=se("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 SY=se("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 Mo=se("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 CY=se("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 WC=se("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 TY=se("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 EY=se("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 KC=se("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 YC=se("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 AY=se("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 ZC=se("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 XC=se("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 QC=se("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 MY=se("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 vF=se("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 la=se("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 IY=se("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 PY=se("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 Co=se("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 LY=se("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 DY=se("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 jl=se("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 Ia=se("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 pg=se("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 RY=se("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 OY=se("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 FY=se("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 zY=se("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 BY=se("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 $Y=se("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 UY=se("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 xg=se("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 qY=se("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 CE=se("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 VY=se("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 HY=se("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 GY=se("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 go=se("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 JC=se("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 e3=se("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 t3=se("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 s3=se("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 r3=se("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 n3=se("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 a3=se("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 i3=se("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 Ti=se("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 qn=se("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 o3=se("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 l3=se("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 c3=se("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 d3=se("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 WY=se("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 u3=se("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 KY=se("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 YY=se("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 ZY=se("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 XY=se("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 QY=se("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 JY=se("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 eZ=se("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 h3=se("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 e_=se("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 m3=se("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 tZ=se("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 f3=se("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 p3=se("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 x3=se("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 g3=se("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 Ff=se("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 y3=se("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 v3=se("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 b3=se("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 sZ=se("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 _3=se("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 w3=se("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 j3=se("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 ad=se("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 Rh=se("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 rZ=se("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 nZ=se("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 aZ=se("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 VI=se("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 iZ=se("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 k1=se("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 oZ=se("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 lZ=se("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 N3=se("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 k3=se("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 cZ=se("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 dZ=se("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 uZ=se("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 hZ=se("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 mZ=se("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 fZ=se("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 pZ=se("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 xZ=se("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 gZ=se("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 yZ=se("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 vZ=se("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 bZ=se("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 _Z=se("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 wZ=se("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 jZ=se("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 NZ=se("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 kZ=se("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 SZ=se("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 CZ=se("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 jn=se("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 TZ=se("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 EZ=se("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 S3=se("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 AZ=se("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 MZ=se("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 IZ=se("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 PZ=se("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 LZ=se("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 DZ=se("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 RZ=se("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 OZ=se("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 FZ=se("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 zZ=se("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 BZ=se("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 $Z=se("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 C3=se("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 UZ=se("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 qZ=se("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 Wj=se("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 VZ=se("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 Rj=se("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 TE=se("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 HZ=se("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 GZ=se("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 EE=se("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 WZ=se("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 bF=se("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 T3=se("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 E3=se("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 KZ=se("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 YZ=se("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 ZZ=se("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 HI=se("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 XZ=se("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 QZ=se("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 JZ=se("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 eX=se("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 tX=se("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 A3=se("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 AE=se("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 sX=se("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 rX=se("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 nX=se("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 aX=se("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 iX=se("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 oX=se("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 lX=se("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 cX=se("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 dX=se("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 si=se("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 uX=se("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 hX=se("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 mX=se("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 fX=se("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 pX=se("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 xX=se("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 gX=se("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 yX=se("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 vX=se("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 bX=se("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 _X=se("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 wX=se("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 S0=se("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 jX=se("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 NX=se("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 kX=se("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 SX=se("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 Gf=se("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 CX=se("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 TX=se("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 EX=se("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 AX=se("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 MX=se("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 IX=se("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 PX=se("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 _F=se("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 LX=se("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 DX=se("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 RX=se("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 OX=se("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 M3=se("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 FX=se("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 zX=se("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 BX=se("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 $X=se("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 UX=se("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 qX=se("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 VX=se("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 HX=se("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 GX=se("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 WX=se("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 KX=se("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 YX=se("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 ZX=se("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 XX=se("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 QX=se("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 JX=se("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 eQ=se("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 tQ=se("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 sQ=se("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 Xl=se("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 rQ=se("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 nQ=se("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 w_=se("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 aQ=se("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 li=se("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 iQ=se("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 oQ=se("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 lQ=se("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 cQ=se("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 dQ=se("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 S1=se("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 uQ=se("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 hQ=se("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 mQ=se("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 fQ=se("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 pQ=se("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 xQ=se("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 I3=se("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 gQ=se("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 yQ=se("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 vQ=se("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 GI=se("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 Fy=se("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 f0=se("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 bQ=se("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 _Q=se("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 wQ=se("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 jQ=se("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 NQ=se("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 kQ=se("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 SQ=se("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 un=se("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 CQ=se("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 Wf=se("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 Nn=se("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=se("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 TQ=se("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 EQ=se("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 AQ=se("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 MQ=se("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 IQ=se("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 PQ=se("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 LQ=se("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 DQ=se("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 RQ=se("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 OQ=se("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 P3=se("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 FQ=se("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 zQ=se("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 BQ=se("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 L3=se("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 D3=se("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 R3=se("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 O3=se("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 $Q=se("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 wF=se("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 UQ=se("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 qQ=se("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 VQ=se("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 F3=se("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 HQ=se("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 GQ=se("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 ME=se("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 WQ=se("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 t2=se("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 KQ=se("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 YQ=se("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 ZQ=se("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 XQ=se("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 QQ=se("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 JQ=se("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 eJ=se("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 tJ=se("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 sJ=se("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 rJ=se("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 nJ=se("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 z3=se("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 B3=se("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 aJ=se("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 iJ=se("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 oJ=se("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 lJ=se("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 cJ=se("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 dJ=se("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 uJ=se("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 s2=se("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 jF=se("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 hJ=se("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 mJ=se("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 En=se("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 fJ=se("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 pJ=se("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 xJ=se("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 gJ=se("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 yJ=se("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 NF=se("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 vJ=se("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 bJ=se("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 _J=se("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 wJ=se("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 jJ=se("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 WI=se("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 NJ=se("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 rf=se("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 kJ=se("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 C1=se("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 SJ=se("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 CJ=se("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 TJ=se("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 EJ=se("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 AJ=se("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 MJ=se("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 IJ=se("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 PJ=se("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 r2=se("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 LJ=se("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 ld=se("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 DJ=se("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 RJ=se("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 OJ=se("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 tS=se("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 FJ=se("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 zJ=se("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 kF=se("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 BJ=se("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 $J=se("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 b1=se("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 UJ=se("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 qJ=se("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 VJ=se("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 HJ=se("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 GJ=se("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 WJ=se("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 KJ=se("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 YJ=se("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 ZJ=se("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 $3=se("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 XJ=se("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 QJ=se("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 JJ=se("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 eee=se("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 tee=se("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 see=se("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 ree=se("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 nee=se("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 aee=se("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 iee=se("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 oee=se("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 Kf=se("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 lee=se("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 U3=se("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 cee=se("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 dee=se("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 uee=se("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 hee=se("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 mee=se("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 fee=se("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 pee=se("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 xee=se("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 gee=se("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 yee=se("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 vee=se("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 bee=se("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 _ee=se("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 wee=se("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 jee=se("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 Nee=se("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 kee=se("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 See=se("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 Cee=se("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 Tee=se("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 Eee=se("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 Aee=se("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 Mee=se("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 Iee=se("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 Pee=se("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 Lee=se("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 Dee=se("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 Ree=se("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 Oee=se("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 IE=se("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 Di=se("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 Fee=se("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 zee=se("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 q3=se("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 Bee=se("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 $ee=se("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 Uee=se("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 qee=se("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 Vee=se("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 Hee=se("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 Gee=se("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 Wee=se("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 Kee=se("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 Yee=se("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 Zee=se("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 Xee=se("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 Qee=se("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 Jee=se("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 ete=se("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 tte=se("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 ste=se("GlobeLock",[["path",{d:"M15.686 15A14.5 14.5 0 0 1 12 22a14.5 14.5 0 0 1 0-20 10 10 0 1 0 9.542 13",key:"qkt0x6"}],["path",{d:"M2 12h8.5",key:"ovaggd"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ql=se("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 rte=se("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 nte=se("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 ch=se("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 ate=se("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 ite=se("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 V3=se("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 ote=se("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 H3=se("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 Ey=se("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 lte=se("GripHorizontal",[["circle",{cx:"12",cy:"9",r:"1",key:"124mty"}],["circle",{cx:"19",cy:"9",r:"1",key:"1ruzo2"}],["circle",{cx:"5",cy:"9",r:"1",key:"1a8b28"}],["circle",{cx:"12",cy:"15",r:"1",key:"1e56xg"}],["circle",{cx:"19",cy:"15",r:"1",key:"1a92ep"}],["circle",{cx:"5",cy:"15",r:"1",key:"5r1jwy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vu=se("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 cte=se("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 dte=se("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 ute=se("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 hte=se("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 SF=se("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 mte=se("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 fte=se("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 p1=se("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 pte=se("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 xte=se("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 CF=se("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 j_=se("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 gte=se("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 yte=se("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 TF=se("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 vte=se("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 sS=se("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 bte=se("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 _te=se("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 KI=se("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 YI=se("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 EF=se("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 wte=se("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 jte=se("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 Nte=se("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 kte=se("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 Ste=se("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 Cte=se("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 Tte=se("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 Ete=se("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 Ate=se("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 Mte=se("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 Ite=se("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 yi=se("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 Pte=se("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 Lte=se("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 Dte=se("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 ZI=se("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 Rte=se("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 Ote=se("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 Fte=se("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 zte=se("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 Bte=se("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 $te=se("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 Ute=se("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 Pn=se("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 G3=se("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 W3=se("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 qte=se("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 Vte=se("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 Hte=se("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 Gte=se("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 Wte=se("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 Qy=se("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 Kte=se("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 Yte=se("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 zo=se("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 Zte=se("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 Xte=se("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 n2=se("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 K3=se("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 Y3=se("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 Qte=se("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 Jte=se("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 a2=se("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 ese=se("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 gu=se("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 rS=se("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 tse=se("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 sse=se("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 rse=se("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 nse=se("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 i2=se("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 PE=se("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 ase=se("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 gg=se("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 ise=se("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 ose=se("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 lse=se("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 cse=se("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 dse=se("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 use=se("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 hse=se("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 mse=se("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 fse=se("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 pse=se("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 xse=se("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 gse=se("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 yse=se("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 Z3=se("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 vse=se("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 bse=se("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 _se=se("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 wse=se("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 jse=se("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 Nse=se("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 AF=se("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 LE=se("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 Ep=se("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 kse=se("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 Sse=se("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 Cse=se("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 DE=se("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 Tse=se("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 Ese=se("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 Ase=se("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 Mse=se("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 Ise=se("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 nS=se("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 XI=se("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 Pse=se("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 Lse=se("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 o2=se("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 Dse=se("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 Ul=se("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 tl=se("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 Yf=se("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 Rse=se("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 l2=se("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 Ose=se("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 Fse=se("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 MF=se("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 zse=se("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 Bse=se("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 T1=se("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 $se=se("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 Use=se("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 qse=se("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 Vse=se("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 Hse=se("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 Gse=se("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 Wse=se("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 Zf=se("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 ls=se("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 Kse=se("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 Yse=se("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 Zse=se("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 Xse=se("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 QI=se("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 X3=se("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 Qse=se("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 Q3=se("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=se("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 RE=se("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 OE=se("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 Jse=se("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 ere=se("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 tre=se("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 sre=se("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 JI=se("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 rre=se("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 IF=se("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 PF=se("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 nre=se("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 are=se("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 ire=se("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 eP=se("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 Ks=se("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 ore=se("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 lre=se("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 cre=se("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 dre=se("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 ure=se("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 hre=se("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 mre=se("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 fre=se("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 pre=se("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 xre=se("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 gre=se("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 yre=se("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 Ma=se("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 vre=se("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 FE=se("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 bre=se("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 LF=se("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 zE=se("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 c2=se("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 _re=se("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 fh=se("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 wre=se("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 jre=se("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 aS=se("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 Nre=se("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 kre=se("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 Sre=se("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 tP=se("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 Cre=se("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 Tre=se("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 Ere=se("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 DF=se("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 Are=se("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 Mre=se("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 Ire=se("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 gc=se("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 Pre=se("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 Lre=se("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 Dre=se("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 Rre=se("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 Ore=se("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 Fre=se("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 RF=se("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 zre=se("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 c_=se("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 sP=se("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 Bre=se("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 $re=se("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 Ure=se("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 qre=se("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 Vre=se("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 Ui=se("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 Hre=se("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 Gre=se("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 J3=se("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 BE=se("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 Wre=se("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 Kre=se("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 Yre=se("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 Zre=se("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 Xre=se("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 Qre=se("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 Jre=se("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 ene=se("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 N_=se("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 tne=se("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 sne=se("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 rne=se("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 nne=se("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 ane=se("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 ine=se("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 OF=se("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 one=se("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 lne=se("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 cne=se("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 $E=se("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 dne=se("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 k_=se("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 une=se("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 hne=se("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 mne=se("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 fne=se("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 pne=se("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 xne=se("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 gne=se("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 Bc=se("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 dm=se("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 yne=se("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 e5=se("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 vne=se("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 bne=se("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 _ne=se("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 wne=se("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 jne=se("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 Nne=se("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 kne=se("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 Sne=se("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 Cne=se("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 Tne=se("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 Ene=se("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 Ane=se("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 Mne=se("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 Ine=se("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 Pne=se("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 Lne=se("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 rP=se("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 Dne=se("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 Rne=se("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 One=se("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 FF=se("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 Fne=se("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 E1=se("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 zne=se("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 Bne=se("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 $ne=se("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 Une=se("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 qne=se("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 Vne=se("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 Hne=se("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 Gne=se("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 Wne=se("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 Oj=se("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 Kne=se("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 t5=se("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 s5=se("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 Yne=se("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 Zne=se("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 Xne=se("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 Qne=se("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 Jne=se("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 eae=se("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 tae=se("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 sae=se("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 rae=se("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 nae=se("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 aae=se("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 iae=se("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 yc=se("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 oae=se("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 lae=se("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 r5=se("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 cae=se("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 dl=se("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 dae=se("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 n5=se("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 uae=se("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 hae=se("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 a5=se("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 i5=se("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 o5=se("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 l5=se("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 mae=se("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 c5=se("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 fae=se("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 pae=se("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 xae=se("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 d5=se("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 gae=se("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 yae=se("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 vae=se("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 bae=se("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 Fj=se("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 iS=se("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 _ae=se("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 wae=se("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 ph=se("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 Xf=se("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 jae=se("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 Nae=se("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 t_=se("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 kae=se("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 oS=se("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 zy=se("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 Sae=se("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 Cae=se("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 Tae=se("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 Ua=se("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 Eae=se("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 UE=se("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 Aae=se("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 Mae=se("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 Iae=se("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 Pae=se("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 Lae=se("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 Dae=se("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 Rae=se("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 Oae=se("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 Mn=se("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 Fae=se("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 zae=se("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 Bae=se("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 $ae=se("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 Uae=se("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 qae=se("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 Vae=se("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 Hae=se("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 Gae=se("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 Wae=se("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 Kae=se("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 zF=se("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 lS=se("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 Yae=se("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 Zae=se("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 Xae=se("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 Qae=se("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 BF=se("Plane",[["path",{d:"M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z",key:"1v9wt8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Al=se("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 Jae=se("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 u5=se("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 d2=se("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 Ys=se("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 eie=se("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 tie=se("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 sie=se("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 rie=se("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 nie=se("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 aie=se("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 iie=se("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 oie=se("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 lie=se("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 $F=se("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 Jy=se("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 cie=se("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 UF=se("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 die=se("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 uie=se("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 hie=se("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 mie=se("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 S_=se("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 u2=se("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 fie=se("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 nP=se("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 pie=se("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 xie=se("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 gie=se("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 yie=se("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 h2=se("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 vie=se("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 bie=se("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 _ie=se("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 wie=se("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 jie=se("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 Nie=se("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 kie=se("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 Sie=se("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 Cie=se("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 Tie=se("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 Eie=se("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 Aie=se("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 Mie=se("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 Iie=se("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 h5=se("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 Pie=se("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 Lie=se("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 Die=se("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 Rie=se("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 Oie=se("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 cS=se("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 Fie=se("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 aP=se("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 zie=se("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 lo=se("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 Bie=se("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 $ie=se("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 Uie=se("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 qie=se("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 Vie=se("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 qF=se("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 Hie=se("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 Gie=se("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 Wie=se("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 VF=se("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 Kie=se("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 Yie=se("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 C_=se("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 Zie=se("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 Xie=se("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 m5=se("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 Qie=se("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 ev=se("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 Jie=se("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 qE=se("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 eoe=se("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 toe=se("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 soe=se("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 f5=se("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 p5=se("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 roe=se("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 noe=se("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 m2=se("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 aoe=se("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 ioe=se("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 ooe=se("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 loe=se("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 coe=se("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 doe=se("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 uoe=se("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 hoe=se("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 Ml=se("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 x5=se("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 HF=se("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 moe=se("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 foe=se("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 poe=se("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 xoe=se("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 goe=se("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 yoe=se("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 voe=se("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 boe=se("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 _oe=se("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 woe=se("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 joe=se("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 Noe=se("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 koe=se("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 Soe=se("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 Coe=se("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 Toe=se("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 Eoe=se("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 Aoe=se("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 Moe=se("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 GF=se("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 _n=se("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 Ioe=se("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 g5=se("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 Poe=se("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 hn=se("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 Loe=se("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 Doe=se("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 Roe=se("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 Ooe=se("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 Foe=se("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 zoe=se("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 WF=se("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 Bo=se("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 Boe=se("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ec=se("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 KF=se("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 $oe=se("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 Uoe=se("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 YF=se("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 qoe=se("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 A1=se("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 Voe=se("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 Hoe=se("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 Goe=se("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 VE=se("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 Woe=se("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 Koe=se("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 y5=se("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 Oh=se("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 Yoe=se("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 Zoe=se("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 Xoe=se("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 T_=se("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 Qoe=se("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 lg=se("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 Joe=se("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 ele=se("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 tle=se("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 sle=se("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 HE=se("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 rle=se("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 nle=se("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 ale=se("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 ile=se("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 ole=se("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 lle=se("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 cle=se("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 dle=se("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 ule=se("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 hle=se("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 mle=se("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 fle=se("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 ple=se("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 xle=se("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 gle=se("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 yle=se("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 dS=se("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 v5=se("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 vle=se("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 ble=se("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 yg=se("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 _le=se("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 wle=se("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 jle=se("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 _1=se("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 Nle=se("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 kle=se("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 Sle=se("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 Cle=se("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 Tle=se("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 Ir=se("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 Ele=se("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 Ale=se("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 Mle=se("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 Ile=se("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 Ple=se("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 Lle=se("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 Dle=se("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 GE=se("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 b5=se("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 _5=se("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 w5=se("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 j5=se("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 N5=se("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 k5=se("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 S5=se("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 C5=se("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 T5=se("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 E5=se("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 A5=se("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 M5=se("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 I5=se("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 P5=se("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 L5=se("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 $b=se("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 zj=se("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 D5=se("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 R5=se("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 O5=se("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 F5=se("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 z5=se("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 B5=se("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 Rle=se("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 Ole=se("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 $5=se("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 U5=se("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 q5=se("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 V5=se("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 H5=se("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 G5=se("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 W5=se("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 K5=se("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 Y5=se("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 Z5=se("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 X5=se("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 Q5=se("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 J5=se("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 eT=se("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 tT=se("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 iu=se("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 sT=se("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 rT=se("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 nT=se("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 aT=se("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 iT=se("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 oT=se("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 Fle=se("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 lT=se("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 cT=se("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 dT=se("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 uT=se("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 hT=se("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 zle=se("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 Ble=se("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 mT=se("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 fT=se("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 pT=se("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 xT=se("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 C0=se("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 $le=se("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 Ule=se("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 qle=se("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 Vle=se("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 Hle=se("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 fa=se("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 Gle=se("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 Wle=se("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 Kle=se("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 Yle=se("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 Zle=se("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 ZF=se("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 Xle=se("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 Qle=se("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 XF=se("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 Jle=se("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 ece=se("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 tce=se("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 sce=se("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 rce=se("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 f2=se("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 nce=se("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 ace=se("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 ice=se("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 oce=se("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 lce=se("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 cce=se("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 dce=se("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 uce=se("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 hce=se("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 iP=se("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 mce=se("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 fce=se("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 pce=se("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 xce=se("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 gce=se("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 yce=se("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 oP=se("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 vce=se("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 lP=se("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 bce=se("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 Fh=se("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 QF=se("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 _ce=se("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 wce=se("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 jce=se("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 Nce=se("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 kce=se("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 Sce=se("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 Hu=se("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 Cce=se("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 Tce=se("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 Ece=se("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 Ace=se("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 gT=se("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 Mce=se("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 Ice=se("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 Pce=se("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 Lce=se("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 Dce=se("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 Rce=se("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 yT=se("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 Oce=se("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 Fce=se("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 zce=se("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 Bce=se("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 $ce=se("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 JF=se("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 wm=se("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 Uce=se("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 qce=se("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 Vce=se("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 Hce=se("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 Gce=se("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 Wce=se("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 e7=se("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 Kce=se("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 Yce=se("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 Zce=se("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 Xce=se("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 Qce=se("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 Jce=se("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 ede=se("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 tde=se("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 sde=se("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 rde=se("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 nde=se("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 ade=se("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 ide=se("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 ode=se("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 lde=se("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 cde=se("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 dde=se("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 ude=se("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 hde=se("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 vT=se("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 zr=se("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 mde=se("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 fde=se("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 bT=se("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 uS=se("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 pde=se("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 xde=se("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 E_=se("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 gde=se("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 Wo=se("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 du=se("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 yde=se("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 vde=se("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 wo=se("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 t7=se("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 bde=se("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 _de=se("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 _T=se("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 wde=se("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 jde=se("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 Nde=se("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 kde=se("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 Sde=se("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 Cde=se("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 Tde=se("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 cP=se("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 Ede=se("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 Ade=se("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 hS=se("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 Mde=se("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 Ide=se("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 Pde=se("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 wT=se("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 Lde=se("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 WE=se("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 Dde=se("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 ka=se("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 Rde=se("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 M1=se("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 s7=se("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 r7=se("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 Ode=se("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 xl=se("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 jT=se("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 NT=se("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 kT=se("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 Fde=se("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 ST=se("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 zde=se("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 CT=se("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 TT=se("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 Bde=se("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 $de=se("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 qi=se("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 ET=se("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 Dr=se("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 AT=se("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 MT=se("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 Ude=se("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 dP=se("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 qde=se("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 Vde=se("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 Hde=se("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 Gde=se("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 Wde=se("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 Kde=se("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 bn=se("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 Yde=se("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 Zde=se("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 Xde=se("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 Qde=se("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 Jde=se("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 n7=se("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 eue=se("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 a7=se("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 tue=se("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 sue=se("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 rue=se("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 IT=se("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 uP=se("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 nue=se("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 p0=se("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 aue=se("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 iue=se("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 oue=se("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 lue=se("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 cue=se("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 due=se("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 uue=se("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 hue=se("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 mue=se("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 fue=se("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 pue=se("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 xue=se("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 gue=se("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 yue=se("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 vue=se("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 bue=se("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 _ue=se("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 wue=se("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 jue=se("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 Nue=se("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 kue=se("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 Sue=se("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 i7=se("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 Cue=se("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 Tue=se("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 A_=se("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 $r=se("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 Eue=se("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 Aue=se("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 zh=se("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 mS=se("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 hP=se("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 i3t=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:xH,AArrowUp:gH,ALargeSmall:yH,Accessibility:vH,Activity:xm,AirVent:bH,Airplay:_H,AlarmClock:jH,AlarmClockCheck:kC,AlarmClockMinus:SC,AlarmClockOff:wH,AlarmClockPlus:CC,AlarmSmoke:NH,Album:kH,AlignCenter:jE,AlignCenterHorizontal:SH,AlignCenterVertical:CH,AlignEndHorizontal:TH,AlignEndVertical:EH,AlignHorizontalDistributeCenter:AH,AlignHorizontalDistributeEnd:MH,AlignHorizontalDistributeStart:IH,AlignHorizontalJustifyCenter:PH,AlignHorizontalJustifyEnd:LH,AlignHorizontalJustifyStart:DH,AlignHorizontalSpaceAround:RH,AlignHorizontalSpaceBetween:OH,AlignJustify:FH,AlignLeft:NE,AlignRight:kE,AlignStartHorizontal:zH,AlignStartVertical:BH,AlignVerticalDistributeCenter:$H,AlignVerticalDistributeEnd:UH,AlignVerticalDistributeStart:qH,AlignVerticalJustifyCenter:VH,AlignVerticalJustifyEnd:HH,AlignVerticalJustifyStart:GH,AlignVerticalSpaceAround:WH,AlignVerticalSpaceBetween:KH,Ambulance:YH,Ampersand:ZH,Ampersands:XH,Amphora:QH,Anchor:JH,Angry:eG,Annoyed:tG,Antenna:sG,Anvil:rG,Aperture:nG,AppWindow:iG,AppWindowMac:aG,Apple:oG,Archive:Qk,ArchiveRestore:qI,ArchiveX:lG,Armchair:cG,ArrowBigDown:uG,ArrowBigDownDash:dG,ArrowBigLeft:mG,ArrowBigLeftDash:hG,ArrowBigRight:pG,ArrowBigRightDash:fG,ArrowBigUp:gG,ArrowBigUpDash:xG,ArrowDown:gm,ArrowDown01:yG,ArrowDown10:vG,ArrowDownAZ:TC,ArrowDownFromLine:bG,ArrowDownLeft:_G,ArrowDownNarrowWide:wG,ArrowDownRight:cF,ArrowDownToDot:jG,ArrowDownToLine:NG,ArrowDownUp:kG,ArrowDownWideNarrow:EC,ArrowDownZA:AC,ArrowLeft:Aa,ArrowLeftFromLine:SG,ArrowLeftRight:CG,ArrowLeftToLine:TG,ArrowRight:ci,ArrowRightFromLine:EG,ArrowRightLeft:Jj,ArrowRightToLine:AG,ArrowUp:qu,ArrowUp01:MG,ArrowUp10:IG,ArrowUpAZ:MC,ArrowUpDown:Uu,ArrowUpFromDot:PG,ArrowUpFromLine:LG,ArrowUpLeft:DG,ArrowUpNarrowWide:IC,ArrowUpRight:dF,ArrowUpToLine:RG,ArrowUpWideNarrow:OG,ArrowUpZA:PC,ArrowsUpFromLine:FG,Asterisk:zG,AtSign:BG,Atom:$G,AudioLines:UG,AudioWaveform:qG,Award:Uc,Axe:VG,Axis3d:LC,Baby:HG,Backpack:GG,Badge:lW,BadgeAlert:WG,BadgeCent:KG,BadgeCheck:DC,BadgeDollarSign:YG,BadgeEuro:ZG,BadgeHelp:XG,BadgeIndianRupee:QG,BadgeInfo:JG,BadgeJapaneseYen:eW,BadgeMinus:tW,BadgePercent:sW,BadgePlus:rW,BadgePoundSterling:nW,BadgeRussianRuble:aW,BadgeSwissFranc:iW,BadgeX:oW,BaggageClaim:cW,Ban:uF,Banana:dW,Bandage:uW,Banknote:hW,Barcode:mW,Baseline:fW,Bath:of,Battery:bW,BatteryCharging:pW,BatteryFull:xW,BatteryLow:gW,BatteryMedium:yW,BatteryWarning:vW,Beaker:_W,Bean:jW,BeanOff:wW,Bed:k0,BedDouble:e2,BedSingle:NW,Beef:kW,Beer:CW,BeerOff:SW,Bell:ym,BellDot:TW,BellElectric:EW,BellMinus:AW,BellOff:b_,BellPlus:MW,BellRing:hF,BetweenHorizontalEnd:RC,BetweenHorizontalStart:OC,BetweenVerticalEnd:IW,BetweenVerticalStart:PW,BicepsFlexed:LW,Bike:DW,Binary:RW,Binoculars:OW,Biohazard:FW,Bird:zW,Bitcoin:BW,Blend:$W,Blinds:UW,Blocks:qW,Bluetooth:WW,BluetoothConnected:VW,BluetoothOff:HW,BluetoothSearching:GW,Bold:Jk,Bolt:KW,Bomb:YW,Bone:ZW,Book:yK,BookA:XW,BookAudio:QW,BookCheck:JW,BookCopy:eK,BookDashed:FC,BookDown:tK,BookHeadphones:sK,BookHeart:rK,BookImage:nK,BookKey:aK,BookLock:iK,BookMarked:oK,BookMinus:lK,BookOpen:vm,BookOpenCheck:cK,BookOpenText:dK,BookPlus:uK,BookText:hK,BookType:mK,BookUp:pK,BookUp2:fK,BookUser:xK,BookX:gK,Bookmark:Zy,BookmarkCheck:vK,BookmarkMinus:bK,BookmarkPlus:mF,BookmarkX:_K,BoomBox:wK,Bot:eS,BotMessageSquare:jK,BotOff:NK,Box:fF,Boxes:kK,Braces:zC,Brackets:SK,Brain:pF,BrainCircuit:CK,BrainCog:TK,BrickWall:EK,Briefcase:bm,BriefcaseBusiness:AK,BriefcaseConveyorBelt:MK,BriefcaseMedical:IK,BringToFront:PK,Brush:LK,Bug:OK,BugOff:DK,BugPlay:RK,Building:SE,Building2:Ga,Bus:zK,BusFront:FK,Cable:$K,CableCar:BK,Cake:_m,CakeSlice:UK,Calculator:__,Calendar:vn,Calendar1:qK,CalendarArrowDown:VK,CalendarArrowUp:HK,CalendarCheck:xF,CalendarCheck2:GK,CalendarClock:Xy,CalendarCog:WK,CalendarDays:xu,CalendarFold:KK,CalendarHeart:gF,CalendarMinus:ZK,CalendarMinus2:YK,CalendarOff:yF,CalendarPlus:Gj,CalendarPlus2:XK,CalendarRange:QK,CalendarSearch:JK,CalendarSync:eY,CalendarX:sY,CalendarX2:tY,Camera:Tp,CameraOff:rY,Candy:iY,CandyCane:nY,CandyOff:aY,Cannabis:oY,Captions:BC,CaptionsOff:lY,Car:uY,CarFront:cY,CarTaxiFront:dY,Caravan:hY,Carrot:mY,CaseLower:fY,CaseSensitive:pY,CaseUpper:xY,CassetteTape:gY,Cast:yY,Castle:vY,Cat:bY,Cctv:_Y,ChartArea:$C,ChartBar:qC,ChartBarBig:UC,ChartBarDecreasing:wY,ChartBarIncreasing:jY,ChartBarStacked:NY,ChartCandlestick:VC,ChartColumn:Mo,ChartColumnBig:HC,ChartColumnDecreasing:kY,ChartColumnIncreasing:GC,ChartColumnStacked:SY,ChartGantt:CY,ChartLine:WC,ChartNetwork:TY,ChartNoAxesColumn:YC,ChartNoAxesColumnDecreasing:EY,ChartNoAxesColumnIncreasing:KC,ChartNoAxesCombined:AY,ChartNoAxesGantt:ZC,ChartPie:XC,ChartScatter:QC,ChartSpline:MY,Check:la,CheckCheck:vF,ChefHat:IY,Cherry:PY,ChevronDown:Co,ChevronFirst:LY,ChevronLast:DY,ChevronLeft:jl,ChevronRight:Ia,ChevronUp:pg,ChevronsDown:OY,ChevronsDownUp:RY,ChevronsLeft:BY,ChevronsLeftRight:zY,ChevronsLeftRightEllipsis:FY,ChevronsRight:UY,ChevronsRightLeft:$Y,ChevronsUp:qY,ChevronsUpDown:xg,Chrome:CE,Church:VY,Cigarette:GY,CigaretteOff:HY,Circle:Rh,CircleAlert:go,CircleArrowDown:JC,CircleArrowLeft:e3,CircleArrowOutDownLeft:t3,CircleArrowOutDownRight:s3,CircleArrowOutUpLeft:r3,CircleArrowOutUpRight:n3,CircleArrowRight:a3,CircleArrowUp:i3,CircleCheck:qn,CircleCheckBig:Ti,CircleChevronDown:o3,CircleChevronLeft:l3,CircleChevronRight:c3,CircleChevronUp:d3,CircleDashed:WY,CircleDivide:u3,CircleDollarSign:KY,CircleDot:ZY,CircleDotDashed:YY,CircleEllipsis:XY,CircleEqual:QY,CircleFadingArrowUp:JY,CircleFadingPlus:eZ,CircleGauge:h3,CircleHelp:e_,CircleMinus:m3,CircleOff:tZ,CircleParking:p3,CircleParkingOff:f3,CirclePause:x3,CirclePercent:g3,CirclePlay:Ff,CirclePlus:y3,CirclePower:v3,CircleSlash:sZ,CircleSlash2:b3,CircleStop:_3,CircleUser:j3,CircleUserRound:w3,CircleX:ad,CircuitBoard:rZ,Citrus:nZ,Clapperboard:aZ,Clipboard:hZ,ClipboardCheck:VI,ClipboardCopy:iZ,ClipboardList:k1,ClipboardMinus:oZ,ClipboardPaste:lZ,ClipboardPen:k3,ClipboardPenLine:N3,ClipboardPlus:cZ,ClipboardType:dZ,ClipboardX:uZ,Clock:jn,Clock1:mZ,Clock10:fZ,Clock11:pZ,Clock12:xZ,Clock2:gZ,Clock3:yZ,Clock4:vZ,Clock5:bZ,Clock6:_Z,Clock7:wZ,Clock8:jZ,Clock9:NZ,ClockAlert:kZ,ClockArrowDown:SZ,ClockArrowUp:CZ,Cloud:UZ,CloudAlert:TZ,CloudCog:EZ,CloudDownload:S3,CloudDrizzle:AZ,CloudFog:MZ,CloudHail:IZ,CloudLightning:PZ,CloudMoon:DZ,CloudMoonRain:LZ,CloudOff:RZ,CloudRain:FZ,CloudRainWind:OZ,CloudSnow:zZ,CloudSun:$Z,CloudSunRain:BZ,CloudUpload:C3,Cloudy:qZ,Clover:Wj,Club:VZ,Code:TE,CodeXml:Rj,Codepen:HZ,Codesandbox:GZ,Coffee:EE,Cog:WZ,Coins:bF,Columns2:T3,Columns3:E3,Columns4:KZ,Combine:YZ,Command:ZZ,Compass:HI,Component:XZ,Computer:QZ,ConciergeBell:JZ,Cone:eX,Construction:tX,Contact:AE,ContactRound:A3,Container:sX,Contrast:rX,Cookie:nX,CookingPot:aX,Copy:si,CopyCheck:iX,CopyMinus:oX,CopyPlus:lX,CopySlash:cX,CopyX:dX,Copyleft:uX,Copyright:hX,CornerDownLeft:mX,CornerDownRight:fX,CornerLeftDown:pX,CornerLeftUp:xX,CornerRightDown:gX,CornerRightUp:yX,CornerUpLeft:vX,CornerUpRight:bX,Cpu:_X,CreativeCommons:wX,CreditCard:S0,Croissant:jX,Crop:NX,Cross:kX,Crosshair:SX,Crown:Gf,Cuboid:CX,CupSoda:TX,Currency:EX,Cylinder:AX,Dam:MX,Database:_F,DatabaseBackup:IX,DatabaseZap:PX,Delete:LX,Dessert:DX,Diameter:RX,Diamond:zX,DiamondMinus:OX,DiamondPercent:M3,DiamondPlus:FX,Dice1:BX,Dice2:$X,Dice3:UX,Dice4:qX,Dice5:VX,Dice6:HX,Dices:GX,Diff:WX,Disc:XX,Disc2:KX,Disc3:YX,DiscAlbum:ZX,Divide:QX,Dna:eQ,DnaOff:JX,Dock:tQ,Dog:sQ,DollarSign:Xl,Donut:rQ,DoorClosed:nQ,DoorOpen:w_,Dot:aQ,Download:li,DraftingCompass:iQ,Drama:oQ,Dribbble:lQ,Drill:cQ,Droplet:dQ,Droplets:S1,Drum:uQ,Drumstick:hQ,Dumbbell:mQ,Ear:pQ,EarOff:fQ,Earth:I3,EarthLock:xQ,Eclipse:gQ,Egg:GI,EggFried:yQ,EggOff:vQ,Ellipsis:f0,EllipsisVertical:Fy,Equal:wQ,EqualApproximately:bQ,EqualNot:_Q,Eraser:jQ,EthernetPort:NQ,Euro:kQ,Expand:SQ,ExternalLink:un,Eye:Nn,EyeClosed:CQ,EyeOff:Wf,Facebook:mh,Factory:TQ,Fan:EQ,FastForward:AQ,Feather:MQ,Fence:IQ,FerrisWheel:PQ,Figma:LQ,File:WI,FileArchive:DQ,FileAudio:OQ,FileAudio2:RQ,FileAxis3d:P3,FileBadge:zQ,FileBadge2:FQ,FileBox:BQ,FileChartColumn:D3,FileChartColumnIncreasing:L3,FileChartLine:R3,FileChartPie:O3,FileCheck:wF,FileCheck2:$Q,FileClock:UQ,FileCode:VQ,FileCode2:qQ,FileCog:F3,FileDiff:HQ,FileDigit:GQ,FileDown:ME,FileHeart:WQ,FileImage:t2,FileInput:KQ,FileJson:ZQ,FileJson2:YQ,FileKey:QQ,FileKey2:XQ,FileLock:eJ,FileLock2:JQ,FileMinus:sJ,FileMinus2:tJ,FileMusic:rJ,FileOutput:nJ,FilePen:B3,FilePenLine:z3,FilePlus:iJ,FilePlus2:aJ,FileQuestion:oJ,FileScan:lJ,FileSearch:dJ,FileSearch2:cJ,FileSliders:uJ,FileSpreadsheet:s2,FileStack:jF,FileSymlink:hJ,FileTerminal:mJ,FileText:En,FileType:pJ,FileType2:fJ,FileUp:xJ,FileUser:gJ,FileVideo:NF,FileVideo2:yJ,FileVolume:bJ,FileVolume2:vJ,FileWarning:_J,FileX:jJ,FileX2:wJ,Files:NJ,Film:rf,Filter:C1,FilterX:kJ,Fingerprint:SJ,FireExtinguisher:CJ,Fish:AJ,FishOff:TJ,FishSymbol:EJ,Flag:r2,FlagOff:MJ,FlagTriangleLeft:IJ,FlagTriangleRight:PJ,Flame:ld,FlameKindling:LJ,Flashlight:RJ,FlashlightOff:DJ,FlaskConical:tS,FlaskConicalOff:OJ,FlaskRound:FJ,FlipHorizontal:kF,FlipHorizontal2:zJ,FlipVertical:$J,FlipVertical2:BJ,Flower:UJ,Flower2:b1,Focus:qJ,FoldHorizontal:VJ,FoldVertical:HJ,Folder:yee,FolderArchive:GJ,FolderCheck:WJ,FolderClock:KJ,FolderClosed:YJ,FolderCode:ZJ,FolderCog:$3,FolderDot:XJ,FolderDown:QJ,FolderGit:eee,FolderGit2:JJ,FolderHeart:tee,FolderInput:see,FolderKanban:ree,FolderKey:nee,FolderLock:aee,FolderMinus:iee,FolderOpen:Kf,FolderOpenDot:oee,FolderOutput:lee,FolderPen:U3,FolderPlus:cee,FolderRoot:dee,FolderSearch:hee,FolderSearch2:uee,FolderSymlink:mee,FolderSync:fee,FolderTree:pee,FolderUp:xee,FolderX:gee,Folders:vee,Footprints:bee,Forklift:_ee,Forward:wee,Frame:jee,Framer:Nee,Frown:kee,Fuel:See,Fullscreen:Cee,GalleryHorizontal:Eee,GalleryHorizontalEnd:Tee,GalleryThumbnails:Aee,GalleryVertical:Iee,GalleryVerticalEnd:Mee,Gamepad:Lee,Gamepad2:Pee,Gauge:Dee,Gavel:Ree,Gem:Oee,Ghost:IE,Gift:Di,GitBranch:zee,GitBranchPlus:Fee,GitCommitHorizontal:q3,GitCommitVertical:Bee,GitCompare:Uee,GitCompareArrows:$ee,GitFork:qee,GitGraph:Vee,GitMerge:Hee,GitPullRequest:Xee,GitPullRequestArrow:Gee,GitPullRequestClosed:Wee,GitPullRequestCreate:Yee,GitPullRequestCreateArrow:Kee,GitPullRequestDraft:Zee,Github:Qee,Gitlab:Jee,GlassWater:ete,Glasses:tte,Globe:Ql,GlobeLock:ste,Goal:rte,Grab:nte,GraduationCap:ch,Grape:ate,Grid2x2:H3,Grid2x2Check:ite,Grid2x2Plus:V3,Grid2x2X:ote,Grid3x3:Ey,Grip:cte,GripHorizontal:lte,GripVertical:Vu,Group:dte,Guitar:ute,Ham:hte,Hammer:SF,Hand:CF,HandCoins:mte,HandHeart:fte,HandHelping:p1,HandMetal:pte,HandPlatter:xte,Handshake:j_,HardDrive:TF,HardDriveDownload:gte,HardDriveUpload:yte,HardHat:vte,Hash:sS,Haze:bte,HdmiPort:_te,Heading:kte,Heading1:KI,Heading2:YI,Heading3:EF,Heading4:wte,Heading5:jte,Heading6:Nte,HeadphoneOff:Ste,Headphones:Cte,Headset:Tte,Heart:yi,HeartCrack:Ete,HeartHandshake:Ate,HeartOff:Mte,HeartPulse:Ite,Heater:Pte,Hexagon:Lte,Highlighter:Dte,History:ZI,Hop:Ote,HopOff:Rte,Hospital:Fte,Hotel:zte,Hourglass:Bte,House:Pn,HousePlug:$te,HousePlus:Ute,IceCreamBowl:G3,IceCreamCone:W3,IdCard:qte,Image:zo,ImageDown:Vte,ImageMinus:Hte,ImageOff:Gte,ImagePlay:Wte,ImagePlus:Qy,ImageUp:Kte,ImageUpscale:Yte,Images:Zte,Import:Xte,Inbox:n2,IndentDecrease:K3,IndentIncrease:Y3,IndianRupee:Qte,Infinity:Jte,Info:a2,InspectionPanel:ese,Instagram:gu,Italic:rS,IterationCcw:tse,IterationCw:sse,JapaneseYen:rse,Joystick:nse,Kanban:i2,Key:gg,KeyRound:PE,KeySquare:ase,Keyboard:lse,KeyboardMusic:ise,KeyboardOff:ose,Lamp:fse,LampCeiling:cse,LampDesk:dse,LampFloor:use,LampWallDown:hse,LampWallUp:mse,LandPlot:pse,Landmark:xse,Languages:gse,Laptop:vse,LaptopMinimal:Z3,LaptopMinimalCheck:yse,Lasso:_se,LassoSelect:bse,Laugh:wse,Layers:AF,Layers2:jse,Layers3:Nse,LayoutDashboard:LE,LayoutGrid:Ep,LayoutList:kse,LayoutPanelLeft:Sse,LayoutPanelTop:Cse,LayoutTemplate:DE,Leaf:Tse,LeafyGreen:Ese,Lectern:Ase,LetterText:Mse,Library:nS,LibraryBig:Ise,LifeBuoy:XI,Ligature:Pse,Lightbulb:o2,LightbulbOff:Lse,Link:tl,Link2:Ul,Link2Off:Dse,Linkedin:Yf,List:Zf,ListCheck:Rse,ListChecks:l2,ListCollapse:Ose,ListEnd:Fse,ListFilter:MF,ListMinus:zse,ListMusic:Bse,ListOrdered:T1,ListPlus:$se,ListRestart:Use,ListStart:qse,ListTodo:Vse,ListTree:Hse,ListVideo:Gse,ListX:Wse,Loader:Yse,LoaderCircle:ls,LoaderPinwheel:Kse,Locate:QI,LocateFixed:Zse,LocateOff:Xse,Lock:Gc,LockKeyhole:Qse,LockKeyholeOpen:X3,LockOpen:Q3,LogIn:RE,LogOut:OE,Logs:Jse,Lollipop:ere,Luggage:tre,Magnet:sre,Mail:Ks,MailCheck:JI,MailMinus:rre,MailOpen:IF,MailPlus:PF,MailQuestion:nre,MailSearch:are,MailWarning:ire,MailX:eP,Mailbox:ore,Mails:lre,Map:FE,MapPin:Ma,MapPinCheck:dre,MapPinCheckInside:cre,MapPinHouse:ure,MapPinMinus:mre,MapPinMinusInside:hre,MapPinOff:fre,MapPinPlus:xre,MapPinPlusInside:pre,MapPinX:yre,MapPinXInside:gre,MapPinned:vre,Martini:bre,Maximize:zE,Maximize2:LF,Medal:c2,Megaphone:fh,MegaphoneOff:_re,Meh:wre,MemoryStick:jre,Menu:aS,Merge:Nre,MessageCircle:gc,MessageCircleCode:kre,MessageCircleDashed:Sre,MessageCircleHeart:tP,MessageCircleMore:Cre,MessageCircleOff:Tre,MessageCirclePlus:Ere,MessageCircleQuestion:DF,MessageCircleReply:Are,MessageCircleWarning:Mre,MessageCircleX:Ire,MessageSquare:Ui,MessageSquareCode:Pre,MessageSquareDashed:Lre,MessageSquareDiff:Dre,MessageSquareDot:Rre,MessageSquareHeart:Ore,MessageSquareLock:Fre,MessageSquareMore:RF,MessageSquareOff:zre,MessageSquarePlus:c_,MessageSquareQuote:sP,MessageSquareReply:Bre,MessageSquareShare:$re,MessageSquareText:Ure,MessageSquareWarning:qre,MessageSquareX:Vre,MessagesSquare:Hre,Mic:BE,MicOff:Gre,MicVocal:J3,Microchip:Wre,Microscope:Kre,Microwave:Yre,Milestone:Zre,Milk:Qre,MilkOff:Xre,Minimize:ene,Minimize2:Jre,Minus:N_,Monitor:k_,MonitorCheck:tne,MonitorCog:sne,MonitorDot:rne,MonitorDown:nne,MonitorOff:ane,MonitorPause:ine,MonitorPlay:OF,MonitorSmartphone:one,MonitorSpeaker:lne,MonitorStop:cne,MonitorUp:$E,MonitorX:dne,Moon:hne,MoonStar:une,Mountain:fne,MountainSnow:mne,Mouse:yne,MouseOff:pne,MousePointer:dm,MousePointer2:xne,MousePointerBan:gne,MousePointerClick:Bc,Move:Mne,Move3d:e5,MoveDiagonal:bne,MoveDiagonal2:vne,MoveDown:jne,MoveDownLeft:_ne,MoveDownRight:wne,MoveHorizontal:Nne,MoveLeft:kne,MoveRight:Sne,MoveUp:Ene,MoveUpLeft:Cne,MoveUpRight:Tne,MoveVertical:Ane,Music:rP,Music2:Ine,Music3:Pne,Music4:Lne,Navigation:FF,Navigation2:Rne,Navigation2Off:Dne,NavigationOff:One,Network:Fne,Newspaper:E1,Nfc:zne,Notebook:qne,NotebookPen:Bne,NotebookTabs:$ne,NotebookText:Une,NotepadText:Hne,NotepadTextDashed:Vne,Nut:Wne,NutOff:Gne,Octagon:Yne,OctagonAlert:Oj,OctagonMinus:Kne,OctagonPause:t5,OctagonX:s5,Omega:Zne,Option:Xne,Orbit:Qne,Origami:Jne,Package:yc,Package2:eae,PackageCheck:tae,PackageMinus:sae,PackageOpen:rae,PackagePlus:nae,PackageSearch:aae,PackageX:iae,PaintBucket:oae,PaintRoller:lae,Paintbrush:cae,PaintbrushVertical:r5,Palette:dl,PanelBottom:hae,PanelBottomClose:dae,PanelBottomDashed:n5,PanelBottomOpen:uae,PanelLeft:l5,PanelLeftClose:a5,PanelLeftDashed:i5,PanelLeftOpen:o5,PanelRight:pae,PanelRightClose:mae,PanelRightDashed:c5,PanelRightOpen:fae,PanelTop:yae,PanelTopClose:xae,PanelTopDashed:d5,PanelTopOpen:gae,PanelsLeftBottom:vae,PanelsRightBottom:bae,PanelsTopLeft:Fj,Paperclip:iS,Parentheses:_ae,ParkingMeter:wae,PartyPopper:ph,Pause:Xf,PawPrint:jae,PcCase:Nae,Pen:zy,PenLine:t_,PenOff:kae,PenTool:oS,Pencil:Ua,PencilLine:Sae,PencilOff:Cae,PencilRuler:Tae,Pentagon:Eae,Percent:UE,PersonStanding:Aae,PhilippinePeso:Mae,Phone:Mn,PhoneCall:Iae,PhoneForwarded:Pae,PhoneIncoming:Lae,PhoneMissed:Dae,PhoneOff:Rae,PhoneOutgoing:Oae,Pi:Fae,Piano:zae,Pickaxe:Bae,PictureInPicture:Uae,PictureInPicture2:$ae,PiggyBank:qae,Pilcrow:Gae,PilcrowLeft:Vae,PilcrowRight:Hae,Pill:Kae,PillBottle:Wae,Pin:lS,PinOff:zF,Pipette:Yae,Pizza:Zae,Plane:BF,PlaneLanding:Xae,PlaneTakeoff:Qae,Play:Al,Plug:d2,Plug2:Jae,PlugZap:u5,Plus:Ys,Pocket:tie,PocketKnife:eie,Podcast:sie,Pointer:nie,PointerOff:rie,Popcorn:aie,Popsicle:iie,PoundSterling:oie,Power:$F,PowerOff:lie,Presentation:Jy,Printer:UF,PrinterCheck:cie,Projector:die,Proportions:uie,Puzzle:hie,Pyramid:mie,QrCode:S_,Quote:u2,Rabbit:fie,Radar:nP,Radiation:pie,Radical:xie,Radio:h2,RadioReceiver:gie,RadioTower:yie,Radius:vie,RailSymbol:bie,Rainbow:_ie,Rat:wie,Ratio:jie,Receipt:Iie,ReceiptCent:Nie,ReceiptEuro:kie,ReceiptIndianRupee:Sie,ReceiptJapaneseYen:Cie,ReceiptPoundSterling:Tie,ReceiptRussianRuble:Eie,ReceiptSwissFranc:Aie,ReceiptText:Mie,RectangleEllipsis:h5,RectangleHorizontal:Pie,RectangleVertical:Lie,Recycle:Die,Redo:cS,Redo2:Rie,RedoDot:Oie,RefreshCcw:aP,RefreshCcwDot:Fie,RefreshCw:lo,RefreshCwOff:zie,Refrigerator:Bie,Regex:$ie,RemoveFormatting:Uie,Repeat:qF,Repeat1:qie,Repeat2:Vie,Replace:Gie,ReplaceAll:Hie,Reply:VF,ReplyAll:Wie,Rewind:Kie,Ribbon:Yie,Rocket:C_,RockingChair:Zie,RollerCoaster:Xie,Rotate3d:m5,RotateCcw:ev,RotateCcwSquare:Qie,RotateCw:qE,RotateCwSquare:Jie,Route:toe,RouteOff:eoe,Router:soe,Rows2:f5,Rows3:p5,Rows4:roe,Rss:noe,Ruler:m2,RussianRuble:aoe,Sailboat:ioe,Salad:ooe,Sandwich:loe,Satellite:doe,SatelliteDish:coe,Save:Ml,SaveAll:uoe,SaveOff:hoe,Scale:HF,Scale3d:x5,Scaling:moe,Scan:_oe,ScanBarcode:foe,ScanEye:poe,ScanFace:xoe,ScanLine:goe,ScanQrCode:yoe,ScanSearch:voe,ScanText:boe,School:woe,Scissors:Noe,ScissorsLineDashed:joe,ScreenShare:Soe,ScreenShareOff:koe,Scroll:Toe,ScrollText:Coe,Search:_n,SearchCheck:Eoe,SearchCode:Aoe,SearchSlash:Moe,SearchX:GF,Section:Ioe,Send:hn,SendHorizontal:g5,SendToBack:Poe,SeparatorHorizontal:Loe,SeparatorVertical:Doe,Server:zoe,ServerCog:Roe,ServerCrash:Ooe,ServerOff:Foe,Settings:Bo,Settings2:WF,Shapes:Boe,Share:KF,Share2:Ec,Sheet:$oe,Shell:Uoe,Shield:Oh,ShieldAlert:YF,ShieldBan:qoe,ShieldCheck:A1,ShieldEllipsis:Voe,ShieldHalf:Hoe,ShieldMinus:Goe,ShieldOff:VE,ShieldPlus:Woe,ShieldQuestion:Koe,ShieldX:y5,Ship:Zoe,ShipWheel:Yoe,Shirt:Xoe,ShoppingBag:T_,ShoppingBasket:Qoe,ShoppingCart:lg,Shovel:Joe,ShowerHead:ele,Shrink:tle,Shrub:sle,Shuffle:HE,Sigma:rle,Signal:lle,SignalHigh:nle,SignalLow:ale,SignalMedium:ile,SignalZero:ole,Signature:cle,Signpost:ule,SignpostBig:dle,Siren:hle,SkipBack:mle,SkipForward:fle,Skull:ple,Slack:xle,Slash:gle,Slice:yle,SlidersHorizontal:dS,SlidersVertical:v5,Smartphone:yg,SmartphoneCharging:vle,SmartphoneNfc:ble,Smile:wle,SmilePlus:_le,Snail:jle,Snowflake:_1,Sofa:Nle,Soup:kle,Space:Sle,Spade:Cle,Sparkle:Tle,Sparkles:Ir,Speaker:Ele,Speech:Ale,SpellCheck:Ile,SpellCheck2:Mle,Spline:Ple,Split:Lle,SprayCan:Dle,Sprout:GE,Square:C0,SquareActivity:b5,SquareArrowDown:j5,SquareArrowDownLeft:_5,SquareArrowDownRight:w5,SquareArrowLeft:N5,SquareArrowOutDownLeft:k5,SquareArrowOutDownRight:S5,SquareArrowOutUpLeft:C5,SquareArrowOutUpRight:T5,SquareArrowRight:E5,SquareArrowUp:I5,SquareArrowUpLeft:A5,SquareArrowUpRight:M5,SquareAsterisk:P5,SquareBottomDashedScissors:L5,SquareChartGantt:$b,SquareCheck:D5,SquareCheckBig:zj,SquareChevronDown:R5,SquareChevronLeft:O5,SquareChevronRight:F5,SquareChevronUp:z5,SquareCode:B5,SquareDashed:q5,SquareDashedBottom:Ole,SquareDashedBottomCode:Rle,SquareDashedKanban:$5,SquareDashedMousePointer:U5,SquareDivide:V5,SquareDot:H5,SquareEqual:G5,SquareFunction:W5,SquareKanban:K5,SquareLibrary:Y5,SquareM:Z5,SquareMenu:X5,SquareMinus:Q5,SquareMousePointer:J5,SquareParking:tT,SquareParkingOff:eT,SquarePen:iu,SquarePercent:sT,SquarePi:rT,SquarePilcrow:nT,SquarePlay:aT,SquarePlus:iT,SquarePower:oT,SquareRadical:Fle,SquareScissors:lT,SquareSigma:cT,SquareSlash:dT,SquareSplitHorizontal:uT,SquareSplitVertical:hT,SquareSquare:zle,SquareStack:Ble,SquareTerminal:mT,SquareUser:pT,SquareUserRound:fT,SquareX:xT,Squircle:$le,Squirrel:Ule,Stamp:qle,Star:fa,StarHalf:Vle,StarOff:Hle,StepBack:Gle,StepForward:Wle,Stethoscope:Kle,Sticker:Yle,StickyNote:Zle,Store:ZF,StretchHorizontal:Xle,StretchVertical:Qle,Strikethrough:XF,Subscript:Jle,Sun:f2,SunDim:ece,SunMedium:tce,SunMoon:sce,SunSnow:rce,Sunrise:nce,Sunset:ace,Superscript:ice,SwatchBook:oce,SwissFranc:lce,SwitchCamera:cce,Sword:dce,Swords:uce,Syringe:hce,Table:oP,Table2:iP,TableCellsMerge:mce,TableCellsSplit:fce,TableColumnsSplit:pce,TableOfContents:xce,TableProperties:gce,TableRowsSplit:yce,Tablet:lP,TabletSmartphone:vce,Tablets:bce,Tag:Fh,Tags:QF,Tally1:_ce,Tally2:wce,Tally3:jce,Tally4:Nce,Tally5:kce,Tangent:Sce,Target:Hu,Telescope:Cce,Tent:Ece,TentTree:Tce,Terminal:Ace,TestTube:Mce,TestTubeDiagonal:gT,TestTubes:Ice,Text:Oce,TextCursor:Lce,TextCursorInput:Pce,TextQuote:Dce,TextSearch:Rce,TextSelect:yT,Theater:Fce,Thermometer:$ce,ThermometerSnowflake:zce,ThermometerSun:Bce,ThumbsDown:JF,ThumbsUp:wm,Ticket:e7,TicketCheck:Uce,TicketMinus:qce,TicketPercent:Vce,TicketPlus:Hce,TicketSlash:Gce,TicketX:Wce,Tickets:Yce,TicketsPlane:Kce,Timer:Qce,TimerOff:Zce,TimerReset:Xce,ToggleLeft:Jce,ToggleRight:ede,Toilet:tde,Tornado:sde,Torus:rde,Touchpad:ade,TouchpadOff:nde,TowerControl:ide,ToyBrick:ode,Tractor:lde,TrafficCone:cde,TrainFront:ude,TrainFrontTunnel:dde,TrainTrack:hde,TramFront:vT,Trash:mde,Trash2:zr,TreeDeciduous:fde,TreePalm:bT,TreePine:uS,Trees:pde,Trello:xde,TrendingDown:E_,TrendingUp:Wo,TrendingUpDown:gde,Triangle:vde,TriangleAlert:du,TriangleRight:yde,Trophy:wo,Truck:t7,Turtle:bde,Tv:wde,TvMinimal:_T,TvMinimalPlay:_de,Twitch:jde,Twitter:Nde,Type:Sde,TypeOutline:kde,Umbrella:Tde,UmbrellaOff:Cde,Underline:cP,Undo:hS,Undo2:Ede,UndoDot:Ade,UnfoldHorizontal:Mde,UnfoldVertical:Ide,Ungroup:Pde,University:wT,Unlink:WE,Unlink2:Lde,Unplug:Dde,Upload:ka,Usb:Rde,User:qi,UserCheck:M1,UserCog:s7,UserMinus:r7,UserPen:Ode,UserPlus:xl,UserRound:TT,UserRoundCheck:jT,UserRoundCog:NT,UserRoundMinus:kT,UserRoundPen:Fde,UserRoundPlus:ST,UserRoundSearch:zde,UserRoundX:CT,UserSearch:Bde,UserX:$de,Users:Dr,UsersRound:ET,Utensils:MT,UtensilsCrossed:AT,UtilityPole:Ude,Variable:dP,Vault:qde,Vegan:Vde,VenetianMask:Hde,Vibrate:Wde,VibrateOff:Gde,Video:bn,VideoOff:Kde,Videotape:Yde,View:Zde,Voicemail:Xde,Volleyball:Qde,Volume:tue,Volume1:Jde,Volume2:n7,VolumeOff:eue,VolumeX:a7,Vote:sue,Wallet:uP,WalletCards:rue,WalletMinimal:IT,Wallpaper:nue,Wand:aue,WandSparkles:p0,Warehouse:iue,WashingMachine:oue,Watch:lue,Waves:cue,Waypoints:due,Webcam:uue,Webhook:mue,WebhookOff:hue,Weight:fue,Wheat:xue,WheatOff:pue,WholeWord:gue,Wifi:wue,WifiHigh:yue,WifiLow:vue,WifiOff:bue,WifiZero:_ue,Wind:Nue,WindArrowDown:jue,Wine:Sue,WineOff:kue,Workflow:i7,Worm:Cue,WrapText:Tue,Wrench:A_,X:$r,Youtube:Eue,Zap:zh,ZapOff:Aue,ZoomIn:mS,ZoomOut:hP},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 _xe=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:xH,AArrowDownIcon:xH,AArrowUp:gH,AArrowUpIcon:gH,ALargeSmall:yH,ALargeSmallIcon:yH,Accessibility:vH,AccessibilityIcon:vH,Activity:xm,ActivityIcon:xm,ActivitySquare:b5,ActivitySquareIcon:b5,AirVent:bH,AirVentIcon:bH,Airplay:_H,AirplayIcon:_H,AlarmCheck:kC,AlarmCheckIcon:kC,AlarmClock:jH,AlarmClockCheck:kC,AlarmClockCheckIcon:kC,AlarmClockIcon:jH,AlarmClockMinus:SC,AlarmClockMinusIcon:SC,AlarmClockOff:wH,AlarmClockOffIcon:wH,AlarmClockPlus:CC,AlarmClockPlusIcon:CC,AlarmMinus:SC,AlarmMinusIcon:SC,AlarmPlus:CC,AlarmPlusIcon:CC,AlarmSmoke:NH,AlarmSmokeIcon:NH,Album:kH,AlbumIcon:kH,AlertCircle:go,AlertCircleIcon:go,AlertOctagon:Oj,AlertOctagonIcon:Oj,AlertTriangle:du,AlertTriangleIcon:du,AlignCenter:jE,AlignCenterHorizontal:SH,AlignCenterHorizontalIcon:SH,AlignCenterIcon:jE,AlignCenterVertical:CH,AlignCenterVerticalIcon:CH,AlignEndHorizontal:TH,AlignEndHorizontalIcon:TH,AlignEndVertical:EH,AlignEndVerticalIcon:EH,AlignHorizontalDistributeCenter:AH,AlignHorizontalDistributeCenterIcon:AH,AlignHorizontalDistributeEnd:MH,AlignHorizontalDistributeEndIcon:MH,AlignHorizontalDistributeStart:IH,AlignHorizontalDistributeStartIcon:IH,AlignHorizontalJustifyCenter:PH,AlignHorizontalJustifyCenterIcon:PH,AlignHorizontalJustifyEnd:LH,AlignHorizontalJustifyEndIcon:LH,AlignHorizontalJustifyStart:DH,AlignHorizontalJustifyStartIcon:DH,AlignHorizontalSpaceAround:RH,AlignHorizontalSpaceAroundIcon:RH,AlignHorizontalSpaceBetween:OH,AlignHorizontalSpaceBetweenIcon:OH,AlignJustify:FH,AlignJustifyIcon:FH,AlignLeft:NE,AlignLeftIcon:NE,AlignRight:kE,AlignRightIcon:kE,AlignStartHorizontal:zH,AlignStartHorizontalIcon:zH,AlignStartVertical:BH,AlignStartVerticalIcon:BH,AlignVerticalDistributeCenter:$H,AlignVerticalDistributeCenterIcon:$H,AlignVerticalDistributeEnd:UH,AlignVerticalDistributeEndIcon:UH,AlignVerticalDistributeStart:qH,AlignVerticalDistributeStartIcon:qH,AlignVerticalJustifyCenter:VH,AlignVerticalJustifyCenterIcon:VH,AlignVerticalJustifyEnd:HH,AlignVerticalJustifyEndIcon:HH,AlignVerticalJustifyStart:GH,AlignVerticalJustifyStartIcon:GH,AlignVerticalSpaceAround:WH,AlignVerticalSpaceAroundIcon:WH,AlignVerticalSpaceBetween:KH,AlignVerticalSpaceBetweenIcon:KH,Ambulance:YH,AmbulanceIcon:YH,Ampersand:ZH,AmpersandIcon:ZH,Ampersands:XH,AmpersandsIcon:XH,Amphora:QH,AmphoraIcon:QH,Anchor:JH,AnchorIcon:JH,Angry:eG,AngryIcon:eG,Annoyed:tG,AnnoyedIcon:tG,Antenna:sG,AntennaIcon:sG,Anvil:rG,AnvilIcon:rG,Aperture:nG,ApertureIcon:nG,AppWindow:iG,AppWindowIcon:iG,AppWindowMac:aG,AppWindowMacIcon:aG,Apple:oG,AppleIcon:oG,Archive:Qk,ArchiveIcon:Qk,ArchiveRestore:qI,ArchiveRestoreIcon:qI,ArchiveX:lG,ArchiveXIcon:lG,AreaChart:$C,AreaChartIcon:$C,Armchair:cG,ArmchairIcon:cG,ArrowBigDown:uG,ArrowBigDownDash:dG,ArrowBigDownDashIcon:dG,ArrowBigDownIcon:uG,ArrowBigLeft:mG,ArrowBigLeftDash:hG,ArrowBigLeftDashIcon:hG,ArrowBigLeftIcon:mG,ArrowBigRight:pG,ArrowBigRightDash:fG,ArrowBigRightDashIcon:fG,ArrowBigRightIcon:pG,ArrowBigUp:gG,ArrowBigUpDash:xG,ArrowBigUpDashIcon:xG,ArrowBigUpIcon:gG,ArrowDown:gm,ArrowDown01:yG,ArrowDown01Icon:yG,ArrowDown10:vG,ArrowDown10Icon:vG,ArrowDownAZ:TC,ArrowDownAZIcon:TC,ArrowDownAz:TC,ArrowDownAzIcon:TC,ArrowDownCircle:JC,ArrowDownCircleIcon:JC,ArrowDownFromLine:bG,ArrowDownFromLineIcon:bG,ArrowDownIcon:gm,ArrowDownLeft:_G,ArrowDownLeftFromCircle:t3,ArrowDownLeftFromCircleIcon:t3,ArrowDownLeftFromSquare:k5,ArrowDownLeftFromSquareIcon:k5,ArrowDownLeftIcon:_G,ArrowDownLeftSquare:_5,ArrowDownLeftSquareIcon:_5,ArrowDownNarrowWide:wG,ArrowDownNarrowWideIcon:wG,ArrowDownRight:cF,ArrowDownRightFromCircle:s3,ArrowDownRightFromCircleIcon:s3,ArrowDownRightFromSquare:S5,ArrowDownRightFromSquareIcon:S5,ArrowDownRightIcon:cF,ArrowDownRightSquare:w5,ArrowDownRightSquareIcon:w5,ArrowDownSquare:j5,ArrowDownSquareIcon:j5,ArrowDownToDot:jG,ArrowDownToDotIcon:jG,ArrowDownToLine:NG,ArrowDownToLineIcon:NG,ArrowDownUp:kG,ArrowDownUpIcon:kG,ArrowDownWideNarrow:EC,ArrowDownWideNarrowIcon:EC,ArrowDownZA:AC,ArrowDownZAIcon:AC,ArrowDownZa:AC,ArrowDownZaIcon:AC,ArrowLeft:Aa,ArrowLeftCircle:e3,ArrowLeftCircleIcon:e3,ArrowLeftFromLine:SG,ArrowLeftFromLineIcon:SG,ArrowLeftIcon:Aa,ArrowLeftRight:CG,ArrowLeftRightIcon:CG,ArrowLeftSquare:N5,ArrowLeftSquareIcon:N5,ArrowLeftToLine:TG,ArrowLeftToLineIcon:TG,ArrowRight:ci,ArrowRightCircle:a3,ArrowRightCircleIcon:a3,ArrowRightFromLine:EG,ArrowRightFromLineIcon:EG,ArrowRightIcon:ci,ArrowRightLeft:Jj,ArrowRightLeftIcon:Jj,ArrowRightSquare:E5,ArrowRightSquareIcon:E5,ArrowRightToLine:AG,ArrowRightToLineIcon:AG,ArrowUp:qu,ArrowUp01:MG,ArrowUp01Icon:MG,ArrowUp10:IG,ArrowUp10Icon:IG,ArrowUpAZ:MC,ArrowUpAZIcon:MC,ArrowUpAz:MC,ArrowUpAzIcon:MC,ArrowUpCircle:i3,ArrowUpCircleIcon:i3,ArrowUpDown:Uu,ArrowUpDownIcon:Uu,ArrowUpFromDot:PG,ArrowUpFromDotIcon:PG,ArrowUpFromLine:LG,ArrowUpFromLineIcon:LG,ArrowUpIcon:qu,ArrowUpLeft:DG,ArrowUpLeftFromCircle:r3,ArrowUpLeftFromCircleIcon:r3,ArrowUpLeftFromSquare:C5,ArrowUpLeftFromSquareIcon:C5,ArrowUpLeftIcon:DG,ArrowUpLeftSquare:A5,ArrowUpLeftSquareIcon:A5,ArrowUpNarrowWide:IC,ArrowUpNarrowWideIcon:IC,ArrowUpRight:dF,ArrowUpRightFromCircle:n3,ArrowUpRightFromCircleIcon:n3,ArrowUpRightFromSquare:T5,ArrowUpRightFromSquareIcon:T5,ArrowUpRightIcon:dF,ArrowUpRightSquare:M5,ArrowUpRightSquareIcon:M5,ArrowUpSquare:I5,ArrowUpSquareIcon:I5,ArrowUpToLine:RG,ArrowUpToLineIcon:RG,ArrowUpWideNarrow:OG,ArrowUpWideNarrowIcon:OG,ArrowUpZA:PC,ArrowUpZAIcon:PC,ArrowUpZa:PC,ArrowUpZaIcon:PC,ArrowsUpFromLine:FG,ArrowsUpFromLineIcon:FG,Asterisk:zG,AsteriskIcon:zG,AsteriskSquare:P5,AsteriskSquareIcon:P5,AtSign:BG,AtSignIcon:BG,Atom:$G,AtomIcon:$G,AudioLines:UG,AudioLinesIcon:UG,AudioWaveform:qG,AudioWaveformIcon:qG,Award:Uc,AwardIcon:Uc,Axe:VG,AxeIcon:VG,Axis3D:LC,Axis3DIcon:LC,Axis3d:LC,Axis3dIcon:LC,Baby:HG,BabyIcon:HG,Backpack:GG,BackpackIcon:GG,Badge:lW,BadgeAlert:WG,BadgeAlertIcon:WG,BadgeCent:KG,BadgeCentIcon:KG,BadgeCheck:DC,BadgeCheckIcon:DC,BadgeDollarSign:YG,BadgeDollarSignIcon:YG,BadgeEuro:ZG,BadgeEuroIcon:ZG,BadgeHelp:XG,BadgeHelpIcon:XG,BadgeIcon:lW,BadgeIndianRupee:QG,BadgeIndianRupeeIcon:QG,BadgeInfo:JG,BadgeInfoIcon:JG,BadgeJapaneseYen:eW,BadgeJapaneseYenIcon:eW,BadgeMinus:tW,BadgeMinusIcon:tW,BadgePercent:sW,BadgePercentIcon:sW,BadgePlus:rW,BadgePlusIcon:rW,BadgePoundSterling:nW,BadgePoundSterlingIcon:nW,BadgeRussianRuble:aW,BadgeRussianRubleIcon:aW,BadgeSwissFranc:iW,BadgeSwissFrancIcon:iW,BadgeX:oW,BadgeXIcon:oW,BaggageClaim:cW,BaggageClaimIcon:cW,Ban:uF,BanIcon:uF,Banana:dW,BananaIcon:dW,Bandage:uW,BandageIcon:uW,Banknote:hW,BanknoteIcon:hW,BarChart:KC,BarChart2:YC,BarChart2Icon:YC,BarChart3:Mo,BarChart3Icon:Mo,BarChart4:GC,BarChart4Icon:GC,BarChartBig:HC,BarChartBigIcon:HC,BarChartHorizontal:qC,BarChartHorizontalBig:UC,BarChartHorizontalBigIcon:UC,BarChartHorizontalIcon:qC,BarChartIcon:KC,Barcode:mW,BarcodeIcon:mW,Baseline:fW,BaselineIcon:fW,Bath:of,BathIcon:of,Battery:bW,BatteryCharging:pW,BatteryChargingIcon:pW,BatteryFull:xW,BatteryFullIcon:xW,BatteryIcon:bW,BatteryLow:gW,BatteryLowIcon:gW,BatteryMedium:yW,BatteryMediumIcon:yW,BatteryWarning:vW,BatteryWarningIcon:vW,Beaker:_W,BeakerIcon:_W,Bean:jW,BeanIcon:jW,BeanOff:wW,BeanOffIcon:wW,Bed:k0,BedDouble:e2,BedDoubleIcon:e2,BedIcon:k0,BedSingle:NW,BedSingleIcon:NW,Beef:kW,BeefIcon:kW,Beer:CW,BeerIcon:CW,BeerOff:SW,BeerOffIcon:SW,Bell:ym,BellDot:TW,BellDotIcon:TW,BellElectric:EW,BellElectricIcon:EW,BellIcon:ym,BellMinus:AW,BellMinusIcon:AW,BellOff:b_,BellOffIcon:b_,BellPlus:MW,BellPlusIcon:MW,BellRing:hF,BellRingIcon:hF,BetweenHorizonalEnd:RC,BetweenHorizonalEndIcon:RC,BetweenHorizonalStart:OC,BetweenHorizonalStartIcon:OC,BetweenHorizontalEnd:RC,BetweenHorizontalEndIcon:RC,BetweenHorizontalStart:OC,BetweenHorizontalStartIcon:OC,BetweenVerticalEnd:IW,BetweenVerticalEndIcon:IW,BetweenVerticalStart:PW,BetweenVerticalStartIcon:PW,BicepsFlexed:LW,BicepsFlexedIcon:LW,Bike:DW,BikeIcon:DW,Binary:RW,BinaryIcon:RW,Binoculars:OW,BinocularsIcon:OW,Biohazard:FW,BiohazardIcon:FW,Bird:zW,BirdIcon:zW,Bitcoin:BW,BitcoinIcon:BW,Blend:$W,BlendIcon:$W,Blinds:UW,BlindsIcon:UW,Blocks:qW,BlocksIcon:qW,Bluetooth:WW,BluetoothConnected:VW,BluetoothConnectedIcon:VW,BluetoothIcon:WW,BluetoothOff:HW,BluetoothOffIcon:HW,BluetoothSearching:GW,BluetoothSearchingIcon:GW,Bold:Jk,BoldIcon:Jk,Bolt:KW,BoltIcon:KW,Bomb:YW,BombIcon:YW,Bone:ZW,BoneIcon:ZW,Book:yK,BookA:XW,BookAIcon:XW,BookAudio:QW,BookAudioIcon:QW,BookCheck:JW,BookCheckIcon:JW,BookCopy:eK,BookCopyIcon:eK,BookDashed:FC,BookDashedIcon:FC,BookDown:tK,BookDownIcon:tK,BookHeadphones:sK,BookHeadphonesIcon:sK,BookHeart:rK,BookHeartIcon:rK,BookIcon:yK,BookImage:nK,BookImageIcon:nK,BookKey:aK,BookKeyIcon:aK,BookLock:iK,BookLockIcon:iK,BookMarked:oK,BookMarkedIcon:oK,BookMinus:lK,BookMinusIcon:lK,BookOpen:vm,BookOpenCheck:cK,BookOpenCheckIcon:cK,BookOpenIcon:vm,BookOpenText:dK,BookOpenTextIcon:dK,BookPlus:uK,BookPlusIcon:uK,BookTemplate:FC,BookTemplateIcon:FC,BookText:hK,BookTextIcon:hK,BookType:mK,BookTypeIcon:mK,BookUp:pK,BookUp2:fK,BookUp2Icon:fK,BookUpIcon:pK,BookUser:xK,BookUserIcon:xK,BookX:gK,BookXIcon:gK,Bookmark:Zy,BookmarkCheck:vK,BookmarkCheckIcon:vK,BookmarkIcon:Zy,BookmarkMinus:bK,BookmarkMinusIcon:bK,BookmarkPlus:mF,BookmarkPlusIcon:mF,BookmarkX:_K,BookmarkXIcon:_K,BoomBox:wK,BoomBoxIcon:wK,Bot:eS,BotIcon:eS,BotMessageSquare:jK,BotMessageSquareIcon:jK,BotOff:NK,BotOffIcon:NK,Box:fF,BoxIcon:fF,BoxSelect:q5,BoxSelectIcon:q5,Boxes:kK,BoxesIcon:kK,Braces:zC,BracesIcon:zC,Brackets:SK,BracketsIcon:SK,Brain:pF,BrainCircuit:CK,BrainCircuitIcon:CK,BrainCog:TK,BrainCogIcon:TK,BrainIcon:pF,BrickWall:EK,BrickWallIcon:EK,Briefcase:bm,BriefcaseBusiness:AK,BriefcaseBusinessIcon:AK,BriefcaseConveyorBelt:MK,BriefcaseConveyorBeltIcon:MK,BriefcaseIcon:bm,BriefcaseMedical:IK,BriefcaseMedicalIcon:IK,BringToFront:PK,BringToFrontIcon:PK,Brush:LK,BrushIcon:LK,Bug:OK,BugIcon:OK,BugOff:DK,BugOffIcon:DK,BugPlay:RK,BugPlayIcon:RK,Building:SE,Building2:Ga,Building2Icon:Ga,BuildingIcon:SE,Bus:zK,BusFront:FK,BusFrontIcon:FK,BusIcon:zK,Cable:$K,CableCar:BK,CableCarIcon:BK,CableIcon:$K,Cake:_m,CakeIcon:_m,CakeSlice:UK,CakeSliceIcon:UK,Calculator:__,CalculatorIcon:__,Calendar:vn,Calendar1:qK,Calendar1Icon:qK,CalendarArrowDown:VK,CalendarArrowDownIcon:VK,CalendarArrowUp:HK,CalendarArrowUpIcon:HK,CalendarCheck:xF,CalendarCheck2:GK,CalendarCheck2Icon:GK,CalendarCheckIcon:xF,CalendarClock:Xy,CalendarClockIcon:Xy,CalendarCog:WK,CalendarCogIcon:WK,CalendarDays:xu,CalendarDaysIcon:xu,CalendarFold:KK,CalendarFoldIcon:KK,CalendarHeart:gF,CalendarHeartIcon:gF,CalendarIcon:vn,CalendarMinus:ZK,CalendarMinus2:YK,CalendarMinus2Icon:YK,CalendarMinusIcon:ZK,CalendarOff:yF,CalendarOffIcon:yF,CalendarPlus:Gj,CalendarPlus2:XK,CalendarPlus2Icon:XK,CalendarPlusIcon:Gj,CalendarRange:QK,CalendarRangeIcon:QK,CalendarSearch:JK,CalendarSearchIcon:JK,CalendarSync:eY,CalendarSyncIcon:eY,CalendarX:sY,CalendarX2:tY,CalendarX2Icon:tY,CalendarXIcon:sY,Camera:Tp,CameraIcon:Tp,CameraOff:rY,CameraOffIcon:rY,CandlestickChart:VC,CandlestickChartIcon:VC,Candy:iY,CandyCane:nY,CandyCaneIcon:nY,CandyIcon:iY,CandyOff:aY,CandyOffIcon:aY,Cannabis:oY,CannabisIcon:oY,Captions:BC,CaptionsIcon:BC,CaptionsOff:lY,CaptionsOffIcon:lY,Car:uY,CarFront:cY,CarFrontIcon:cY,CarIcon:uY,CarTaxiFront:dY,CarTaxiFrontIcon:dY,Caravan:hY,CaravanIcon:hY,Carrot:mY,CarrotIcon:mY,CaseLower:fY,CaseLowerIcon:fY,CaseSensitive:pY,CaseSensitiveIcon:pY,CaseUpper:xY,CaseUpperIcon:xY,CassetteTape:gY,CassetteTapeIcon:gY,Cast:yY,CastIcon:yY,Castle:vY,CastleIcon:vY,Cat:bY,CatIcon:bY,Cctv:_Y,CctvIcon:_Y,ChartArea:$C,ChartAreaIcon:$C,ChartBar:qC,ChartBarBig:UC,ChartBarBigIcon:UC,ChartBarDecreasing:wY,ChartBarDecreasingIcon:wY,ChartBarIcon:qC,ChartBarIncreasing:jY,ChartBarIncreasingIcon:jY,ChartBarStacked:NY,ChartBarStackedIcon:NY,ChartCandlestick:VC,ChartCandlestickIcon:VC,ChartColumn:Mo,ChartColumnBig:HC,ChartColumnBigIcon:HC,ChartColumnDecreasing:kY,ChartColumnDecreasingIcon:kY,ChartColumnIcon:Mo,ChartColumnIncreasing:GC,ChartColumnIncreasingIcon:GC,ChartColumnStacked:SY,ChartColumnStackedIcon:SY,ChartGantt:CY,ChartGanttIcon:CY,ChartLine:WC,ChartLineIcon:WC,ChartNetwork:TY,ChartNetworkIcon:TY,ChartNoAxesColumn:YC,ChartNoAxesColumnDecreasing:EY,ChartNoAxesColumnDecreasingIcon:EY,ChartNoAxesColumnIcon:YC,ChartNoAxesColumnIncreasing:KC,ChartNoAxesColumnIncreasingIcon:KC,ChartNoAxesCombined:AY,ChartNoAxesCombinedIcon:AY,ChartNoAxesGantt:ZC,ChartNoAxesGanttIcon:ZC,ChartPie:XC,ChartPieIcon:XC,ChartScatter:QC,ChartScatterIcon:QC,ChartSpline:MY,ChartSplineIcon:MY,Check:la,CheckCheck:vF,CheckCheckIcon:vF,CheckCircle:Ti,CheckCircle2:qn,CheckCircle2Icon:qn,CheckCircleIcon:Ti,CheckIcon:la,CheckSquare:zj,CheckSquare2:D5,CheckSquare2Icon:D5,CheckSquareIcon:zj,ChefHat:IY,ChefHatIcon:IY,Cherry:PY,CherryIcon:PY,ChevronDown:Co,ChevronDownCircle:o3,ChevronDownCircleIcon:o3,ChevronDownIcon:Co,ChevronDownSquare:R5,ChevronDownSquareIcon:R5,ChevronFirst:LY,ChevronFirstIcon:LY,ChevronLast:DY,ChevronLastIcon:DY,ChevronLeft:jl,ChevronLeftCircle:l3,ChevronLeftCircleIcon:l3,ChevronLeftIcon:jl,ChevronLeftSquare:O5,ChevronLeftSquareIcon:O5,ChevronRight:Ia,ChevronRightCircle:c3,ChevronRightCircleIcon:c3,ChevronRightIcon:Ia,ChevronRightSquare:F5,ChevronRightSquareIcon:F5,ChevronUp:pg,ChevronUpCircle:d3,ChevronUpCircleIcon:d3,ChevronUpIcon:pg,ChevronUpSquare:z5,ChevronUpSquareIcon:z5,ChevronsDown:OY,ChevronsDownIcon:OY,ChevronsDownUp:RY,ChevronsDownUpIcon:RY,ChevronsLeft:BY,ChevronsLeftIcon:BY,ChevronsLeftRight:zY,ChevronsLeftRightEllipsis:FY,ChevronsLeftRightEllipsisIcon:FY,ChevronsLeftRightIcon:zY,ChevronsRight:UY,ChevronsRightIcon:UY,ChevronsRightLeft:$Y,ChevronsRightLeftIcon:$Y,ChevronsUp:qY,ChevronsUpDown:xg,ChevronsUpDownIcon:xg,ChevronsUpIcon:qY,Chrome:CE,ChromeIcon:CE,Church:VY,ChurchIcon:VY,Cigarette:GY,CigaretteIcon:GY,CigaretteOff:HY,CigaretteOffIcon:HY,Circle:Rh,CircleAlert:go,CircleAlertIcon:go,CircleArrowDown:JC,CircleArrowDownIcon:JC,CircleArrowLeft:e3,CircleArrowLeftIcon:e3,CircleArrowOutDownLeft:t3,CircleArrowOutDownLeftIcon:t3,CircleArrowOutDownRight:s3,CircleArrowOutDownRightIcon:s3,CircleArrowOutUpLeft:r3,CircleArrowOutUpLeftIcon:r3,CircleArrowOutUpRight:n3,CircleArrowOutUpRightIcon:n3,CircleArrowRight:a3,CircleArrowRightIcon:a3,CircleArrowUp:i3,CircleArrowUpIcon:i3,CircleCheck:qn,CircleCheckBig:Ti,CircleCheckBigIcon:Ti,CircleCheckIcon:qn,CircleChevronDown:o3,CircleChevronDownIcon:o3,CircleChevronLeft:l3,CircleChevronLeftIcon:l3,CircleChevronRight:c3,CircleChevronRightIcon:c3,CircleChevronUp:d3,CircleChevronUpIcon:d3,CircleDashed:WY,CircleDashedIcon:WY,CircleDivide:u3,CircleDivideIcon:u3,CircleDollarSign:KY,CircleDollarSignIcon:KY,CircleDot:ZY,CircleDotDashed:YY,CircleDotDashedIcon:YY,CircleDotIcon:ZY,CircleEllipsis:XY,CircleEllipsisIcon:XY,CircleEqual:QY,CircleEqualIcon:QY,CircleFadingArrowUp:JY,CircleFadingArrowUpIcon:JY,CircleFadingPlus:eZ,CircleFadingPlusIcon:eZ,CircleGauge:h3,CircleGaugeIcon:h3,CircleHelp:e_,CircleHelpIcon:e_,CircleIcon:Rh,CircleMinus:m3,CircleMinusIcon:m3,CircleOff:tZ,CircleOffIcon:tZ,CircleParking:p3,CircleParkingIcon:p3,CircleParkingOff:f3,CircleParkingOffIcon:f3,CirclePause:x3,CirclePauseIcon:x3,CirclePercent:g3,CirclePercentIcon:g3,CirclePlay:Ff,CirclePlayIcon:Ff,CirclePlus:y3,CirclePlusIcon:y3,CirclePower:v3,CirclePowerIcon:v3,CircleSlash:sZ,CircleSlash2:b3,CircleSlash2Icon:b3,CircleSlashIcon:sZ,CircleSlashed:b3,CircleSlashedIcon:b3,CircleStop:_3,CircleStopIcon:_3,CircleUser:j3,CircleUserIcon:j3,CircleUserRound:w3,CircleUserRoundIcon:w3,CircleX:ad,CircleXIcon:ad,CircuitBoard:rZ,CircuitBoardIcon:rZ,Citrus:nZ,CitrusIcon:nZ,Clapperboard:aZ,ClapperboardIcon:aZ,Clipboard:hZ,ClipboardCheck:VI,ClipboardCheckIcon:VI,ClipboardCopy:iZ,ClipboardCopyIcon:iZ,ClipboardEdit:k3,ClipboardEditIcon:k3,ClipboardIcon:hZ,ClipboardList:k1,ClipboardListIcon:k1,ClipboardMinus:oZ,ClipboardMinusIcon:oZ,ClipboardPaste:lZ,ClipboardPasteIcon:lZ,ClipboardPen:k3,ClipboardPenIcon:k3,ClipboardPenLine:N3,ClipboardPenLineIcon:N3,ClipboardPlus:cZ,ClipboardPlusIcon:cZ,ClipboardSignature:N3,ClipboardSignatureIcon:N3,ClipboardType:dZ,ClipboardTypeIcon:dZ,ClipboardX:uZ,ClipboardXIcon:uZ,Clock:jn,Clock1:mZ,Clock10:fZ,Clock10Icon:fZ,Clock11:pZ,Clock11Icon:pZ,Clock12:xZ,Clock12Icon:xZ,Clock1Icon:mZ,Clock2:gZ,Clock2Icon:gZ,Clock3:yZ,Clock3Icon:yZ,Clock4:vZ,Clock4Icon:vZ,Clock5:bZ,Clock5Icon:bZ,Clock6:_Z,Clock6Icon:_Z,Clock7:wZ,Clock7Icon:wZ,Clock8:jZ,Clock8Icon:jZ,Clock9:NZ,Clock9Icon:NZ,ClockAlert:kZ,ClockAlertIcon:kZ,ClockArrowDown:SZ,ClockArrowDownIcon:SZ,ClockArrowUp:CZ,ClockArrowUpIcon:CZ,ClockIcon:jn,Cloud:UZ,CloudAlert:TZ,CloudAlertIcon:TZ,CloudCog:EZ,CloudCogIcon:EZ,CloudDownload:S3,CloudDownloadIcon:S3,CloudDrizzle:AZ,CloudDrizzleIcon:AZ,CloudFog:MZ,CloudFogIcon:MZ,CloudHail:IZ,CloudHailIcon:IZ,CloudIcon:UZ,CloudLightning:PZ,CloudLightningIcon:PZ,CloudMoon:DZ,CloudMoonIcon:DZ,CloudMoonRain:LZ,CloudMoonRainIcon:LZ,CloudOff:RZ,CloudOffIcon:RZ,CloudRain:FZ,CloudRainIcon:FZ,CloudRainWind:OZ,CloudRainWindIcon:OZ,CloudSnow:zZ,CloudSnowIcon:zZ,CloudSun:$Z,CloudSunIcon:$Z,CloudSunRain:BZ,CloudSunRainIcon:BZ,CloudUpload:C3,CloudUploadIcon:C3,Cloudy:qZ,CloudyIcon:qZ,Clover:Wj,CloverIcon:Wj,Club:VZ,ClubIcon:VZ,Code:TE,Code2:Rj,Code2Icon:Rj,CodeIcon:TE,CodeSquare:B5,CodeSquareIcon:B5,CodeXml:Rj,CodeXmlIcon:Rj,Codepen:HZ,CodepenIcon:HZ,Codesandbox:GZ,CodesandboxIcon:GZ,Coffee:EE,CoffeeIcon:EE,Cog:WZ,CogIcon:WZ,Coins:bF,CoinsIcon:bF,Columns:T3,Columns2:T3,Columns2Icon:T3,Columns3:E3,Columns3Icon:E3,Columns4:KZ,Columns4Icon:KZ,ColumnsIcon:T3,Combine:YZ,CombineIcon:YZ,Command:ZZ,CommandIcon:ZZ,Compass:HI,CompassIcon:HI,Component:XZ,ComponentIcon:XZ,Computer:QZ,ComputerIcon:QZ,ConciergeBell:JZ,ConciergeBellIcon:JZ,Cone:eX,ConeIcon:eX,Construction:tX,ConstructionIcon:tX,Contact:AE,Contact2:A3,Contact2Icon:A3,ContactIcon:AE,ContactRound:A3,ContactRoundIcon:A3,Container:sX,ContainerIcon:sX,Contrast:rX,ContrastIcon:rX,Cookie:nX,CookieIcon:nX,CookingPot:aX,CookingPotIcon:aX,Copy:si,CopyCheck:iX,CopyCheckIcon:iX,CopyIcon:si,CopyMinus:oX,CopyMinusIcon:oX,CopyPlus:lX,CopyPlusIcon:lX,CopySlash:cX,CopySlashIcon:cX,CopyX:dX,CopyXIcon:dX,Copyleft:uX,CopyleftIcon:uX,Copyright:hX,CopyrightIcon:hX,CornerDownLeft:mX,CornerDownLeftIcon:mX,CornerDownRight:fX,CornerDownRightIcon:fX,CornerLeftDown:pX,CornerLeftDownIcon:pX,CornerLeftUp:xX,CornerLeftUpIcon:xX,CornerRightDown:gX,CornerRightDownIcon:gX,CornerRightUp:yX,CornerRightUpIcon:yX,CornerUpLeft:vX,CornerUpLeftIcon:vX,CornerUpRight:bX,CornerUpRightIcon:bX,Cpu:_X,CpuIcon:_X,CreativeCommons:wX,CreativeCommonsIcon:wX,CreditCard:S0,CreditCardIcon:S0,Croissant:jX,CroissantIcon:jX,Crop:NX,CropIcon:NX,Cross:kX,CrossIcon:kX,Crosshair:SX,CrosshairIcon:SX,Crown:Gf,CrownIcon:Gf,Cuboid:CX,CuboidIcon:CX,CupSoda:TX,CupSodaIcon:TX,CurlyBraces:zC,CurlyBracesIcon:zC,Currency:EX,CurrencyIcon:EX,Cylinder:AX,CylinderIcon:AX,Dam:MX,DamIcon:MX,Database:_F,DatabaseBackup:IX,DatabaseBackupIcon:IX,DatabaseIcon:_F,DatabaseZap:PX,DatabaseZapIcon:PX,Delete:LX,DeleteIcon:LX,Dessert:DX,DessertIcon:DX,Diameter:RX,DiameterIcon:RX,Diamond:zX,DiamondIcon:zX,DiamondMinus:OX,DiamondMinusIcon:OX,DiamondPercent:M3,DiamondPercentIcon:M3,DiamondPlus:FX,DiamondPlusIcon:FX,Dice1:BX,Dice1Icon:BX,Dice2:$X,Dice2Icon:$X,Dice3:UX,Dice3Icon:UX,Dice4:qX,Dice4Icon:qX,Dice5:VX,Dice5Icon:VX,Dice6:HX,Dice6Icon:HX,Dices:GX,DicesIcon:GX,Diff:WX,DiffIcon:WX,Disc:XX,Disc2:KX,Disc2Icon:KX,Disc3:YX,Disc3Icon:YX,DiscAlbum:ZX,DiscAlbumIcon:ZX,DiscIcon:XX,Divide:QX,DivideCircle:u3,DivideCircleIcon:u3,DivideIcon:QX,DivideSquare:V5,DivideSquareIcon:V5,Dna:eQ,DnaIcon:eQ,DnaOff:JX,DnaOffIcon:JX,Dock:tQ,DockIcon:tQ,Dog:sQ,DogIcon:sQ,DollarSign:Xl,DollarSignIcon:Xl,Donut:rQ,DonutIcon:rQ,DoorClosed:nQ,DoorClosedIcon:nQ,DoorOpen:w_,DoorOpenIcon:w_,Dot:aQ,DotIcon:aQ,DotSquare:H5,DotSquareIcon:H5,Download:li,DownloadCloud:S3,DownloadCloudIcon:S3,DownloadIcon:li,DraftingCompass:iQ,DraftingCompassIcon:iQ,Drama:oQ,DramaIcon:oQ,Dribbble:lQ,DribbbleIcon:lQ,Drill:cQ,DrillIcon:cQ,Droplet:dQ,DropletIcon:dQ,Droplets:S1,DropletsIcon:S1,Drum:uQ,DrumIcon:uQ,Drumstick:hQ,DrumstickIcon:hQ,Dumbbell:mQ,DumbbellIcon:mQ,Ear:pQ,EarIcon:pQ,EarOff:fQ,EarOffIcon:fQ,Earth:I3,EarthIcon:I3,EarthLock:xQ,EarthLockIcon:xQ,Eclipse:gQ,EclipseIcon:gQ,Edit:iu,Edit2:zy,Edit2Icon:zy,Edit3:t_,Edit3Icon:t_,EditIcon:iu,Egg:GI,EggFried:yQ,EggFriedIcon:yQ,EggIcon:GI,EggOff:vQ,EggOffIcon:vQ,Ellipsis:f0,EllipsisIcon:f0,EllipsisVertical:Fy,EllipsisVerticalIcon:Fy,Equal:wQ,EqualApproximately:bQ,EqualApproximatelyIcon:bQ,EqualIcon:wQ,EqualNot:_Q,EqualNotIcon:_Q,EqualSquare:G5,EqualSquareIcon:G5,Eraser:jQ,EraserIcon:jQ,EthernetPort:NQ,EthernetPortIcon:NQ,Euro:kQ,EuroIcon:kQ,Expand:SQ,ExpandIcon:SQ,ExternalLink:un,ExternalLinkIcon:un,Eye:Nn,EyeClosed:CQ,EyeClosedIcon:CQ,EyeIcon:Nn,EyeOff:Wf,EyeOffIcon:Wf,Facebook:mh,FacebookIcon:mh,Factory:TQ,FactoryIcon:TQ,Fan:EQ,FanIcon:EQ,FastForward:AQ,FastForwardIcon:AQ,Feather:MQ,FeatherIcon:MQ,Fence:IQ,FenceIcon:IQ,FerrisWheel:PQ,FerrisWheelIcon:PQ,Figma:LQ,FigmaIcon:LQ,File:WI,FileArchive:DQ,FileArchiveIcon:DQ,FileAudio:OQ,FileAudio2:RQ,FileAudio2Icon:RQ,FileAudioIcon:OQ,FileAxis3D:P3,FileAxis3DIcon:P3,FileAxis3d:P3,FileAxis3dIcon:P3,FileBadge:zQ,FileBadge2:FQ,FileBadge2Icon:FQ,FileBadgeIcon:zQ,FileBarChart:L3,FileBarChart2:D3,FileBarChart2Icon:D3,FileBarChartIcon:L3,FileBox:BQ,FileBoxIcon:BQ,FileChartColumn:D3,FileChartColumnIcon:D3,FileChartColumnIncreasing:L3,FileChartColumnIncreasingIcon:L3,FileChartLine:R3,FileChartLineIcon:R3,FileChartPie:O3,FileChartPieIcon:O3,FileCheck:wF,FileCheck2:$Q,FileCheck2Icon:$Q,FileCheckIcon:wF,FileClock:UQ,FileClockIcon:UQ,FileCode:VQ,FileCode2:qQ,FileCode2Icon:qQ,FileCodeIcon:VQ,FileCog:F3,FileCog2:F3,FileCog2Icon:F3,FileCogIcon:F3,FileDiff:HQ,FileDiffIcon:HQ,FileDigit:GQ,FileDigitIcon:GQ,FileDown:ME,FileDownIcon:ME,FileEdit:B3,FileEditIcon:B3,FileHeart:WQ,FileHeartIcon:WQ,FileIcon:WI,FileImage:t2,FileImageIcon:t2,FileInput:KQ,FileInputIcon:KQ,FileJson:ZQ,FileJson2:YQ,FileJson2Icon:YQ,FileJsonIcon:ZQ,FileKey:QQ,FileKey2:XQ,FileKey2Icon:XQ,FileKeyIcon:QQ,FileLineChart:R3,FileLineChartIcon:R3,FileLock:eJ,FileLock2:JQ,FileLock2Icon:JQ,FileLockIcon:eJ,FileMinus:sJ,FileMinus2:tJ,FileMinus2Icon:tJ,FileMinusIcon:sJ,FileMusic:rJ,FileMusicIcon:rJ,FileOutput:nJ,FileOutputIcon:nJ,FilePen:B3,FilePenIcon:B3,FilePenLine:z3,FilePenLineIcon:z3,FilePieChart:O3,FilePieChartIcon:O3,FilePlus:iJ,FilePlus2:aJ,FilePlus2Icon:aJ,FilePlusIcon:iJ,FileQuestion:oJ,FileQuestionIcon:oJ,FileScan:lJ,FileScanIcon:lJ,FileSearch:dJ,FileSearch2:cJ,FileSearch2Icon:cJ,FileSearchIcon:dJ,FileSignature:z3,FileSignatureIcon:z3,FileSliders:uJ,FileSlidersIcon:uJ,FileSpreadsheet:s2,FileSpreadsheetIcon:s2,FileStack:jF,FileStackIcon:jF,FileSymlink:hJ,FileSymlinkIcon:hJ,FileTerminal:mJ,FileTerminalIcon:mJ,FileText:En,FileTextIcon:En,FileType:pJ,FileType2:fJ,FileType2Icon:fJ,FileTypeIcon:pJ,FileUp:xJ,FileUpIcon:xJ,FileUser:gJ,FileUserIcon:gJ,FileVideo:NF,FileVideo2:yJ,FileVideo2Icon:yJ,FileVideoIcon:NF,FileVolume:bJ,FileVolume2:vJ,FileVolume2Icon:vJ,FileVolumeIcon:bJ,FileWarning:_J,FileWarningIcon:_J,FileX:jJ,FileX2:wJ,FileX2Icon:wJ,FileXIcon:jJ,Files:NJ,FilesIcon:NJ,Film:rf,FilmIcon:rf,Filter:C1,FilterIcon:C1,FilterX:kJ,FilterXIcon:kJ,Fingerprint:SJ,FingerprintIcon:SJ,FireExtinguisher:CJ,FireExtinguisherIcon:CJ,Fish:AJ,FishIcon:AJ,FishOff:TJ,FishOffIcon:TJ,FishSymbol:EJ,FishSymbolIcon:EJ,Flag:r2,FlagIcon:r2,FlagOff:MJ,FlagOffIcon:MJ,FlagTriangleLeft:IJ,FlagTriangleLeftIcon:IJ,FlagTriangleRight:PJ,FlagTriangleRightIcon:PJ,Flame:ld,FlameIcon:ld,FlameKindling:LJ,FlameKindlingIcon:LJ,Flashlight:RJ,FlashlightIcon:RJ,FlashlightOff:DJ,FlashlightOffIcon:DJ,FlaskConical:tS,FlaskConicalIcon:tS,FlaskConicalOff:OJ,FlaskConicalOffIcon:OJ,FlaskRound:FJ,FlaskRoundIcon:FJ,FlipHorizontal:kF,FlipHorizontal2:zJ,FlipHorizontal2Icon:zJ,FlipHorizontalIcon:kF,FlipVertical:$J,FlipVertical2:BJ,FlipVertical2Icon:BJ,FlipVerticalIcon:$J,Flower:UJ,Flower2:b1,Flower2Icon:b1,FlowerIcon:UJ,Focus:qJ,FocusIcon:qJ,FoldHorizontal:VJ,FoldHorizontalIcon:VJ,FoldVertical:HJ,FoldVerticalIcon:HJ,Folder:yee,FolderArchive:GJ,FolderArchiveIcon:GJ,FolderCheck:WJ,FolderCheckIcon:WJ,FolderClock:KJ,FolderClockIcon:KJ,FolderClosed:YJ,FolderClosedIcon:YJ,FolderCode:ZJ,FolderCodeIcon:ZJ,FolderCog:$3,FolderCog2:$3,FolderCog2Icon:$3,FolderCogIcon:$3,FolderDot:XJ,FolderDotIcon:XJ,FolderDown:QJ,FolderDownIcon:QJ,FolderEdit:U3,FolderEditIcon:U3,FolderGit:eee,FolderGit2:JJ,FolderGit2Icon:JJ,FolderGitIcon:eee,FolderHeart:tee,FolderHeartIcon:tee,FolderIcon:yee,FolderInput:see,FolderInputIcon:see,FolderKanban:ree,FolderKanbanIcon:ree,FolderKey:nee,FolderKeyIcon:nee,FolderLock:aee,FolderLockIcon:aee,FolderMinus:iee,FolderMinusIcon:iee,FolderOpen:Kf,FolderOpenDot:oee,FolderOpenDotIcon:oee,FolderOpenIcon:Kf,FolderOutput:lee,FolderOutputIcon:lee,FolderPen:U3,FolderPenIcon:U3,FolderPlus:cee,FolderPlusIcon:cee,FolderRoot:dee,FolderRootIcon:dee,FolderSearch:hee,FolderSearch2:uee,FolderSearch2Icon:uee,FolderSearchIcon:hee,FolderSymlink:mee,FolderSymlinkIcon:mee,FolderSync:fee,FolderSyncIcon:fee,FolderTree:pee,FolderTreeIcon:pee,FolderUp:xee,FolderUpIcon:xee,FolderX:gee,FolderXIcon:gee,Folders:vee,FoldersIcon:vee,Footprints:bee,FootprintsIcon:bee,ForkKnife:MT,ForkKnifeCrossed:AT,ForkKnifeCrossedIcon:AT,ForkKnifeIcon:MT,Forklift:_ee,ForkliftIcon:_ee,FormInput:h5,FormInputIcon:h5,Forward:wee,ForwardIcon:wee,Frame:jee,FrameIcon:jee,Framer:Nee,FramerIcon:Nee,Frown:kee,FrownIcon:kee,Fuel:See,FuelIcon:See,Fullscreen:Cee,FullscreenIcon:Cee,FunctionSquare:W5,FunctionSquareIcon:W5,GalleryHorizontal:Eee,GalleryHorizontalEnd:Tee,GalleryHorizontalEndIcon:Tee,GalleryHorizontalIcon:Eee,GalleryThumbnails:Aee,GalleryThumbnailsIcon:Aee,GalleryVertical:Iee,GalleryVerticalEnd:Mee,GalleryVerticalEndIcon:Mee,GalleryVerticalIcon:Iee,Gamepad:Lee,Gamepad2:Pee,Gamepad2Icon:Pee,GamepadIcon:Lee,GanttChart:ZC,GanttChartIcon:ZC,GanttChartSquare:$b,GanttChartSquareIcon:$b,Gauge:Dee,GaugeCircle:h3,GaugeCircleIcon:h3,GaugeIcon:Dee,Gavel:Ree,GavelIcon:Ree,Gem:Oee,GemIcon:Oee,Ghost:IE,GhostIcon:IE,Gift:Di,GiftIcon:Di,GitBranch:zee,GitBranchIcon:zee,GitBranchPlus:Fee,GitBranchPlusIcon:Fee,GitCommit:q3,GitCommitHorizontal:q3,GitCommitHorizontalIcon:q3,GitCommitIcon:q3,GitCommitVertical:Bee,GitCommitVerticalIcon:Bee,GitCompare:Uee,GitCompareArrows:$ee,GitCompareArrowsIcon:$ee,GitCompareIcon:Uee,GitFork:qee,GitForkIcon:qee,GitGraph:Vee,GitGraphIcon:Vee,GitMerge:Hee,GitMergeIcon:Hee,GitPullRequest:Xee,GitPullRequestArrow:Gee,GitPullRequestArrowIcon:Gee,GitPullRequestClosed:Wee,GitPullRequestClosedIcon:Wee,GitPullRequestCreate:Yee,GitPullRequestCreateArrow:Kee,GitPullRequestCreateArrowIcon:Kee,GitPullRequestCreateIcon:Yee,GitPullRequestDraft:Zee,GitPullRequestDraftIcon:Zee,GitPullRequestIcon:Xee,Github:Qee,GithubIcon:Qee,Gitlab:Jee,GitlabIcon:Jee,GlassWater:ete,GlassWaterIcon:ete,Glasses:tte,GlassesIcon:tte,Globe:Ql,Globe2:I3,Globe2Icon:I3,GlobeIcon:Ql,GlobeLock:ste,GlobeLockIcon:ste,Goal:rte,GoalIcon:rte,Grab:nte,GrabIcon:nte,GraduationCap:ch,GraduationCapIcon:ch,Grape:ate,GrapeIcon:ate,Grid:Ey,Grid2X2:H3,Grid2X2Icon:H3,Grid2X2Plus:V3,Grid2X2PlusIcon:V3,Grid2x2:H3,Grid2x2Check:ite,Grid2x2CheckIcon:ite,Grid2x2Icon:H3,Grid2x2Plus:V3,Grid2x2PlusIcon:V3,Grid2x2X:ote,Grid2x2XIcon:ote,Grid3X3:Ey,Grid3X3Icon:Ey,Grid3x3:Ey,Grid3x3Icon:Ey,GridIcon:Ey,Grip:cte,GripHorizontal:lte,GripHorizontalIcon:lte,GripIcon:cte,GripVertical:Vu,GripVerticalIcon:Vu,Group:dte,GroupIcon:dte,Guitar:ute,GuitarIcon:ute,Ham:hte,HamIcon:hte,Hammer:SF,HammerIcon:SF,Hand:CF,HandCoins:mte,HandCoinsIcon:mte,HandHeart:fte,HandHeartIcon:fte,HandHelping:p1,HandHelpingIcon:p1,HandIcon:CF,HandMetal:pte,HandMetalIcon:pte,HandPlatter:xte,HandPlatterIcon:xte,Handshake:j_,HandshakeIcon:j_,HardDrive:TF,HardDriveDownload:gte,HardDriveDownloadIcon:gte,HardDriveIcon:TF,HardDriveUpload:yte,HardDriveUploadIcon:yte,HardHat:vte,HardHatIcon:vte,Hash:sS,HashIcon:sS,Haze:bte,HazeIcon:bte,HdmiPort:_te,HdmiPortIcon:_te,Heading:kte,Heading1:KI,Heading1Icon:KI,Heading2:YI,Heading2Icon:YI,Heading3:EF,Heading3Icon:EF,Heading4:wte,Heading4Icon:wte,Heading5:jte,Heading5Icon:jte,Heading6:Nte,Heading6Icon:Nte,HeadingIcon:kte,HeadphoneOff:Ste,HeadphoneOffIcon:Ste,Headphones:Cte,HeadphonesIcon:Cte,Headset:Tte,HeadsetIcon:Tte,Heart:yi,HeartCrack:Ete,HeartCrackIcon:Ete,HeartHandshake:Ate,HeartHandshakeIcon:Ate,HeartIcon:yi,HeartOff:Mte,HeartOffIcon:Mte,HeartPulse:Ite,HeartPulseIcon:Ite,Heater:Pte,HeaterIcon:Pte,HelpCircle:e_,HelpCircleIcon:e_,HelpingHand:p1,HelpingHandIcon:p1,Hexagon:Lte,HexagonIcon:Lte,Highlighter:Dte,HighlighterIcon:Dte,History:ZI,HistoryIcon:ZI,Home:Pn,HomeIcon:Pn,Hop:Ote,HopIcon:Ote,HopOff:Rte,HopOffIcon:Rte,Hospital:Fte,HospitalIcon:Fte,Hotel:zte,HotelIcon:zte,Hourglass:Bte,HourglassIcon:Bte,House:Pn,HouseIcon:Pn,HousePlug:$te,HousePlugIcon:$te,HousePlus:Ute,HousePlusIcon:Ute,IceCream:W3,IceCream2:G3,IceCream2Icon:G3,IceCreamBowl:G3,IceCreamBowlIcon:G3,IceCreamCone:W3,IceCreamConeIcon:W3,IceCreamIcon:W3,Icon:set,IdCard:qte,IdCardIcon:qte,Image:zo,ImageDown:Vte,ImageDownIcon:Vte,ImageIcon:zo,ImageMinus:Hte,ImageMinusIcon:Hte,ImageOff:Gte,ImageOffIcon:Gte,ImagePlay:Wte,ImagePlayIcon:Wte,ImagePlus:Qy,ImagePlusIcon:Qy,ImageUp:Kte,ImageUpIcon:Kte,ImageUpscale:Yte,ImageUpscaleIcon:Yte,Images:Zte,ImagesIcon:Zte,Import:Xte,ImportIcon:Xte,Inbox:n2,InboxIcon:n2,Indent:Y3,IndentDecrease:K3,IndentDecreaseIcon:K3,IndentIcon:Y3,IndentIncrease:Y3,IndentIncreaseIcon:Y3,IndianRupee:Qte,IndianRupeeIcon:Qte,Infinity:Jte,InfinityIcon:Jte,Info:a2,InfoIcon:a2,Inspect:J5,InspectIcon:J5,InspectionPanel:ese,InspectionPanelIcon:ese,Instagram:gu,InstagramIcon:gu,Italic:rS,ItalicIcon:rS,IterationCcw:tse,IterationCcwIcon:tse,IterationCw:sse,IterationCwIcon:sse,JapaneseYen:rse,JapaneseYenIcon:rse,Joystick:nse,JoystickIcon:nse,Kanban:i2,KanbanIcon:i2,KanbanSquare:K5,KanbanSquareDashed:$5,KanbanSquareDashedIcon:$5,KanbanSquareIcon:K5,Key:gg,KeyIcon:gg,KeyRound:PE,KeyRoundIcon:PE,KeySquare:ase,KeySquareIcon:ase,Keyboard:lse,KeyboardIcon:lse,KeyboardMusic:ise,KeyboardMusicIcon:ise,KeyboardOff:ose,KeyboardOffIcon:ose,Lamp:fse,LampCeiling:cse,LampCeilingIcon:cse,LampDesk:dse,LampDeskIcon:dse,LampFloor:use,LampFloorIcon:use,LampIcon:fse,LampWallDown:hse,LampWallDownIcon:hse,LampWallUp:mse,LampWallUpIcon:mse,LandPlot:pse,LandPlotIcon:pse,Landmark:xse,LandmarkIcon:xse,Languages:gse,LanguagesIcon:gse,Laptop:vse,Laptop2:Z3,Laptop2Icon:Z3,LaptopIcon:vse,LaptopMinimal:Z3,LaptopMinimalCheck:yse,LaptopMinimalCheckIcon:yse,LaptopMinimalIcon:Z3,Lasso:_se,LassoIcon:_se,LassoSelect:bse,LassoSelectIcon:bse,Laugh:wse,LaughIcon:wse,Layers:AF,Layers2:jse,Layers2Icon:jse,Layers3:Nse,Layers3Icon:Nse,LayersIcon:AF,Layout:Fj,LayoutDashboard:LE,LayoutDashboardIcon:LE,LayoutGrid:Ep,LayoutGridIcon:Ep,LayoutIcon:Fj,LayoutList:kse,LayoutListIcon:kse,LayoutPanelLeft:Sse,LayoutPanelLeftIcon:Sse,LayoutPanelTop:Cse,LayoutPanelTopIcon:Cse,LayoutTemplate:DE,LayoutTemplateIcon:DE,Leaf:Tse,LeafIcon:Tse,LeafyGreen:Ese,LeafyGreenIcon:Ese,Lectern:Ase,LecternIcon:Ase,LetterText:Mse,LetterTextIcon:Mse,Library:nS,LibraryBig:Ise,LibraryBigIcon:Ise,LibraryIcon:nS,LibrarySquare:Y5,LibrarySquareIcon:Y5,LifeBuoy:XI,LifeBuoyIcon:XI,Ligature:Pse,LigatureIcon:Pse,Lightbulb:o2,LightbulbIcon:o2,LightbulbOff:Lse,LightbulbOffIcon:Lse,LineChart:WC,LineChartIcon:WC,Link:tl,Link2:Ul,Link2Icon:Ul,Link2Off:Dse,Link2OffIcon:Dse,LinkIcon:tl,Linkedin:Yf,LinkedinIcon:Yf,List:Zf,ListCheck:Rse,ListCheckIcon:Rse,ListChecks:l2,ListChecksIcon:l2,ListCollapse:Ose,ListCollapseIcon:Ose,ListEnd:Fse,ListEndIcon:Fse,ListFilter:MF,ListFilterIcon:MF,ListIcon:Zf,ListMinus:zse,ListMinusIcon:zse,ListMusic:Bse,ListMusicIcon:Bse,ListOrdered:T1,ListOrderedIcon:T1,ListPlus:$se,ListPlusIcon:$se,ListRestart:Use,ListRestartIcon:Use,ListStart:qse,ListStartIcon:qse,ListTodo:Vse,ListTodoIcon:Vse,ListTree:Hse,ListTreeIcon:Hse,ListVideo:Gse,ListVideoIcon:Gse,ListX:Wse,ListXIcon:Wse,Loader:Yse,Loader2:ls,Loader2Icon:ls,LoaderCircle:ls,LoaderCircleIcon:ls,LoaderIcon:Yse,LoaderPinwheel:Kse,LoaderPinwheelIcon:Kse,Locate:QI,LocateFixed:Zse,LocateFixedIcon:Zse,LocateIcon:QI,LocateOff:Xse,LocateOffIcon:Xse,Lock:Gc,LockIcon:Gc,LockKeyhole:Qse,LockKeyholeIcon:Qse,LockKeyholeOpen:X3,LockKeyholeOpenIcon:X3,LockOpen:Q3,LockOpenIcon:Q3,LogIn:RE,LogInIcon:RE,LogOut:OE,LogOutIcon:OE,Logs:Jse,LogsIcon:Jse,Lollipop:ere,LollipopIcon:ere,LucideAArrowDown:xH,LucideAArrowUp:gH,LucideALargeSmall:yH,LucideAccessibility:vH,LucideActivity:xm,LucideActivitySquare:b5,LucideAirVent:bH,LucideAirplay:_H,LucideAlarmCheck:kC,LucideAlarmClock:jH,LucideAlarmClockCheck:kC,LucideAlarmClockMinus:SC,LucideAlarmClockOff:wH,LucideAlarmClockPlus:CC,LucideAlarmMinus:SC,LucideAlarmPlus:CC,LucideAlarmSmoke:NH,LucideAlbum:kH,LucideAlertCircle:go,LucideAlertOctagon:Oj,LucideAlertTriangle:du,LucideAlignCenter:jE,LucideAlignCenterHorizontal:SH,LucideAlignCenterVertical:CH,LucideAlignEndHorizontal:TH,LucideAlignEndVertical:EH,LucideAlignHorizontalDistributeCenter:AH,LucideAlignHorizontalDistributeEnd:MH,LucideAlignHorizontalDistributeStart:IH,LucideAlignHorizontalJustifyCenter:PH,LucideAlignHorizontalJustifyEnd:LH,LucideAlignHorizontalJustifyStart:DH,LucideAlignHorizontalSpaceAround:RH,LucideAlignHorizontalSpaceBetween:OH,LucideAlignJustify:FH,LucideAlignLeft:NE,LucideAlignRight:kE,LucideAlignStartHorizontal:zH,LucideAlignStartVertical:BH,LucideAlignVerticalDistributeCenter:$H,LucideAlignVerticalDistributeEnd:UH,LucideAlignVerticalDistributeStart:qH,LucideAlignVerticalJustifyCenter:VH,LucideAlignVerticalJustifyEnd:HH,LucideAlignVerticalJustifyStart:GH,LucideAlignVerticalSpaceAround:WH,LucideAlignVerticalSpaceBetween:KH,LucideAmbulance:YH,LucideAmpersand:ZH,LucideAmpersands:XH,LucideAmphora:QH,LucideAnchor:JH,LucideAngry:eG,LucideAnnoyed:tG,LucideAntenna:sG,LucideAnvil:rG,LucideAperture:nG,LucideAppWindow:iG,LucideAppWindowMac:aG,LucideApple:oG,LucideArchive:Qk,LucideArchiveRestore:qI,LucideArchiveX:lG,LucideAreaChart:$C,LucideArmchair:cG,LucideArrowBigDown:uG,LucideArrowBigDownDash:dG,LucideArrowBigLeft:mG,LucideArrowBigLeftDash:hG,LucideArrowBigRight:pG,LucideArrowBigRightDash:fG,LucideArrowBigUp:gG,LucideArrowBigUpDash:xG,LucideArrowDown:gm,LucideArrowDown01:yG,LucideArrowDown10:vG,LucideArrowDownAZ:TC,LucideArrowDownAz:TC,LucideArrowDownCircle:JC,LucideArrowDownFromLine:bG,LucideArrowDownLeft:_G,LucideArrowDownLeftFromCircle:t3,LucideArrowDownLeftFromSquare:k5,LucideArrowDownLeftSquare:_5,LucideArrowDownNarrowWide:wG,LucideArrowDownRight:cF,LucideArrowDownRightFromCircle:s3,LucideArrowDownRightFromSquare:S5,LucideArrowDownRightSquare:w5,LucideArrowDownSquare:j5,LucideArrowDownToDot:jG,LucideArrowDownToLine:NG,LucideArrowDownUp:kG,LucideArrowDownWideNarrow:EC,LucideArrowDownZA:AC,LucideArrowDownZa:AC,LucideArrowLeft:Aa,LucideArrowLeftCircle:e3,LucideArrowLeftFromLine:SG,LucideArrowLeftRight:CG,LucideArrowLeftSquare:N5,LucideArrowLeftToLine:TG,LucideArrowRight:ci,LucideArrowRightCircle:a3,LucideArrowRightFromLine:EG,LucideArrowRightLeft:Jj,LucideArrowRightSquare:E5,LucideArrowRightToLine:AG,LucideArrowUp:qu,LucideArrowUp01:MG,LucideArrowUp10:IG,LucideArrowUpAZ:MC,LucideArrowUpAz:MC,LucideArrowUpCircle:i3,LucideArrowUpDown:Uu,LucideArrowUpFromDot:PG,LucideArrowUpFromLine:LG,LucideArrowUpLeft:DG,LucideArrowUpLeftFromCircle:r3,LucideArrowUpLeftFromSquare:C5,LucideArrowUpLeftSquare:A5,LucideArrowUpNarrowWide:IC,LucideArrowUpRight:dF,LucideArrowUpRightFromCircle:n3,LucideArrowUpRightFromSquare:T5,LucideArrowUpRightSquare:M5,LucideArrowUpSquare:I5,LucideArrowUpToLine:RG,LucideArrowUpWideNarrow:OG,LucideArrowUpZA:PC,LucideArrowUpZa:PC,LucideArrowsUpFromLine:FG,LucideAsterisk:zG,LucideAsteriskSquare:P5,LucideAtSign:BG,LucideAtom:$G,LucideAudioLines:UG,LucideAudioWaveform:qG,LucideAward:Uc,LucideAxe:VG,LucideAxis3D:LC,LucideAxis3d:LC,LucideBaby:HG,LucideBackpack:GG,LucideBadge:lW,LucideBadgeAlert:WG,LucideBadgeCent:KG,LucideBadgeCheck:DC,LucideBadgeDollarSign:YG,LucideBadgeEuro:ZG,LucideBadgeHelp:XG,LucideBadgeIndianRupee:QG,LucideBadgeInfo:JG,LucideBadgeJapaneseYen:eW,LucideBadgeMinus:tW,LucideBadgePercent:sW,LucideBadgePlus:rW,LucideBadgePoundSterling:nW,LucideBadgeRussianRuble:aW,LucideBadgeSwissFranc:iW,LucideBadgeX:oW,LucideBaggageClaim:cW,LucideBan:uF,LucideBanana:dW,LucideBandage:uW,LucideBanknote:hW,LucideBarChart:KC,LucideBarChart2:YC,LucideBarChart3:Mo,LucideBarChart4:GC,LucideBarChartBig:HC,LucideBarChartHorizontal:qC,LucideBarChartHorizontalBig:UC,LucideBarcode:mW,LucideBaseline:fW,LucideBath:of,LucideBattery:bW,LucideBatteryCharging:pW,LucideBatteryFull:xW,LucideBatteryLow:gW,LucideBatteryMedium:yW,LucideBatteryWarning:vW,LucideBeaker:_W,LucideBean:jW,LucideBeanOff:wW,LucideBed:k0,LucideBedDouble:e2,LucideBedSingle:NW,LucideBeef:kW,LucideBeer:CW,LucideBeerOff:SW,LucideBell:ym,LucideBellDot:TW,LucideBellElectric:EW,LucideBellMinus:AW,LucideBellOff:b_,LucideBellPlus:MW,LucideBellRing:hF,LucideBetweenHorizonalEnd:RC,LucideBetweenHorizonalStart:OC,LucideBetweenHorizontalEnd:RC,LucideBetweenHorizontalStart:OC,LucideBetweenVerticalEnd:IW,LucideBetweenVerticalStart:PW,LucideBicepsFlexed:LW,LucideBike:DW,LucideBinary:RW,LucideBinoculars:OW,LucideBiohazard:FW,LucideBird:zW,LucideBitcoin:BW,LucideBlend:$W,LucideBlinds:UW,LucideBlocks:qW,LucideBluetooth:WW,LucideBluetoothConnected:VW,LucideBluetoothOff:HW,LucideBluetoothSearching:GW,LucideBold:Jk,LucideBolt:KW,LucideBomb:YW,LucideBone:ZW,LucideBook:yK,LucideBookA:XW,LucideBookAudio:QW,LucideBookCheck:JW,LucideBookCopy:eK,LucideBookDashed:FC,LucideBookDown:tK,LucideBookHeadphones:sK,LucideBookHeart:rK,LucideBookImage:nK,LucideBookKey:aK,LucideBookLock:iK,LucideBookMarked:oK,LucideBookMinus:lK,LucideBookOpen:vm,LucideBookOpenCheck:cK,LucideBookOpenText:dK,LucideBookPlus:uK,LucideBookTemplate:FC,LucideBookText:hK,LucideBookType:mK,LucideBookUp:pK,LucideBookUp2:fK,LucideBookUser:xK,LucideBookX:gK,LucideBookmark:Zy,LucideBookmarkCheck:vK,LucideBookmarkMinus:bK,LucideBookmarkPlus:mF,LucideBookmarkX:_K,LucideBoomBox:wK,LucideBot:eS,LucideBotMessageSquare:jK,LucideBotOff:NK,LucideBox:fF,LucideBoxSelect:q5,LucideBoxes:kK,LucideBraces:zC,LucideBrackets:SK,LucideBrain:pF,LucideBrainCircuit:CK,LucideBrainCog:TK,LucideBrickWall:EK,LucideBriefcase:bm,LucideBriefcaseBusiness:AK,LucideBriefcaseConveyorBelt:MK,LucideBriefcaseMedical:IK,LucideBringToFront:PK,LucideBrush:LK,LucideBug:OK,LucideBugOff:DK,LucideBugPlay:RK,LucideBuilding:SE,LucideBuilding2:Ga,LucideBus:zK,LucideBusFront:FK,LucideCable:$K,LucideCableCar:BK,LucideCake:_m,LucideCakeSlice:UK,LucideCalculator:__,LucideCalendar:vn,LucideCalendar1:qK,LucideCalendarArrowDown:VK,LucideCalendarArrowUp:HK,LucideCalendarCheck:xF,LucideCalendarCheck2:GK,LucideCalendarClock:Xy,LucideCalendarCog:WK,LucideCalendarDays:xu,LucideCalendarFold:KK,LucideCalendarHeart:gF,LucideCalendarMinus:ZK,LucideCalendarMinus2:YK,LucideCalendarOff:yF,LucideCalendarPlus:Gj,LucideCalendarPlus2:XK,LucideCalendarRange:QK,LucideCalendarSearch:JK,LucideCalendarSync:eY,LucideCalendarX:sY,LucideCalendarX2:tY,LucideCamera:Tp,LucideCameraOff:rY,LucideCandlestickChart:VC,LucideCandy:iY,LucideCandyCane:nY,LucideCandyOff:aY,LucideCannabis:oY,LucideCaptions:BC,LucideCaptionsOff:lY,LucideCar:uY,LucideCarFront:cY,LucideCarTaxiFront:dY,LucideCaravan:hY,LucideCarrot:mY,LucideCaseLower:fY,LucideCaseSensitive:pY,LucideCaseUpper:xY,LucideCassetteTape:gY,LucideCast:yY,LucideCastle:vY,LucideCat:bY,LucideCctv:_Y,LucideChartArea:$C,LucideChartBar:qC,LucideChartBarBig:UC,LucideChartBarDecreasing:wY,LucideChartBarIncreasing:jY,LucideChartBarStacked:NY,LucideChartCandlestick:VC,LucideChartColumn:Mo,LucideChartColumnBig:HC,LucideChartColumnDecreasing:kY,LucideChartColumnIncreasing:GC,LucideChartColumnStacked:SY,LucideChartGantt:CY,LucideChartLine:WC,LucideChartNetwork:TY,LucideChartNoAxesColumn:YC,LucideChartNoAxesColumnDecreasing:EY,LucideChartNoAxesColumnIncreasing:KC,LucideChartNoAxesCombined:AY,LucideChartNoAxesGantt:ZC,LucideChartPie:XC,LucideChartScatter:QC,LucideChartSpline:MY,LucideCheck:la,LucideCheckCheck:vF,LucideCheckCircle:Ti,LucideCheckCircle2:qn,LucideCheckSquare:zj,LucideCheckSquare2:D5,LucideChefHat:IY,LucideCherry:PY,LucideChevronDown:Co,LucideChevronDownCircle:o3,LucideChevronDownSquare:R5,LucideChevronFirst:LY,LucideChevronLast:DY,LucideChevronLeft:jl,LucideChevronLeftCircle:l3,LucideChevronLeftSquare:O5,LucideChevronRight:Ia,LucideChevronRightCircle:c3,LucideChevronRightSquare:F5,LucideChevronUp:pg,LucideChevronUpCircle:d3,LucideChevronUpSquare:z5,LucideChevronsDown:OY,LucideChevronsDownUp:RY,LucideChevronsLeft:BY,LucideChevronsLeftRight:zY,LucideChevronsLeftRightEllipsis:FY,LucideChevronsRight:UY,LucideChevronsRightLeft:$Y,LucideChevronsUp:qY,LucideChevronsUpDown:xg,LucideChrome:CE,LucideChurch:VY,LucideCigarette:GY,LucideCigaretteOff:HY,LucideCircle:Rh,LucideCircleAlert:go,LucideCircleArrowDown:JC,LucideCircleArrowLeft:e3,LucideCircleArrowOutDownLeft:t3,LucideCircleArrowOutDownRight:s3,LucideCircleArrowOutUpLeft:r3,LucideCircleArrowOutUpRight:n3,LucideCircleArrowRight:a3,LucideCircleArrowUp:i3,LucideCircleCheck:qn,LucideCircleCheckBig:Ti,LucideCircleChevronDown:o3,LucideCircleChevronLeft:l3,LucideCircleChevronRight:c3,LucideCircleChevronUp:d3,LucideCircleDashed:WY,LucideCircleDivide:u3,LucideCircleDollarSign:KY,LucideCircleDot:ZY,LucideCircleDotDashed:YY,LucideCircleEllipsis:XY,LucideCircleEqual:QY,LucideCircleFadingArrowUp:JY,LucideCircleFadingPlus:eZ,LucideCircleGauge:h3,LucideCircleHelp:e_,LucideCircleMinus:m3,LucideCircleOff:tZ,LucideCircleParking:p3,LucideCircleParkingOff:f3,LucideCirclePause:x3,LucideCirclePercent:g3,LucideCirclePlay:Ff,LucideCirclePlus:y3,LucideCirclePower:v3,LucideCircleSlash:sZ,LucideCircleSlash2:b3,LucideCircleSlashed:b3,LucideCircleStop:_3,LucideCircleUser:j3,LucideCircleUserRound:w3,LucideCircleX:ad,LucideCircuitBoard:rZ,LucideCitrus:nZ,LucideClapperboard:aZ,LucideClipboard:hZ,LucideClipboardCheck:VI,LucideClipboardCopy:iZ,LucideClipboardEdit:k3,LucideClipboardList:k1,LucideClipboardMinus:oZ,LucideClipboardPaste:lZ,LucideClipboardPen:k3,LucideClipboardPenLine:N3,LucideClipboardPlus:cZ,LucideClipboardSignature:N3,LucideClipboardType:dZ,LucideClipboardX:uZ,LucideClock:jn,LucideClock1:mZ,LucideClock10:fZ,LucideClock11:pZ,LucideClock12:xZ,LucideClock2:gZ,LucideClock3:yZ,LucideClock4:vZ,LucideClock5:bZ,LucideClock6:_Z,LucideClock7:wZ,LucideClock8:jZ,LucideClock9:NZ,LucideClockAlert:kZ,LucideClockArrowDown:SZ,LucideClockArrowUp:CZ,LucideCloud:UZ,LucideCloudAlert:TZ,LucideCloudCog:EZ,LucideCloudDownload:S3,LucideCloudDrizzle:AZ,LucideCloudFog:MZ,LucideCloudHail:IZ,LucideCloudLightning:PZ,LucideCloudMoon:DZ,LucideCloudMoonRain:LZ,LucideCloudOff:RZ,LucideCloudRain:FZ,LucideCloudRainWind:OZ,LucideCloudSnow:zZ,LucideCloudSun:$Z,LucideCloudSunRain:BZ,LucideCloudUpload:C3,LucideCloudy:qZ,LucideClover:Wj,LucideClub:VZ,LucideCode:TE,LucideCode2:Rj,LucideCodeSquare:B5,LucideCodeXml:Rj,LucideCodepen:HZ,LucideCodesandbox:GZ,LucideCoffee:EE,LucideCog:WZ,LucideCoins:bF,LucideColumns:T3,LucideColumns2:T3,LucideColumns3:E3,LucideColumns4:KZ,LucideCombine:YZ,LucideCommand:ZZ,LucideCompass:HI,LucideComponent:XZ,LucideComputer:QZ,LucideConciergeBell:JZ,LucideCone:eX,LucideConstruction:tX,LucideContact:AE,LucideContact2:A3,LucideContactRound:A3,LucideContainer:sX,LucideContrast:rX,LucideCookie:nX,LucideCookingPot:aX,LucideCopy:si,LucideCopyCheck:iX,LucideCopyMinus:oX,LucideCopyPlus:lX,LucideCopySlash:cX,LucideCopyX:dX,LucideCopyleft:uX,LucideCopyright:hX,LucideCornerDownLeft:mX,LucideCornerDownRight:fX,LucideCornerLeftDown:pX,LucideCornerLeftUp:xX,LucideCornerRightDown:gX,LucideCornerRightUp:yX,LucideCornerUpLeft:vX,LucideCornerUpRight:bX,LucideCpu:_X,LucideCreativeCommons:wX,LucideCreditCard:S0,LucideCroissant:jX,LucideCrop:NX,LucideCross:kX,LucideCrosshair:SX,LucideCrown:Gf,LucideCuboid:CX,LucideCupSoda:TX,LucideCurlyBraces:zC,LucideCurrency:EX,LucideCylinder:AX,LucideDam:MX,LucideDatabase:_F,LucideDatabaseBackup:IX,LucideDatabaseZap:PX,LucideDelete:LX,LucideDessert:DX,LucideDiameter:RX,LucideDiamond:zX,LucideDiamondMinus:OX,LucideDiamondPercent:M3,LucideDiamondPlus:FX,LucideDice1:BX,LucideDice2:$X,LucideDice3:UX,LucideDice4:qX,LucideDice5:VX,LucideDice6:HX,LucideDices:GX,LucideDiff:WX,LucideDisc:XX,LucideDisc2:KX,LucideDisc3:YX,LucideDiscAlbum:ZX,LucideDivide:QX,LucideDivideCircle:u3,LucideDivideSquare:V5,LucideDna:eQ,LucideDnaOff:JX,LucideDock:tQ,LucideDog:sQ,LucideDollarSign:Xl,LucideDonut:rQ,LucideDoorClosed:nQ,LucideDoorOpen:w_,LucideDot:aQ,LucideDotSquare:H5,LucideDownload:li,LucideDownloadCloud:S3,LucideDraftingCompass:iQ,LucideDrama:oQ,LucideDribbble:lQ,LucideDrill:cQ,LucideDroplet:dQ,LucideDroplets:S1,LucideDrum:uQ,LucideDrumstick:hQ,LucideDumbbell:mQ,LucideEar:pQ,LucideEarOff:fQ,LucideEarth:I3,LucideEarthLock:xQ,LucideEclipse:gQ,LucideEdit:iu,LucideEdit2:zy,LucideEdit3:t_,LucideEgg:GI,LucideEggFried:yQ,LucideEggOff:vQ,LucideEllipsis:f0,LucideEllipsisVertical:Fy,LucideEqual:wQ,LucideEqualApproximately:bQ,LucideEqualNot:_Q,LucideEqualSquare:G5,LucideEraser:jQ,LucideEthernetPort:NQ,LucideEuro:kQ,LucideExpand:SQ,LucideExternalLink:un,LucideEye:Nn,LucideEyeClosed:CQ,LucideEyeOff:Wf,LucideFacebook:mh,LucideFactory:TQ,LucideFan:EQ,LucideFastForward:AQ,LucideFeather:MQ,LucideFence:IQ,LucideFerrisWheel:PQ,LucideFigma:LQ,LucideFile:WI,LucideFileArchive:DQ,LucideFileAudio:OQ,LucideFileAudio2:RQ,LucideFileAxis3D:P3,LucideFileAxis3d:P3,LucideFileBadge:zQ,LucideFileBadge2:FQ,LucideFileBarChart:L3,LucideFileBarChart2:D3,LucideFileBox:BQ,LucideFileChartColumn:D3,LucideFileChartColumnIncreasing:L3,LucideFileChartLine:R3,LucideFileChartPie:O3,LucideFileCheck:wF,LucideFileCheck2:$Q,LucideFileClock:UQ,LucideFileCode:VQ,LucideFileCode2:qQ,LucideFileCog:F3,LucideFileCog2:F3,LucideFileDiff:HQ,LucideFileDigit:GQ,LucideFileDown:ME,LucideFileEdit:B3,LucideFileHeart:WQ,LucideFileImage:t2,LucideFileInput:KQ,LucideFileJson:ZQ,LucideFileJson2:YQ,LucideFileKey:QQ,LucideFileKey2:XQ,LucideFileLineChart:R3,LucideFileLock:eJ,LucideFileLock2:JQ,LucideFileMinus:sJ,LucideFileMinus2:tJ,LucideFileMusic:rJ,LucideFileOutput:nJ,LucideFilePen:B3,LucideFilePenLine:z3,LucideFilePieChart:O3,LucideFilePlus:iJ,LucideFilePlus2:aJ,LucideFileQuestion:oJ,LucideFileScan:lJ,LucideFileSearch:dJ,LucideFileSearch2:cJ,LucideFileSignature:z3,LucideFileSliders:uJ,LucideFileSpreadsheet:s2,LucideFileStack:jF,LucideFileSymlink:hJ,LucideFileTerminal:mJ,LucideFileText:En,LucideFileType:pJ,LucideFileType2:fJ,LucideFileUp:xJ,LucideFileUser:gJ,LucideFileVideo:NF,LucideFileVideo2:yJ,LucideFileVolume:bJ,LucideFileVolume2:vJ,LucideFileWarning:_J,LucideFileX:jJ,LucideFileX2:wJ,LucideFiles:NJ,LucideFilm:rf,LucideFilter:C1,LucideFilterX:kJ,LucideFingerprint:SJ,LucideFireExtinguisher:CJ,LucideFish:AJ,LucideFishOff:TJ,LucideFishSymbol:EJ,LucideFlag:r2,LucideFlagOff:MJ,LucideFlagTriangleLeft:IJ,LucideFlagTriangleRight:PJ,LucideFlame:ld,LucideFlameKindling:LJ,LucideFlashlight:RJ,LucideFlashlightOff:DJ,LucideFlaskConical:tS,LucideFlaskConicalOff:OJ,LucideFlaskRound:FJ,LucideFlipHorizontal:kF,LucideFlipHorizontal2:zJ,LucideFlipVertical:$J,LucideFlipVertical2:BJ,LucideFlower:UJ,LucideFlower2:b1,LucideFocus:qJ,LucideFoldHorizontal:VJ,LucideFoldVertical:HJ,LucideFolder:yee,LucideFolderArchive:GJ,LucideFolderCheck:WJ,LucideFolderClock:KJ,LucideFolderClosed:YJ,LucideFolderCode:ZJ,LucideFolderCog:$3,LucideFolderCog2:$3,LucideFolderDot:XJ,LucideFolderDown:QJ,LucideFolderEdit:U3,LucideFolderGit:eee,LucideFolderGit2:JJ,LucideFolderHeart:tee,LucideFolderInput:see,LucideFolderKanban:ree,LucideFolderKey:nee,LucideFolderLock:aee,LucideFolderMinus:iee,LucideFolderOpen:Kf,LucideFolderOpenDot:oee,LucideFolderOutput:lee,LucideFolderPen:U3,LucideFolderPlus:cee,LucideFolderRoot:dee,LucideFolderSearch:hee,LucideFolderSearch2:uee,LucideFolderSymlink:mee,LucideFolderSync:fee,LucideFolderTree:pee,LucideFolderUp:xee,LucideFolderX:gee,LucideFolders:vee,LucideFootprints:bee,LucideForkKnife:MT,LucideForkKnifeCrossed:AT,LucideForklift:_ee,LucideFormInput:h5,LucideForward:wee,LucideFrame:jee,LucideFramer:Nee,LucideFrown:kee,LucideFuel:See,LucideFullscreen:Cee,LucideFunctionSquare:W5,LucideGalleryHorizontal:Eee,LucideGalleryHorizontalEnd:Tee,LucideGalleryThumbnails:Aee,LucideGalleryVertical:Iee,LucideGalleryVerticalEnd:Mee,LucideGamepad:Lee,LucideGamepad2:Pee,LucideGanttChart:ZC,LucideGanttChartSquare:$b,LucideGauge:Dee,LucideGaugeCircle:h3,LucideGavel:Ree,LucideGem:Oee,LucideGhost:IE,LucideGift:Di,LucideGitBranch:zee,LucideGitBranchPlus:Fee,LucideGitCommit:q3,LucideGitCommitHorizontal:q3,LucideGitCommitVertical:Bee,LucideGitCompare:Uee,LucideGitCompareArrows:$ee,LucideGitFork:qee,LucideGitGraph:Vee,LucideGitMerge:Hee,LucideGitPullRequest:Xee,LucideGitPullRequestArrow:Gee,LucideGitPullRequestClosed:Wee,LucideGitPullRequestCreate:Yee,LucideGitPullRequestCreateArrow:Kee,LucideGitPullRequestDraft:Zee,LucideGithub:Qee,LucideGitlab:Jee,LucideGlassWater:ete,LucideGlasses:tte,LucideGlobe:Ql,LucideGlobe2:I3,LucideGlobeLock:ste,LucideGoal:rte,LucideGrab:nte,LucideGraduationCap:ch,LucideGrape:ate,LucideGrid:Ey,LucideGrid2X2:H3,LucideGrid2X2Plus:V3,LucideGrid2x2:H3,LucideGrid2x2Check:ite,LucideGrid2x2Plus:V3,LucideGrid2x2X:ote,LucideGrid3X3:Ey,LucideGrid3x3:Ey,LucideGrip:cte,LucideGripHorizontal:lte,LucideGripVertical:Vu,LucideGroup:dte,LucideGuitar:ute,LucideHam:hte,LucideHammer:SF,LucideHand:CF,LucideHandCoins:mte,LucideHandHeart:fte,LucideHandHelping:p1,LucideHandMetal:pte,LucideHandPlatter:xte,LucideHandshake:j_,LucideHardDrive:TF,LucideHardDriveDownload:gte,LucideHardDriveUpload:yte,LucideHardHat:vte,LucideHash:sS,LucideHaze:bte,LucideHdmiPort:_te,LucideHeading:kte,LucideHeading1:KI,LucideHeading2:YI,LucideHeading3:EF,LucideHeading4:wte,LucideHeading5:jte,LucideHeading6:Nte,LucideHeadphoneOff:Ste,LucideHeadphones:Cte,LucideHeadset:Tte,LucideHeart:yi,LucideHeartCrack:Ete,LucideHeartHandshake:Ate,LucideHeartOff:Mte,LucideHeartPulse:Ite,LucideHeater:Pte,LucideHelpCircle:e_,LucideHelpingHand:p1,LucideHexagon:Lte,LucideHighlighter:Dte,LucideHistory:ZI,LucideHome:Pn,LucideHop:Ote,LucideHopOff:Rte,LucideHospital:Fte,LucideHotel:zte,LucideHourglass:Bte,LucideHouse:Pn,LucideHousePlug:$te,LucideHousePlus:Ute,LucideIceCream:W3,LucideIceCream2:G3,LucideIceCreamBowl:G3,LucideIceCreamCone:W3,LucideIdCard:qte,LucideImage:zo,LucideImageDown:Vte,LucideImageMinus:Hte,LucideImageOff:Gte,LucideImagePlay:Wte,LucideImagePlus:Qy,LucideImageUp:Kte,LucideImageUpscale:Yte,LucideImages:Zte,LucideImport:Xte,LucideInbox:n2,LucideIndent:Y3,LucideIndentDecrease:K3,LucideIndentIncrease:Y3,LucideIndianRupee:Qte,LucideInfinity:Jte,LucideInfo:a2,LucideInspect:J5,LucideInspectionPanel:ese,LucideInstagram:gu,LucideItalic:rS,LucideIterationCcw:tse,LucideIterationCw:sse,LucideJapaneseYen:rse,LucideJoystick:nse,LucideKanban:i2,LucideKanbanSquare:K5,LucideKanbanSquareDashed:$5,LucideKey:gg,LucideKeyRound:PE,LucideKeySquare:ase,LucideKeyboard:lse,LucideKeyboardMusic:ise,LucideKeyboardOff:ose,LucideLamp:fse,LucideLampCeiling:cse,LucideLampDesk:dse,LucideLampFloor:use,LucideLampWallDown:hse,LucideLampWallUp:mse,LucideLandPlot:pse,LucideLandmark:xse,LucideLanguages:gse,LucideLaptop:vse,LucideLaptop2:Z3,LucideLaptopMinimal:Z3,LucideLaptopMinimalCheck:yse,LucideLasso:_se,LucideLassoSelect:bse,LucideLaugh:wse,LucideLayers:AF,LucideLayers2:jse,LucideLayers3:Nse,LucideLayout:Fj,LucideLayoutDashboard:LE,LucideLayoutGrid:Ep,LucideLayoutList:kse,LucideLayoutPanelLeft:Sse,LucideLayoutPanelTop:Cse,LucideLayoutTemplate:DE,LucideLeaf:Tse,LucideLeafyGreen:Ese,LucideLectern:Ase,LucideLetterText:Mse,LucideLibrary:nS,LucideLibraryBig:Ise,LucideLibrarySquare:Y5,LucideLifeBuoy:XI,LucideLigature:Pse,LucideLightbulb:o2,LucideLightbulbOff:Lse,LucideLineChart:WC,LucideLink:tl,LucideLink2:Ul,LucideLink2Off:Dse,LucideLinkedin:Yf,LucideList:Zf,LucideListCheck:Rse,LucideListChecks:l2,LucideListCollapse:Ose,LucideListEnd:Fse,LucideListFilter:MF,LucideListMinus:zse,LucideListMusic:Bse,LucideListOrdered:T1,LucideListPlus:$se,LucideListRestart:Use,LucideListStart:qse,LucideListTodo:Vse,LucideListTree:Hse,LucideListVideo:Gse,LucideListX:Wse,LucideLoader:Yse,LucideLoader2:ls,LucideLoaderCircle:ls,LucideLoaderPinwheel:Kse,LucideLocate:QI,LucideLocateFixed:Zse,LucideLocateOff:Xse,LucideLock:Gc,LucideLockKeyhole:Qse,LucideLockKeyholeOpen:X3,LucideLockOpen:Q3,LucideLogIn:RE,LucideLogOut:OE,LucideLogs:Jse,LucideLollipop:ere,LucideLuggage:tre,LucideMSquare:Z5,LucideMagnet:sre,LucideMail:Ks,LucideMailCheck:JI,LucideMailMinus:rre,LucideMailOpen:IF,LucideMailPlus:PF,LucideMailQuestion:nre,LucideMailSearch:are,LucideMailWarning:ire,LucideMailX:eP,LucideMailbox:ore,LucideMails:lre,LucideMap:FE,LucideMapPin:Ma,LucideMapPinCheck:dre,LucideMapPinCheckInside:cre,LucideMapPinHouse:ure,LucideMapPinMinus:mre,LucideMapPinMinusInside:hre,LucideMapPinOff:fre,LucideMapPinPlus:xre,LucideMapPinPlusInside:pre,LucideMapPinX:yre,LucideMapPinXInside:gre,LucideMapPinned:vre,LucideMartini:bre,LucideMaximize:zE,LucideMaximize2:LF,LucideMedal:c2,LucideMegaphone:fh,LucideMegaphoneOff:_re,LucideMeh:wre,LucideMemoryStick:jre,LucideMenu:aS,LucideMenuSquare:X5,LucideMerge:Nre,LucideMessageCircle:gc,LucideMessageCircleCode:kre,LucideMessageCircleDashed:Sre,LucideMessageCircleHeart:tP,LucideMessageCircleMore:Cre,LucideMessageCircleOff:Tre,LucideMessageCirclePlus:Ere,LucideMessageCircleQuestion:DF,LucideMessageCircleReply:Are,LucideMessageCircleWarning:Mre,LucideMessageCircleX:Ire,LucideMessageSquare:Ui,LucideMessageSquareCode:Pre,LucideMessageSquareDashed:Lre,LucideMessageSquareDiff:Dre,LucideMessageSquareDot:Rre,LucideMessageSquareHeart:Ore,LucideMessageSquareLock:Fre,LucideMessageSquareMore:RF,LucideMessageSquareOff:zre,LucideMessageSquarePlus:c_,LucideMessageSquareQuote:sP,LucideMessageSquareReply:Bre,LucideMessageSquareShare:$re,LucideMessageSquareText:Ure,LucideMessageSquareWarning:qre,LucideMessageSquareX:Vre,LucideMessagesSquare:Hre,LucideMic:BE,LucideMic2:J3,LucideMicOff:Gre,LucideMicVocal:J3,LucideMicrochip:Wre,LucideMicroscope:Kre,LucideMicrowave:Yre,LucideMilestone:Zre,LucideMilk:Qre,LucideMilkOff:Xre,LucideMinimize:ene,LucideMinimize2:Jre,LucideMinus:N_,LucideMinusCircle:m3,LucideMinusSquare:Q5,LucideMonitor:k_,LucideMonitorCheck:tne,LucideMonitorCog:sne,LucideMonitorDot:rne,LucideMonitorDown:nne,LucideMonitorOff:ane,LucideMonitorPause:ine,LucideMonitorPlay:OF,LucideMonitorSmartphone:one,LucideMonitorSpeaker:lne,LucideMonitorStop:cne,LucideMonitorUp:$E,LucideMonitorX:dne,LucideMoon:hne,LucideMoonStar:une,LucideMoreHorizontal:f0,LucideMoreVertical:Fy,LucideMountain:fne,LucideMountainSnow:mne,LucideMouse:yne,LucideMouseOff:pne,LucideMousePointer:dm,LucideMousePointer2:xne,LucideMousePointerBan:gne,LucideMousePointerClick:Bc,LucideMousePointerSquareDashed:U5,LucideMove:Mne,LucideMove3D:e5,LucideMove3d:e5,LucideMoveDiagonal:bne,LucideMoveDiagonal2:vne,LucideMoveDown:jne,LucideMoveDownLeft:_ne,LucideMoveDownRight:wne,LucideMoveHorizontal:Nne,LucideMoveLeft:kne,LucideMoveRight:Sne,LucideMoveUp:Ene,LucideMoveUpLeft:Cne,LucideMoveUpRight:Tne,LucideMoveVertical:Ane,LucideMusic:rP,LucideMusic2:Ine,LucideMusic3:Pne,LucideMusic4:Lne,LucideNavigation:FF,LucideNavigation2:Rne,LucideNavigation2Off:Dne,LucideNavigationOff:One,LucideNetwork:Fne,LucideNewspaper:E1,LucideNfc:zne,LucideNotebook:qne,LucideNotebookPen:Bne,LucideNotebookTabs:$ne,LucideNotebookText:Une,LucideNotepadText:Hne,LucideNotepadTextDashed:Vne,LucideNut:Wne,LucideNutOff:Gne,LucideOctagon:Yne,LucideOctagonAlert:Oj,LucideOctagonMinus:Kne,LucideOctagonPause:t5,LucideOctagonX:s5,LucideOmega:Zne,LucideOption:Xne,LucideOrbit:Qne,LucideOrigami:Jne,LucideOutdent:K3,LucidePackage:yc,LucidePackage2:eae,LucidePackageCheck:tae,LucidePackageMinus:sae,LucidePackageOpen:rae,LucidePackagePlus:nae,LucidePackageSearch:aae,LucidePackageX:iae,LucidePaintBucket:oae,LucidePaintRoller:lae,LucidePaintbrush:cae,LucidePaintbrush2:r5,LucidePaintbrushVertical:r5,LucidePalette:dl,LucidePalmtree:bT,LucidePanelBottom:hae,LucidePanelBottomClose:dae,LucidePanelBottomDashed:n5,LucidePanelBottomInactive:n5,LucidePanelBottomOpen:uae,LucidePanelLeft:l5,LucidePanelLeftClose:a5,LucidePanelLeftDashed:i5,LucidePanelLeftInactive:i5,LucidePanelLeftOpen:o5,LucidePanelRight:pae,LucidePanelRightClose:mae,LucidePanelRightDashed:c5,LucidePanelRightInactive:c5,LucidePanelRightOpen:fae,LucidePanelTop:yae,LucidePanelTopClose:xae,LucidePanelTopDashed:d5,LucidePanelTopInactive:d5,LucidePanelTopOpen:gae,LucidePanelsLeftBottom:vae,LucidePanelsLeftRight:E3,LucidePanelsRightBottom:bae,LucidePanelsTopBottom:p5,LucidePanelsTopLeft:Fj,LucidePaperclip:iS,LucideParentheses:_ae,LucideParkingCircle:p3,LucideParkingCircleOff:f3,LucideParkingMeter:wae,LucideParkingSquare:tT,LucideParkingSquareOff:eT,LucidePartyPopper:ph,LucidePause:Xf,LucidePauseCircle:x3,LucidePauseOctagon:t5,LucidePawPrint:jae,LucidePcCase:Nae,LucidePen:zy,LucidePenBox:iu,LucidePenLine:t_,LucidePenOff:kae,LucidePenSquare:iu,LucidePenTool:oS,LucidePencil:Ua,LucidePencilLine:Sae,LucidePencilOff:Cae,LucidePencilRuler:Tae,LucidePentagon:Eae,LucidePercent:UE,LucidePercentCircle:g3,LucidePercentDiamond:M3,LucidePercentSquare:sT,LucidePersonStanding:Aae,LucidePhilippinePeso:Mae,LucidePhone:Mn,LucidePhoneCall:Iae,LucidePhoneForwarded:Pae,LucidePhoneIncoming:Lae,LucidePhoneMissed:Dae,LucidePhoneOff:Rae,LucidePhoneOutgoing:Oae,LucidePi:Fae,LucidePiSquare:rT,LucidePiano:zae,LucidePickaxe:Bae,LucidePictureInPicture:Uae,LucidePictureInPicture2:$ae,LucidePieChart:XC,LucidePiggyBank:qae,LucidePilcrow:Gae,LucidePilcrowLeft:Vae,LucidePilcrowRight:Hae,LucidePilcrowSquare:nT,LucidePill:Kae,LucidePillBottle:Wae,LucidePin:lS,LucidePinOff:zF,LucidePipette:Yae,LucidePizza:Zae,LucidePlane:BF,LucidePlaneLanding:Xae,LucidePlaneTakeoff:Qae,LucidePlay:Al,LucidePlayCircle:Ff,LucidePlaySquare:aT,LucidePlug:d2,LucidePlug2:Jae,LucidePlugZap:u5,LucidePlugZap2:u5,LucidePlus:Ys,LucidePlusCircle:y3,LucidePlusSquare:iT,LucidePocket:tie,LucidePocketKnife:eie,LucidePodcast:sie,LucidePointer:nie,LucidePointerOff:rie,LucidePopcorn:aie,LucidePopsicle:iie,LucidePoundSterling:oie,LucidePower:$F,LucidePowerCircle:v3,LucidePowerOff:lie,LucidePowerSquare:oT,LucidePresentation:Jy,LucidePrinter:UF,LucidePrinterCheck:cie,LucideProjector:die,LucideProportions:uie,LucidePuzzle:hie,LucidePyramid:mie,LucideQrCode:S_,LucideQuote:u2,LucideRabbit:fie,LucideRadar:nP,LucideRadiation:pie,LucideRadical:xie,LucideRadio:h2,LucideRadioReceiver:gie,LucideRadioTower:yie,LucideRadius:vie,LucideRailSymbol:bie,LucideRainbow:_ie,LucideRat:wie,LucideRatio:jie,LucideReceipt:Iie,LucideReceiptCent:Nie,LucideReceiptEuro:kie,LucideReceiptIndianRupee:Sie,LucideReceiptJapaneseYen:Cie,LucideReceiptPoundSterling:Tie,LucideReceiptRussianRuble:Eie,LucideReceiptSwissFranc:Aie,LucideReceiptText:Mie,LucideRectangleEllipsis:h5,LucideRectangleHorizontal:Pie,LucideRectangleVertical:Lie,LucideRecycle:Die,LucideRedo:cS,LucideRedo2:Rie,LucideRedoDot:Oie,LucideRefreshCcw:aP,LucideRefreshCcwDot:Fie,LucideRefreshCw:lo,LucideRefreshCwOff:zie,LucideRefrigerator:Bie,LucideRegex:$ie,LucideRemoveFormatting:Uie,LucideRepeat:qF,LucideRepeat1:qie,LucideRepeat2:Vie,LucideReplace:Gie,LucideReplaceAll:Hie,LucideReply:VF,LucideReplyAll:Wie,LucideRewind:Kie,LucideRibbon:Yie,LucideRocket:C_,LucideRockingChair:Zie,LucideRollerCoaster:Xie,LucideRotate3D:m5,LucideRotate3d:m5,LucideRotateCcw:ev,LucideRotateCcwSquare:Qie,LucideRotateCw:qE,LucideRotateCwSquare:Jie,LucideRoute:toe,LucideRouteOff:eoe,LucideRouter:soe,LucideRows:f5,LucideRows2:f5,LucideRows3:p5,LucideRows4:roe,LucideRss:noe,LucideRuler:m2,LucideRussianRuble:aoe,LucideSailboat:ioe,LucideSalad:ooe,LucideSandwich:loe,LucideSatellite:doe,LucideSatelliteDish:coe,LucideSave:Ml,LucideSaveAll:uoe,LucideSaveOff:hoe,LucideScale:HF,LucideScale3D:x5,LucideScale3d:x5,LucideScaling:moe,LucideScan:_oe,LucideScanBarcode:foe,LucideScanEye:poe,LucideScanFace:xoe,LucideScanLine:goe,LucideScanQrCode:yoe,LucideScanSearch:voe,LucideScanText:boe,LucideScatterChart:QC,LucideSchool:woe,LucideSchool2:wT,LucideScissors:Noe,LucideScissorsLineDashed:joe,LucideScissorsSquare:lT,LucideScissorsSquareDashedBottom:L5,LucideScreenShare:Soe,LucideScreenShareOff:koe,LucideScroll:Toe,LucideScrollText:Coe,LucideSearch:_n,LucideSearchCheck:Eoe,LucideSearchCode:Aoe,LucideSearchSlash:Moe,LucideSearchX:GF,LucideSection:Ioe,LucideSend:hn,LucideSendHorizonal:g5,LucideSendHorizontal:g5,LucideSendToBack:Poe,LucideSeparatorHorizontal:Loe,LucideSeparatorVertical:Doe,LucideServer:zoe,LucideServerCog:Roe,LucideServerCrash:Ooe,LucideServerOff:Foe,LucideSettings:Bo,LucideSettings2:WF,LucideShapes:Boe,LucideShare:KF,LucideShare2:Ec,LucideSheet:$oe,LucideShell:Uoe,LucideShield:Oh,LucideShieldAlert:YF,LucideShieldBan:qoe,LucideShieldCheck:A1,LucideShieldClose:y5,LucideShieldEllipsis:Voe,LucideShieldHalf:Hoe,LucideShieldMinus:Goe,LucideShieldOff:VE,LucideShieldPlus:Woe,LucideShieldQuestion:Koe,LucideShieldX:y5,LucideShip:Zoe,LucideShipWheel:Yoe,LucideShirt:Xoe,LucideShoppingBag:T_,LucideShoppingBasket:Qoe,LucideShoppingCart:lg,LucideShovel:Joe,LucideShowerHead:ele,LucideShrink:tle,LucideShrub:sle,LucideShuffle:HE,LucideSidebar:l5,LucideSidebarClose:a5,LucideSidebarOpen:o5,LucideSigma:rle,LucideSigmaSquare:cT,LucideSignal:lle,LucideSignalHigh:nle,LucideSignalLow:ale,LucideSignalMedium:ile,LucideSignalZero:ole,LucideSignature:cle,LucideSignpost:ule,LucideSignpostBig:dle,LucideSiren:hle,LucideSkipBack:mle,LucideSkipForward:fle,LucideSkull:ple,LucideSlack:xle,LucideSlash:gle,LucideSlashSquare:dT,LucideSlice:yle,LucideSliders:v5,LucideSlidersHorizontal:dS,LucideSlidersVertical:v5,LucideSmartphone:yg,LucideSmartphoneCharging:vle,LucideSmartphoneNfc:ble,LucideSmile:wle,LucideSmilePlus:_le,LucideSnail:jle,LucideSnowflake:_1,LucideSofa:Nle,LucideSortAsc:IC,LucideSortDesc:EC,LucideSoup:kle,LucideSpace:Sle,LucideSpade:Cle,LucideSparkle:Tle,LucideSparkles:Ir,LucideSpeaker:Ele,LucideSpeech:Ale,LucideSpellCheck:Ile,LucideSpellCheck2:Mle,LucideSpline:Ple,LucideSplit:Lle,LucideSplitSquareHorizontal:uT,LucideSplitSquareVertical:hT,LucideSprayCan:Dle,LucideSprout:GE,LucideSquare:C0,LucideSquareActivity:b5,LucideSquareArrowDown:j5,LucideSquareArrowDownLeft:_5,LucideSquareArrowDownRight:w5,LucideSquareArrowLeft:N5,LucideSquareArrowOutDownLeft:k5,LucideSquareArrowOutDownRight:S5,LucideSquareArrowOutUpLeft:C5,LucideSquareArrowOutUpRight:T5,LucideSquareArrowRight:E5,LucideSquareArrowUp:I5,LucideSquareArrowUpLeft:A5,LucideSquareArrowUpRight:M5,LucideSquareAsterisk:P5,LucideSquareBottomDashedScissors:L5,LucideSquareChartGantt:$b,LucideSquareCheck:D5,LucideSquareCheckBig:zj,LucideSquareChevronDown:R5,LucideSquareChevronLeft:O5,LucideSquareChevronRight:F5,LucideSquareChevronUp:z5,LucideSquareCode:B5,LucideSquareDashed:q5,LucideSquareDashedBottom:Ole,LucideSquareDashedBottomCode:Rle,LucideSquareDashedKanban:$5,LucideSquareDashedMousePointer:U5,LucideSquareDivide:V5,LucideSquareDot:H5,LucideSquareEqual:G5,LucideSquareFunction:W5,LucideSquareGanttChart:$b,LucideSquareKanban:K5,LucideSquareLibrary:Y5,LucideSquareM:Z5,LucideSquareMenu:X5,LucideSquareMinus:Q5,LucideSquareMousePointer:J5,LucideSquareParking:tT,LucideSquareParkingOff:eT,LucideSquarePen:iu,LucideSquarePercent:sT,LucideSquarePi:rT,LucideSquarePilcrow:nT,LucideSquarePlay:aT,LucideSquarePlus:iT,LucideSquarePower:oT,LucideSquareRadical:Fle,LucideSquareScissors:lT,LucideSquareSigma:cT,LucideSquareSlash:dT,LucideSquareSplitHorizontal:uT,LucideSquareSplitVertical:hT,LucideSquareSquare:zle,LucideSquareStack:Ble,LucideSquareTerminal:mT,LucideSquareUser:pT,LucideSquareUserRound:fT,LucideSquareX:xT,LucideSquircle:$le,LucideSquirrel:Ule,LucideStamp:qle,LucideStar:fa,LucideStarHalf:Vle,LucideStarOff:Hle,LucideStars:Ir,LucideStepBack:Gle,LucideStepForward:Wle,LucideStethoscope:Kle,LucideSticker:Yle,LucideStickyNote:Zle,LucideStopCircle:_3,LucideStore:ZF,LucideStretchHorizontal:Xle,LucideStretchVertical:Qle,LucideStrikethrough:XF,LucideSubscript:Jle,LucideSubtitles:BC,LucideSun:f2,LucideSunDim:ece,LucideSunMedium:tce,LucideSunMoon:sce,LucideSunSnow:rce,LucideSunrise:nce,LucideSunset:ace,LucideSuperscript:ice,LucideSwatchBook:oce,LucideSwissFranc:lce,LucideSwitchCamera:cce,LucideSword:dce,LucideSwords:uce,LucideSyringe:hce,LucideTable:oP,LucideTable2:iP,LucideTableCellsMerge:mce,LucideTableCellsSplit:fce,LucideTableColumnsSplit:pce,LucideTableOfContents:xce,LucideTableProperties:gce,LucideTableRowsSplit:yce,LucideTablet:lP,LucideTabletSmartphone:vce,LucideTablets:bce,LucideTag:Fh,LucideTags:QF,LucideTally1:_ce,LucideTally2:wce,LucideTally3:jce,LucideTally4:Nce,LucideTally5:kce,LucideTangent:Sce,LucideTarget:Hu,LucideTelescope:Cce,LucideTent:Ece,LucideTentTree:Tce,LucideTerminal:Ace,LucideTerminalSquare:mT,LucideTestTube:Mce,LucideTestTube2:gT,LucideTestTubeDiagonal:gT,LucideTestTubes:Ice,LucideText:Oce,LucideTextCursor:Lce,LucideTextCursorInput:Pce,LucideTextQuote:Dce,LucideTextSearch:Rce,LucideTextSelect:yT,LucideTextSelection:yT,LucideTheater:Fce,LucideThermometer:$ce,LucideThermometerSnowflake:zce,LucideThermometerSun:Bce,LucideThumbsDown:JF,LucideThumbsUp:wm,LucideTicket:e7,LucideTicketCheck:Uce,LucideTicketMinus:qce,LucideTicketPercent:Vce,LucideTicketPlus:Hce,LucideTicketSlash:Gce,LucideTicketX:Wce,LucideTickets:Yce,LucideTicketsPlane:Kce,LucideTimer:Qce,LucideTimerOff:Zce,LucideTimerReset:Xce,LucideToggleLeft:Jce,LucideToggleRight:ede,LucideToilet:tde,LucideTornado:sde,LucideTorus:rde,LucideTouchpad:ade,LucideTouchpadOff:nde,LucideTowerControl:ide,LucideToyBrick:ode,LucideTractor:lde,LucideTrafficCone:cde,LucideTrain:vT,LucideTrainFront:ude,LucideTrainFrontTunnel:dde,LucideTrainTrack:hde,LucideTramFront:vT,LucideTrash:mde,LucideTrash2:zr,LucideTreeDeciduous:fde,LucideTreePalm:bT,LucideTreePine:uS,LucideTrees:pde,LucideTrello:xde,LucideTrendingDown:E_,LucideTrendingUp:Wo,LucideTrendingUpDown:gde,LucideTriangle:vde,LucideTriangleAlert:du,LucideTriangleRight:yde,LucideTrophy:wo,LucideTruck:t7,LucideTurtle:bde,LucideTv:wde,LucideTv2:_T,LucideTvMinimal:_T,LucideTvMinimalPlay:_de,LucideTwitch:jde,LucideTwitter:Nde,LucideType:Sde,LucideTypeOutline:kde,LucideUmbrella:Tde,LucideUmbrellaOff:Cde,LucideUnderline:cP,LucideUndo:hS,LucideUndo2:Ede,LucideUndoDot:Ade,LucideUnfoldHorizontal:Mde,LucideUnfoldVertical:Ide,LucideUngroup:Pde,LucideUniversity:wT,LucideUnlink:WE,LucideUnlink2:Lde,LucideUnlock:Q3,LucideUnlockKeyhole:X3,LucideUnplug:Dde,LucideUpload:ka,LucideUploadCloud:C3,LucideUsb:Rde,LucideUser:qi,LucideUser2:TT,LucideUserCheck:M1,LucideUserCheck2:jT,LucideUserCircle:j3,LucideUserCircle2:w3,LucideUserCog:s7,LucideUserCog2:NT,LucideUserMinus:r7,LucideUserMinus2:kT,LucideUserPen:Ode,LucideUserPlus:xl,LucideUserPlus2:ST,LucideUserRound:TT,LucideUserRoundCheck:jT,LucideUserRoundCog:NT,LucideUserRoundMinus:kT,LucideUserRoundPen:Fde,LucideUserRoundPlus:ST,LucideUserRoundSearch:zde,LucideUserRoundX:CT,LucideUserSearch:Bde,LucideUserSquare:pT,LucideUserSquare2:fT,LucideUserX:$de,LucideUserX2:CT,LucideUsers:Dr,LucideUsers2:ET,LucideUsersRound:ET,LucideUtensils:MT,LucideUtensilsCrossed:AT,LucideUtilityPole:Ude,LucideVariable:dP,LucideVault:qde,LucideVegan:Vde,LucideVenetianMask:Hde,LucideVerified:DC,LucideVibrate:Wde,LucideVibrateOff:Gde,LucideVideo:bn,LucideVideoOff:Kde,LucideVideotape:Yde,LucideView:Zde,LucideVoicemail:Xde,LucideVolleyball:Qde,LucideVolume:tue,LucideVolume1:Jde,LucideVolume2:n7,LucideVolumeOff:eue,LucideVolumeX:a7,LucideVote:sue,LucideWallet:uP,LucideWallet2:IT,LucideWalletCards:rue,LucideWalletMinimal:IT,LucideWallpaper:nue,LucideWand:aue,LucideWand2:p0,LucideWandSparkles:p0,LucideWarehouse:iue,LucideWashingMachine:oue,LucideWatch:lue,LucideWaves:cue,LucideWaypoints:due,LucideWebcam:uue,LucideWebhook:mue,LucideWebhookOff:hue,LucideWeight:fue,LucideWheat:xue,LucideWheatOff:pue,LucideWholeWord:gue,LucideWifi:wue,LucideWifiHigh:yue,LucideWifiLow:vue,LucideWifiOff:bue,LucideWifiZero:_ue,LucideWind:Nue,LucideWindArrowDown:jue,LucideWine:Sue,LucideWineOff:kue,LucideWorkflow:i7,LucideWorm:Cue,LucideWrapText:Tue,LucideWrench:A_,LucideX:$r,LucideXCircle:ad,LucideXOctagon:s5,LucideXSquare:xT,LucideYoutube:Eue,LucideZap:zh,LucideZapOff:Aue,LucideZoomIn:mS,LucideZoomOut:hP,Luggage:tre,LuggageIcon:tre,MSquare:Z5,MSquareIcon:Z5,Magnet:sre,MagnetIcon:sre,Mail:Ks,MailCheck:JI,MailCheckIcon:JI,MailIcon:Ks,MailMinus:rre,MailMinusIcon:rre,MailOpen:IF,MailOpenIcon:IF,MailPlus:PF,MailPlusIcon:PF,MailQuestion:nre,MailQuestionIcon:nre,MailSearch:are,MailSearchIcon:are,MailWarning:ire,MailWarningIcon:ire,MailX:eP,MailXIcon:eP,Mailbox:ore,MailboxIcon:ore,Mails:lre,MailsIcon:lre,Map:FE,MapIcon:FE,MapPin:Ma,MapPinCheck:dre,MapPinCheckIcon:dre,MapPinCheckInside:cre,MapPinCheckInsideIcon:cre,MapPinHouse:ure,MapPinHouseIcon:ure,MapPinIcon:Ma,MapPinMinus:mre,MapPinMinusIcon:mre,MapPinMinusInside:hre,MapPinMinusInsideIcon:hre,MapPinOff:fre,MapPinOffIcon:fre,MapPinPlus:xre,MapPinPlusIcon:xre,MapPinPlusInside:pre,MapPinPlusInsideIcon:pre,MapPinX:yre,MapPinXIcon:yre,MapPinXInside:gre,MapPinXInsideIcon:gre,MapPinned:vre,MapPinnedIcon:vre,Martini:bre,MartiniIcon:bre,Maximize:zE,Maximize2:LF,Maximize2Icon:LF,MaximizeIcon:zE,Medal:c2,MedalIcon:c2,Megaphone:fh,MegaphoneIcon:fh,MegaphoneOff:_re,MegaphoneOffIcon:_re,Meh:wre,MehIcon:wre,MemoryStick:jre,MemoryStickIcon:jre,Menu:aS,MenuIcon:aS,MenuSquare:X5,MenuSquareIcon:X5,Merge:Nre,MergeIcon:Nre,MessageCircle:gc,MessageCircleCode:kre,MessageCircleCodeIcon:kre,MessageCircleDashed:Sre,MessageCircleDashedIcon:Sre,MessageCircleHeart:tP,MessageCircleHeartIcon:tP,MessageCircleIcon:gc,MessageCircleMore:Cre,MessageCircleMoreIcon:Cre,MessageCircleOff:Tre,MessageCircleOffIcon:Tre,MessageCirclePlus:Ere,MessageCirclePlusIcon:Ere,MessageCircleQuestion:DF,MessageCircleQuestionIcon:DF,MessageCircleReply:Are,MessageCircleReplyIcon:Are,MessageCircleWarning:Mre,MessageCircleWarningIcon:Mre,MessageCircleX:Ire,MessageCircleXIcon:Ire,MessageSquare:Ui,MessageSquareCode:Pre,MessageSquareCodeIcon:Pre,MessageSquareDashed:Lre,MessageSquareDashedIcon:Lre,MessageSquareDiff:Dre,MessageSquareDiffIcon:Dre,MessageSquareDot:Rre,MessageSquareDotIcon:Rre,MessageSquareHeart:Ore,MessageSquareHeartIcon:Ore,MessageSquareIcon:Ui,MessageSquareLock:Fre,MessageSquareLockIcon:Fre,MessageSquareMore:RF,MessageSquareMoreIcon:RF,MessageSquareOff:zre,MessageSquareOffIcon:zre,MessageSquarePlus:c_,MessageSquarePlusIcon:c_,MessageSquareQuote:sP,MessageSquareQuoteIcon:sP,MessageSquareReply:Bre,MessageSquareReplyIcon:Bre,MessageSquareShare:$re,MessageSquareShareIcon:$re,MessageSquareText:Ure,MessageSquareTextIcon:Ure,MessageSquareWarning:qre,MessageSquareWarningIcon:qre,MessageSquareX:Vre,MessageSquareXIcon:Vre,MessagesSquare:Hre,MessagesSquareIcon:Hre,Mic:BE,Mic2:J3,Mic2Icon:J3,MicIcon:BE,MicOff:Gre,MicOffIcon:Gre,MicVocal:J3,MicVocalIcon:J3,Microchip:Wre,MicrochipIcon:Wre,Microscope:Kre,MicroscopeIcon:Kre,Microwave:Yre,MicrowaveIcon:Yre,Milestone:Zre,MilestoneIcon:Zre,Milk:Qre,MilkIcon:Qre,MilkOff:Xre,MilkOffIcon:Xre,Minimize:ene,Minimize2:Jre,Minimize2Icon:Jre,MinimizeIcon:ene,Minus:N_,MinusCircle:m3,MinusCircleIcon:m3,MinusIcon:N_,MinusSquare:Q5,MinusSquareIcon:Q5,Monitor:k_,MonitorCheck:tne,MonitorCheckIcon:tne,MonitorCog:sne,MonitorCogIcon:sne,MonitorDot:rne,MonitorDotIcon:rne,MonitorDown:nne,MonitorDownIcon:nne,MonitorIcon:k_,MonitorOff:ane,MonitorOffIcon:ane,MonitorPause:ine,MonitorPauseIcon:ine,MonitorPlay:OF,MonitorPlayIcon:OF,MonitorSmartphone:one,MonitorSmartphoneIcon:one,MonitorSpeaker:lne,MonitorSpeakerIcon:lne,MonitorStop:cne,MonitorStopIcon:cne,MonitorUp:$E,MonitorUpIcon:$E,MonitorX:dne,MonitorXIcon:dne,Moon:hne,MoonIcon:hne,MoonStar:une,MoonStarIcon:une,MoreHorizontal:f0,MoreHorizontalIcon:f0,MoreVertical:Fy,MoreVerticalIcon:Fy,Mountain:fne,MountainIcon:fne,MountainSnow:mne,MountainSnowIcon:mne,Mouse:yne,MouseIcon:yne,MouseOff:pne,MouseOffIcon:pne,MousePointer:dm,MousePointer2:xne,MousePointer2Icon:xne,MousePointerBan:gne,MousePointerBanIcon:gne,MousePointerClick:Bc,MousePointerClickIcon:Bc,MousePointerIcon:dm,MousePointerSquareDashed:U5,MousePointerSquareDashedIcon:U5,Move:Mne,Move3D:e5,Move3DIcon:e5,Move3d:e5,Move3dIcon:e5,MoveDiagonal:bne,MoveDiagonal2:vne,MoveDiagonal2Icon:vne,MoveDiagonalIcon:bne,MoveDown:jne,MoveDownIcon:jne,MoveDownLeft:_ne,MoveDownLeftIcon:_ne,MoveDownRight:wne,MoveDownRightIcon:wne,MoveHorizontal:Nne,MoveHorizontalIcon:Nne,MoveIcon:Mne,MoveLeft:kne,MoveLeftIcon:kne,MoveRight:Sne,MoveRightIcon:Sne,MoveUp:Ene,MoveUpIcon:Ene,MoveUpLeft:Cne,MoveUpLeftIcon:Cne,MoveUpRight:Tne,MoveUpRightIcon:Tne,MoveVertical:Ane,MoveVerticalIcon:Ane,Music:rP,Music2:Ine,Music2Icon:Ine,Music3:Pne,Music3Icon:Pne,Music4:Lne,Music4Icon:Lne,MusicIcon:rP,Navigation:FF,Navigation2:Rne,Navigation2Icon:Rne,Navigation2Off:Dne,Navigation2OffIcon:Dne,NavigationIcon:FF,NavigationOff:One,NavigationOffIcon:One,Network:Fne,NetworkIcon:Fne,Newspaper:E1,NewspaperIcon:E1,Nfc:zne,NfcIcon:zne,Notebook:qne,NotebookIcon:qne,NotebookPen:Bne,NotebookPenIcon:Bne,NotebookTabs:$ne,NotebookTabsIcon:$ne,NotebookText:Une,NotebookTextIcon:Une,NotepadText:Hne,NotepadTextDashed:Vne,NotepadTextDashedIcon:Vne,NotepadTextIcon:Hne,Nut:Wne,NutIcon:Wne,NutOff:Gne,NutOffIcon:Gne,Octagon:Yne,OctagonAlert:Oj,OctagonAlertIcon:Oj,OctagonIcon:Yne,OctagonMinus:Kne,OctagonMinusIcon:Kne,OctagonPause:t5,OctagonPauseIcon:t5,OctagonX:s5,OctagonXIcon:s5,Omega:Zne,OmegaIcon:Zne,Option:Xne,OptionIcon:Xne,Orbit:Qne,OrbitIcon:Qne,Origami:Jne,OrigamiIcon:Jne,Outdent:K3,OutdentIcon:K3,Package:yc,Package2:eae,Package2Icon:eae,PackageCheck:tae,PackageCheckIcon:tae,PackageIcon:yc,PackageMinus:sae,PackageMinusIcon:sae,PackageOpen:rae,PackageOpenIcon:rae,PackagePlus:nae,PackagePlusIcon:nae,PackageSearch:aae,PackageSearchIcon:aae,PackageX:iae,PackageXIcon:iae,PaintBucket:oae,PaintBucketIcon:oae,PaintRoller:lae,PaintRollerIcon:lae,Paintbrush:cae,Paintbrush2:r5,Paintbrush2Icon:r5,PaintbrushIcon:cae,PaintbrushVertical:r5,PaintbrushVerticalIcon:r5,Palette:dl,PaletteIcon:dl,Palmtree:bT,PalmtreeIcon:bT,PanelBottom:hae,PanelBottomClose:dae,PanelBottomCloseIcon:dae,PanelBottomDashed:n5,PanelBottomDashedIcon:n5,PanelBottomIcon:hae,PanelBottomInactive:n5,PanelBottomInactiveIcon:n5,PanelBottomOpen:uae,PanelBottomOpenIcon:uae,PanelLeft:l5,PanelLeftClose:a5,PanelLeftCloseIcon:a5,PanelLeftDashed:i5,PanelLeftDashedIcon:i5,PanelLeftIcon:l5,PanelLeftInactive:i5,PanelLeftInactiveIcon:i5,PanelLeftOpen:o5,PanelLeftOpenIcon:o5,PanelRight:pae,PanelRightClose:mae,PanelRightCloseIcon:mae,PanelRightDashed:c5,PanelRightDashedIcon:c5,PanelRightIcon:pae,PanelRightInactive:c5,PanelRightInactiveIcon:c5,PanelRightOpen:fae,PanelRightOpenIcon:fae,PanelTop:yae,PanelTopClose:xae,PanelTopCloseIcon:xae,PanelTopDashed:d5,PanelTopDashedIcon:d5,PanelTopIcon:yae,PanelTopInactive:d5,PanelTopInactiveIcon:d5,PanelTopOpen:gae,PanelTopOpenIcon:gae,PanelsLeftBottom:vae,PanelsLeftBottomIcon:vae,PanelsLeftRight:E3,PanelsLeftRightIcon:E3,PanelsRightBottom:bae,PanelsRightBottomIcon:bae,PanelsTopBottom:p5,PanelsTopBottomIcon:p5,PanelsTopLeft:Fj,PanelsTopLeftIcon:Fj,Paperclip:iS,PaperclipIcon:iS,Parentheses:_ae,ParenthesesIcon:_ae,ParkingCircle:p3,ParkingCircleIcon:p3,ParkingCircleOff:f3,ParkingCircleOffIcon:f3,ParkingMeter:wae,ParkingMeterIcon:wae,ParkingSquare:tT,ParkingSquareIcon:tT,ParkingSquareOff:eT,ParkingSquareOffIcon:eT,PartyPopper:ph,PartyPopperIcon:ph,Pause:Xf,PauseCircle:x3,PauseCircleIcon:x3,PauseIcon:Xf,PauseOctagon:t5,PauseOctagonIcon:t5,PawPrint:jae,PawPrintIcon:jae,PcCase:Nae,PcCaseIcon:Nae,Pen:zy,PenBox:iu,PenBoxIcon:iu,PenIcon:zy,PenLine:t_,PenLineIcon:t_,PenOff:kae,PenOffIcon:kae,PenSquare:iu,PenSquareIcon:iu,PenTool:oS,PenToolIcon:oS,Pencil:Ua,PencilIcon:Ua,PencilLine:Sae,PencilLineIcon:Sae,PencilOff:Cae,PencilOffIcon:Cae,PencilRuler:Tae,PencilRulerIcon:Tae,Pentagon:Eae,PentagonIcon:Eae,Percent:UE,PercentCircle:g3,PercentCircleIcon:g3,PercentDiamond:M3,PercentDiamondIcon:M3,PercentIcon:UE,PercentSquare:sT,PercentSquareIcon:sT,PersonStanding:Aae,PersonStandingIcon:Aae,PhilippinePeso:Mae,PhilippinePesoIcon:Mae,Phone:Mn,PhoneCall:Iae,PhoneCallIcon:Iae,PhoneForwarded:Pae,PhoneForwardedIcon:Pae,PhoneIcon:Mn,PhoneIncoming:Lae,PhoneIncomingIcon:Lae,PhoneMissed:Dae,PhoneMissedIcon:Dae,PhoneOff:Rae,PhoneOffIcon:Rae,PhoneOutgoing:Oae,PhoneOutgoingIcon:Oae,Pi:Fae,PiIcon:Fae,PiSquare:rT,PiSquareIcon:rT,Piano:zae,PianoIcon:zae,Pickaxe:Bae,PickaxeIcon:Bae,PictureInPicture:Uae,PictureInPicture2:$ae,PictureInPicture2Icon:$ae,PictureInPictureIcon:Uae,PieChart:XC,PieChartIcon:XC,PiggyBank:qae,PiggyBankIcon:qae,Pilcrow:Gae,PilcrowIcon:Gae,PilcrowLeft:Vae,PilcrowLeftIcon:Vae,PilcrowRight:Hae,PilcrowRightIcon:Hae,PilcrowSquare:nT,PilcrowSquareIcon:nT,Pill:Kae,PillBottle:Wae,PillBottleIcon:Wae,PillIcon:Kae,Pin:lS,PinIcon:lS,PinOff:zF,PinOffIcon:zF,Pipette:Yae,PipetteIcon:Yae,Pizza:Zae,PizzaIcon:Zae,Plane:BF,PlaneIcon:BF,PlaneLanding:Xae,PlaneLandingIcon:Xae,PlaneTakeoff:Qae,PlaneTakeoffIcon:Qae,Play:Al,PlayCircle:Ff,PlayCircleIcon:Ff,PlayIcon:Al,PlaySquare:aT,PlaySquareIcon:aT,Plug:d2,Plug2:Jae,Plug2Icon:Jae,PlugIcon:d2,PlugZap:u5,PlugZap2:u5,PlugZap2Icon:u5,PlugZapIcon:u5,Plus:Ys,PlusCircle:y3,PlusCircleIcon:y3,PlusIcon:Ys,PlusSquare:iT,PlusSquareIcon:iT,Pocket:tie,PocketIcon:tie,PocketKnife:eie,PocketKnifeIcon:eie,Podcast:sie,PodcastIcon:sie,Pointer:nie,PointerIcon:nie,PointerOff:rie,PointerOffIcon:rie,Popcorn:aie,PopcornIcon:aie,Popsicle:iie,PopsicleIcon:iie,PoundSterling:oie,PoundSterlingIcon:oie,Power:$F,PowerCircle:v3,PowerCircleIcon:v3,PowerIcon:$F,PowerOff:lie,PowerOffIcon:lie,PowerSquare:oT,PowerSquareIcon:oT,Presentation:Jy,PresentationIcon:Jy,Printer:UF,PrinterCheck:cie,PrinterCheckIcon:cie,PrinterIcon:UF,Projector:die,ProjectorIcon:die,Proportions:uie,ProportionsIcon:uie,Puzzle:hie,PuzzleIcon:hie,Pyramid:mie,PyramidIcon:mie,QrCode:S_,QrCodeIcon:S_,Quote:u2,QuoteIcon:u2,Rabbit:fie,RabbitIcon:fie,Radar:nP,RadarIcon:nP,Radiation:pie,RadiationIcon:pie,Radical:xie,RadicalIcon:xie,Radio:h2,RadioIcon:h2,RadioReceiver:gie,RadioReceiverIcon:gie,RadioTower:yie,RadioTowerIcon:yie,Radius:vie,RadiusIcon:vie,RailSymbol:bie,RailSymbolIcon:bie,Rainbow:_ie,RainbowIcon:_ie,Rat:wie,RatIcon:wie,Ratio:jie,RatioIcon:jie,Receipt:Iie,ReceiptCent:Nie,ReceiptCentIcon:Nie,ReceiptEuro:kie,ReceiptEuroIcon:kie,ReceiptIcon:Iie,ReceiptIndianRupee:Sie,ReceiptIndianRupeeIcon:Sie,ReceiptJapaneseYen:Cie,ReceiptJapaneseYenIcon:Cie,ReceiptPoundSterling:Tie,ReceiptPoundSterlingIcon:Tie,ReceiptRussianRuble:Eie,ReceiptRussianRubleIcon:Eie,ReceiptSwissFranc:Aie,ReceiptSwissFrancIcon:Aie,ReceiptText:Mie,ReceiptTextIcon:Mie,RectangleEllipsis:h5,RectangleEllipsisIcon:h5,RectangleHorizontal:Pie,RectangleHorizontalIcon:Pie,RectangleVertical:Lie,RectangleVerticalIcon:Lie,Recycle:Die,RecycleIcon:Die,Redo:cS,Redo2:Rie,Redo2Icon:Rie,RedoDot:Oie,RedoDotIcon:Oie,RedoIcon:cS,RefreshCcw:aP,RefreshCcwDot:Fie,RefreshCcwDotIcon:Fie,RefreshCcwIcon:aP,RefreshCw:lo,RefreshCwIcon:lo,RefreshCwOff:zie,RefreshCwOffIcon:zie,Refrigerator:Bie,RefrigeratorIcon:Bie,Regex:$ie,RegexIcon:$ie,RemoveFormatting:Uie,RemoveFormattingIcon:Uie,Repeat:qF,Repeat1:qie,Repeat1Icon:qie,Repeat2:Vie,Repeat2Icon:Vie,RepeatIcon:qF,Replace:Gie,ReplaceAll:Hie,ReplaceAllIcon:Hie,ReplaceIcon:Gie,Reply:VF,ReplyAll:Wie,ReplyAllIcon:Wie,ReplyIcon:VF,Rewind:Kie,RewindIcon:Kie,Ribbon:Yie,RibbonIcon:Yie,Rocket:C_,RocketIcon:C_,RockingChair:Zie,RockingChairIcon:Zie,RollerCoaster:Xie,RollerCoasterIcon:Xie,Rotate3D:m5,Rotate3DIcon:m5,Rotate3d:m5,Rotate3dIcon:m5,RotateCcw:ev,RotateCcwIcon:ev,RotateCcwSquare:Qie,RotateCcwSquareIcon:Qie,RotateCw:qE,RotateCwIcon:qE,RotateCwSquare:Jie,RotateCwSquareIcon:Jie,Route:toe,RouteIcon:toe,RouteOff:eoe,RouteOffIcon:eoe,Router:soe,RouterIcon:soe,Rows:f5,Rows2:f5,Rows2Icon:f5,Rows3:p5,Rows3Icon:p5,Rows4:roe,Rows4Icon:roe,RowsIcon:f5,Rss:noe,RssIcon:noe,Ruler:m2,RulerIcon:m2,RussianRuble:aoe,RussianRubleIcon:aoe,Sailboat:ioe,SailboatIcon:ioe,Salad:ooe,SaladIcon:ooe,Sandwich:loe,SandwichIcon:loe,Satellite:doe,SatelliteDish:coe,SatelliteDishIcon:coe,SatelliteIcon:doe,Save:Ml,SaveAll:uoe,SaveAllIcon:uoe,SaveIcon:Ml,SaveOff:hoe,SaveOffIcon:hoe,Scale:HF,Scale3D:x5,Scale3DIcon:x5,Scale3d:x5,Scale3dIcon:x5,ScaleIcon:HF,Scaling:moe,ScalingIcon:moe,Scan:_oe,ScanBarcode:foe,ScanBarcodeIcon:foe,ScanEye:poe,ScanEyeIcon:poe,ScanFace:xoe,ScanFaceIcon:xoe,ScanIcon:_oe,ScanLine:goe,ScanLineIcon:goe,ScanQrCode:yoe,ScanQrCodeIcon:yoe,ScanSearch:voe,ScanSearchIcon:voe,ScanText:boe,ScanTextIcon:boe,ScatterChart:QC,ScatterChartIcon:QC,School:woe,School2:wT,School2Icon:wT,SchoolIcon:woe,Scissors:Noe,ScissorsIcon:Noe,ScissorsLineDashed:joe,ScissorsLineDashedIcon:joe,ScissorsSquare:lT,ScissorsSquareDashedBottom:L5,ScissorsSquareDashedBottomIcon:L5,ScissorsSquareIcon:lT,ScreenShare:Soe,ScreenShareIcon:Soe,ScreenShareOff:koe,ScreenShareOffIcon:koe,Scroll:Toe,ScrollIcon:Toe,ScrollText:Coe,ScrollTextIcon:Coe,Search:_n,SearchCheck:Eoe,SearchCheckIcon:Eoe,SearchCode:Aoe,SearchCodeIcon:Aoe,SearchIcon:_n,SearchSlash:Moe,SearchSlashIcon:Moe,SearchX:GF,SearchXIcon:GF,Section:Ioe,SectionIcon:Ioe,Send:hn,SendHorizonal:g5,SendHorizonalIcon:g5,SendHorizontal:g5,SendHorizontalIcon:g5,SendIcon:hn,SendToBack:Poe,SendToBackIcon:Poe,SeparatorHorizontal:Loe,SeparatorHorizontalIcon:Loe,SeparatorVertical:Doe,SeparatorVerticalIcon:Doe,Server:zoe,ServerCog:Roe,ServerCogIcon:Roe,ServerCrash:Ooe,ServerCrashIcon:Ooe,ServerIcon:zoe,ServerOff:Foe,ServerOffIcon:Foe,Settings:Bo,Settings2:WF,Settings2Icon:WF,SettingsIcon:Bo,Shapes:Boe,ShapesIcon:Boe,Share:KF,Share2:Ec,Share2Icon:Ec,ShareIcon:KF,Sheet:$oe,SheetIcon:$oe,Shell:Uoe,ShellIcon:Uoe,Shield:Oh,ShieldAlert:YF,ShieldAlertIcon:YF,ShieldBan:qoe,ShieldBanIcon:qoe,ShieldCheck:A1,ShieldCheckIcon:A1,ShieldClose:y5,ShieldCloseIcon:y5,ShieldEllipsis:Voe,ShieldEllipsisIcon:Voe,ShieldHalf:Hoe,ShieldHalfIcon:Hoe,ShieldIcon:Oh,ShieldMinus:Goe,ShieldMinusIcon:Goe,ShieldOff:VE,ShieldOffIcon:VE,ShieldPlus:Woe,ShieldPlusIcon:Woe,ShieldQuestion:Koe,ShieldQuestionIcon:Koe,ShieldX:y5,ShieldXIcon:y5,Ship:Zoe,ShipIcon:Zoe,ShipWheel:Yoe,ShipWheelIcon:Yoe,Shirt:Xoe,ShirtIcon:Xoe,ShoppingBag:T_,ShoppingBagIcon:T_,ShoppingBasket:Qoe,ShoppingBasketIcon:Qoe,ShoppingCart:lg,ShoppingCartIcon:lg,Shovel:Joe,ShovelIcon:Joe,ShowerHead:ele,ShowerHeadIcon:ele,Shrink:tle,ShrinkIcon:tle,Shrub:sle,ShrubIcon:sle,Shuffle:HE,ShuffleIcon:HE,Sidebar:l5,SidebarClose:a5,SidebarCloseIcon:a5,SidebarIcon:l5,SidebarOpen:o5,SidebarOpenIcon:o5,Sigma:rle,SigmaIcon:rle,SigmaSquare:cT,SigmaSquareIcon:cT,Signal:lle,SignalHigh:nle,SignalHighIcon:nle,SignalIcon:lle,SignalLow:ale,SignalLowIcon:ale,SignalMedium:ile,SignalMediumIcon:ile,SignalZero:ole,SignalZeroIcon:ole,Signature:cle,SignatureIcon:cle,Signpost:ule,SignpostBig:dle,SignpostBigIcon:dle,SignpostIcon:ule,Siren:hle,SirenIcon:hle,SkipBack:mle,SkipBackIcon:mle,SkipForward:fle,SkipForwardIcon:fle,Skull:ple,SkullIcon:ple,Slack:xle,SlackIcon:xle,Slash:gle,SlashIcon:gle,SlashSquare:dT,SlashSquareIcon:dT,Slice:yle,SliceIcon:yle,Sliders:v5,SlidersHorizontal:dS,SlidersHorizontalIcon:dS,SlidersIcon:v5,SlidersVertical:v5,SlidersVerticalIcon:v5,Smartphone:yg,SmartphoneCharging:vle,SmartphoneChargingIcon:vle,SmartphoneIcon:yg,SmartphoneNfc:ble,SmartphoneNfcIcon:ble,Smile:wle,SmileIcon:wle,SmilePlus:_le,SmilePlusIcon:_le,Snail:jle,SnailIcon:jle,Snowflake:_1,SnowflakeIcon:_1,Sofa:Nle,SofaIcon:Nle,SortAsc:IC,SortAscIcon:IC,SortDesc:EC,SortDescIcon:EC,Soup:kle,SoupIcon:kle,Space:Sle,SpaceIcon:Sle,Spade:Cle,SpadeIcon:Cle,Sparkle:Tle,SparkleIcon:Tle,Sparkles:Ir,SparklesIcon:Ir,Speaker:Ele,SpeakerIcon:Ele,Speech:Ale,SpeechIcon:Ale,SpellCheck:Ile,SpellCheck2:Mle,SpellCheck2Icon:Mle,SpellCheckIcon:Ile,Spline:Ple,SplineIcon:Ple,Split:Lle,SplitIcon:Lle,SplitSquareHorizontal:uT,SplitSquareHorizontalIcon:uT,SplitSquareVertical:hT,SplitSquareVerticalIcon:hT,SprayCan:Dle,SprayCanIcon:Dle,Sprout:GE,SproutIcon:GE,Square:C0,SquareActivity:b5,SquareActivityIcon:b5,SquareArrowDown:j5,SquareArrowDownIcon:j5,SquareArrowDownLeft:_5,SquareArrowDownLeftIcon:_5,SquareArrowDownRight:w5,SquareArrowDownRightIcon:w5,SquareArrowLeft:N5,SquareArrowLeftIcon:N5,SquareArrowOutDownLeft:k5,SquareArrowOutDownLeftIcon:k5,SquareArrowOutDownRight:S5,SquareArrowOutDownRightIcon:S5,SquareArrowOutUpLeft:C5,SquareArrowOutUpLeftIcon:C5,SquareArrowOutUpRight:T5,SquareArrowOutUpRightIcon:T5,SquareArrowRight:E5,SquareArrowRightIcon:E5,SquareArrowUp:I5,SquareArrowUpIcon:I5,SquareArrowUpLeft:A5,SquareArrowUpLeftIcon:A5,SquareArrowUpRight:M5,SquareArrowUpRightIcon:M5,SquareAsterisk:P5,SquareAsteriskIcon:P5,SquareBottomDashedScissors:L5,SquareBottomDashedScissorsIcon:L5,SquareChartGantt:$b,SquareChartGanttIcon:$b,SquareCheck:D5,SquareCheckBig:zj,SquareCheckBigIcon:zj,SquareCheckIcon:D5,SquareChevronDown:R5,SquareChevronDownIcon:R5,SquareChevronLeft:O5,SquareChevronLeftIcon:O5,SquareChevronRight:F5,SquareChevronRightIcon:F5,SquareChevronUp:z5,SquareChevronUpIcon:z5,SquareCode:B5,SquareCodeIcon:B5,SquareDashed:q5,SquareDashedBottom:Ole,SquareDashedBottomCode:Rle,SquareDashedBottomCodeIcon:Rle,SquareDashedBottomIcon:Ole,SquareDashedIcon:q5,SquareDashedKanban:$5,SquareDashedKanbanIcon:$5,SquareDashedMousePointer:U5,SquareDashedMousePointerIcon:U5,SquareDivide:V5,SquareDivideIcon:V5,SquareDot:H5,SquareDotIcon:H5,SquareEqual:G5,SquareEqualIcon:G5,SquareFunction:W5,SquareFunctionIcon:W5,SquareGanttChart:$b,SquareGanttChartIcon:$b,SquareIcon:C0,SquareKanban:K5,SquareKanbanIcon:K5,SquareLibrary:Y5,SquareLibraryIcon:Y5,SquareM:Z5,SquareMIcon:Z5,SquareMenu:X5,SquareMenuIcon:X5,SquareMinus:Q5,SquareMinusIcon:Q5,SquareMousePointer:J5,SquareMousePointerIcon:J5,SquareParking:tT,SquareParkingIcon:tT,SquareParkingOff:eT,SquareParkingOffIcon:eT,SquarePen:iu,SquarePenIcon:iu,SquarePercent:sT,SquarePercentIcon:sT,SquarePi:rT,SquarePiIcon:rT,SquarePilcrow:nT,SquarePilcrowIcon:nT,SquarePlay:aT,SquarePlayIcon:aT,SquarePlus:iT,SquarePlusIcon:iT,SquarePower:oT,SquarePowerIcon:oT,SquareRadical:Fle,SquareRadicalIcon:Fle,SquareScissors:lT,SquareScissorsIcon:lT,SquareSigma:cT,SquareSigmaIcon:cT,SquareSlash:dT,SquareSlashIcon:dT,SquareSplitHorizontal:uT,SquareSplitHorizontalIcon:uT,SquareSplitVertical:hT,SquareSplitVerticalIcon:hT,SquareSquare:zle,SquareSquareIcon:zle,SquareStack:Ble,SquareStackIcon:Ble,SquareTerminal:mT,SquareTerminalIcon:mT,SquareUser:pT,SquareUserIcon:pT,SquareUserRound:fT,SquareUserRoundIcon:fT,SquareX:xT,SquareXIcon:xT,Squircle:$le,SquircleIcon:$le,Squirrel:Ule,SquirrelIcon:Ule,Stamp:qle,StampIcon:qle,Star:fa,StarHalf:Vle,StarHalfIcon:Vle,StarIcon:fa,StarOff:Hle,StarOffIcon:Hle,Stars:Ir,StarsIcon:Ir,StepBack:Gle,StepBackIcon:Gle,StepForward:Wle,StepForwardIcon:Wle,Stethoscope:Kle,StethoscopeIcon:Kle,Sticker:Yle,StickerIcon:Yle,StickyNote:Zle,StickyNoteIcon:Zle,StopCircle:_3,StopCircleIcon:_3,Store:ZF,StoreIcon:ZF,StretchHorizontal:Xle,StretchHorizontalIcon:Xle,StretchVertical:Qle,StretchVerticalIcon:Qle,Strikethrough:XF,StrikethroughIcon:XF,Subscript:Jle,SubscriptIcon:Jle,Subtitles:BC,SubtitlesIcon:BC,Sun:f2,SunDim:ece,SunDimIcon:ece,SunIcon:f2,SunMedium:tce,SunMediumIcon:tce,SunMoon:sce,SunMoonIcon:sce,SunSnow:rce,SunSnowIcon:rce,Sunrise:nce,SunriseIcon:nce,Sunset:ace,SunsetIcon:ace,Superscript:ice,SuperscriptIcon:ice,SwatchBook:oce,SwatchBookIcon:oce,SwissFranc:lce,SwissFrancIcon:lce,SwitchCamera:cce,SwitchCameraIcon:cce,Sword:dce,SwordIcon:dce,Swords:uce,SwordsIcon:uce,Syringe:hce,SyringeIcon:hce,Table:oP,Table2:iP,Table2Icon:iP,TableCellsMerge:mce,TableCellsMergeIcon:mce,TableCellsSplit:fce,TableCellsSplitIcon:fce,TableColumnsSplit:pce,TableColumnsSplitIcon:pce,TableIcon:oP,TableOfContents:xce,TableOfContentsIcon:xce,TableProperties:gce,TablePropertiesIcon:gce,TableRowsSplit:yce,TableRowsSplitIcon:yce,Tablet:lP,TabletIcon:lP,TabletSmartphone:vce,TabletSmartphoneIcon:vce,Tablets:bce,TabletsIcon:bce,Tag:Fh,TagIcon:Fh,Tags:QF,TagsIcon:QF,Tally1:_ce,Tally1Icon:_ce,Tally2:wce,Tally2Icon:wce,Tally3:jce,Tally3Icon:jce,Tally4:Nce,Tally4Icon:Nce,Tally5:kce,Tally5Icon:kce,Tangent:Sce,TangentIcon:Sce,Target:Hu,TargetIcon:Hu,Telescope:Cce,TelescopeIcon:Cce,Tent:Ece,TentIcon:Ece,TentTree:Tce,TentTreeIcon:Tce,Terminal:Ace,TerminalIcon:Ace,TerminalSquare:mT,TerminalSquareIcon:mT,TestTube:Mce,TestTube2:gT,TestTube2Icon:gT,TestTubeDiagonal:gT,TestTubeDiagonalIcon:gT,TestTubeIcon:Mce,TestTubes:Ice,TestTubesIcon:Ice,Text:Oce,TextCursor:Lce,TextCursorIcon:Lce,TextCursorInput:Pce,TextCursorInputIcon:Pce,TextIcon:Oce,TextQuote:Dce,TextQuoteIcon:Dce,TextSearch:Rce,TextSearchIcon:Rce,TextSelect:yT,TextSelectIcon:yT,TextSelection:yT,TextSelectionIcon:yT,Theater:Fce,TheaterIcon:Fce,Thermometer:$ce,ThermometerIcon:$ce,ThermometerSnowflake:zce,ThermometerSnowflakeIcon:zce,ThermometerSun:Bce,ThermometerSunIcon:Bce,ThumbsDown:JF,ThumbsDownIcon:JF,ThumbsUp:wm,ThumbsUpIcon:wm,Ticket:e7,TicketCheck:Uce,TicketCheckIcon:Uce,TicketIcon:e7,TicketMinus:qce,TicketMinusIcon:qce,TicketPercent:Vce,TicketPercentIcon:Vce,TicketPlus:Hce,TicketPlusIcon:Hce,TicketSlash:Gce,TicketSlashIcon:Gce,TicketX:Wce,TicketXIcon:Wce,Tickets:Yce,TicketsIcon:Yce,TicketsPlane:Kce,TicketsPlaneIcon:Kce,Timer:Qce,TimerIcon:Qce,TimerOff:Zce,TimerOffIcon:Zce,TimerReset:Xce,TimerResetIcon:Xce,ToggleLeft:Jce,ToggleLeftIcon:Jce,ToggleRight:ede,ToggleRightIcon:ede,Toilet:tde,ToiletIcon:tde,Tornado:sde,TornadoIcon:sde,Torus:rde,TorusIcon:rde,Touchpad:ade,TouchpadIcon:ade,TouchpadOff:nde,TouchpadOffIcon:nde,TowerControl:ide,TowerControlIcon:ide,ToyBrick:ode,ToyBrickIcon:ode,Tractor:lde,TractorIcon:lde,TrafficCone:cde,TrafficConeIcon:cde,Train:vT,TrainFront:ude,TrainFrontIcon:ude,TrainFrontTunnel:dde,TrainFrontTunnelIcon:dde,TrainIcon:vT,TrainTrack:hde,TrainTrackIcon:hde,TramFront:vT,TramFrontIcon:vT,Trash:mde,Trash2:zr,Trash2Icon:zr,TrashIcon:mde,TreeDeciduous:fde,TreeDeciduousIcon:fde,TreePalm:bT,TreePalmIcon:bT,TreePine:uS,TreePineIcon:uS,Trees:pde,TreesIcon:pde,Trello:xde,TrelloIcon:xde,TrendingDown:E_,TrendingDownIcon:E_,TrendingUp:Wo,TrendingUpDown:gde,TrendingUpDownIcon:gde,TrendingUpIcon:Wo,Triangle:vde,TriangleAlert:du,TriangleAlertIcon:du,TriangleIcon:vde,TriangleRight:yde,TriangleRightIcon:yde,Trophy:wo,TrophyIcon:wo,Truck:t7,TruckIcon:t7,Turtle:bde,TurtleIcon:bde,Tv:wde,Tv2:_T,Tv2Icon:_T,TvIcon:wde,TvMinimal:_T,TvMinimalIcon:_T,TvMinimalPlay:_de,TvMinimalPlayIcon:_de,Twitch:jde,TwitchIcon:jde,Twitter:Nde,TwitterIcon:Nde,Type:Sde,TypeIcon:Sde,TypeOutline:kde,TypeOutlineIcon:kde,Umbrella:Tde,UmbrellaIcon:Tde,UmbrellaOff:Cde,UmbrellaOffIcon:Cde,Underline:cP,UnderlineIcon:cP,Undo:hS,Undo2:Ede,Undo2Icon:Ede,UndoDot:Ade,UndoDotIcon:Ade,UndoIcon:hS,UnfoldHorizontal:Mde,UnfoldHorizontalIcon:Mde,UnfoldVertical:Ide,UnfoldVerticalIcon:Ide,Ungroup:Pde,UngroupIcon:Pde,University:wT,UniversityIcon:wT,Unlink:WE,Unlink2:Lde,Unlink2Icon:Lde,UnlinkIcon:WE,Unlock:Q3,UnlockIcon:Q3,UnlockKeyhole:X3,UnlockKeyholeIcon:X3,Unplug:Dde,UnplugIcon:Dde,Upload:ka,UploadCloud:C3,UploadCloudIcon:C3,UploadIcon:ka,Usb:Rde,UsbIcon:Rde,User:qi,User2:TT,User2Icon:TT,UserCheck:M1,UserCheck2:jT,UserCheck2Icon:jT,UserCheckIcon:M1,UserCircle:j3,UserCircle2:w3,UserCircle2Icon:w3,UserCircleIcon:j3,UserCog:s7,UserCog2:NT,UserCog2Icon:NT,UserCogIcon:s7,UserIcon:qi,UserMinus:r7,UserMinus2:kT,UserMinus2Icon:kT,UserMinusIcon:r7,UserPen:Ode,UserPenIcon:Ode,UserPlus:xl,UserPlus2:ST,UserPlus2Icon:ST,UserPlusIcon:xl,UserRound:TT,UserRoundCheck:jT,UserRoundCheckIcon:jT,UserRoundCog:NT,UserRoundCogIcon:NT,UserRoundIcon:TT,UserRoundMinus:kT,UserRoundMinusIcon:kT,UserRoundPen:Fde,UserRoundPenIcon:Fde,UserRoundPlus:ST,UserRoundPlusIcon:ST,UserRoundSearch:zde,UserRoundSearchIcon:zde,UserRoundX:CT,UserRoundXIcon:CT,UserSearch:Bde,UserSearchIcon:Bde,UserSquare:pT,UserSquare2:fT,UserSquare2Icon:fT,UserSquareIcon:pT,UserX:$de,UserX2:CT,UserX2Icon:CT,UserXIcon:$de,Users:Dr,Users2:ET,Users2Icon:ET,UsersIcon:Dr,UsersRound:ET,UsersRoundIcon:ET,Utensils:MT,UtensilsCrossed:AT,UtensilsCrossedIcon:AT,UtensilsIcon:MT,UtilityPole:Ude,UtilityPoleIcon:Ude,Variable:dP,VariableIcon:dP,Vault:qde,VaultIcon:qde,Vegan:Vde,VeganIcon:Vde,VenetianMask:Hde,VenetianMaskIcon:Hde,Verified:DC,VerifiedIcon:DC,Vibrate:Wde,VibrateIcon:Wde,VibrateOff:Gde,VibrateOffIcon:Gde,Video:bn,VideoIcon:bn,VideoOff:Kde,VideoOffIcon:Kde,Videotape:Yde,VideotapeIcon:Yde,View:Zde,ViewIcon:Zde,Voicemail:Xde,VoicemailIcon:Xde,Volleyball:Qde,VolleyballIcon:Qde,Volume:tue,Volume1:Jde,Volume1Icon:Jde,Volume2:n7,Volume2Icon:n7,VolumeIcon:tue,VolumeOff:eue,VolumeOffIcon:eue,VolumeX:a7,VolumeXIcon:a7,Vote:sue,VoteIcon:sue,Wallet:uP,Wallet2:IT,Wallet2Icon:IT,WalletCards:rue,WalletCardsIcon:rue,WalletIcon:uP,WalletMinimal:IT,WalletMinimalIcon:IT,Wallpaper:nue,WallpaperIcon:nue,Wand:aue,Wand2:p0,Wand2Icon:p0,WandIcon:aue,WandSparkles:p0,WandSparklesIcon:p0,Warehouse:iue,WarehouseIcon:iue,WashingMachine:oue,WashingMachineIcon:oue,Watch:lue,WatchIcon:lue,Waves:cue,WavesIcon:cue,Waypoints:due,WaypointsIcon:due,Webcam:uue,WebcamIcon:uue,Webhook:mue,WebhookIcon:mue,WebhookOff:hue,WebhookOffIcon:hue,Weight:fue,WeightIcon:fue,Wheat:xue,WheatIcon:xue,WheatOff:pue,WheatOffIcon:pue,WholeWord:gue,WholeWordIcon:gue,Wifi:wue,WifiHigh:yue,WifiHighIcon:yue,WifiIcon:wue,WifiLow:vue,WifiLowIcon:vue,WifiOff:bue,WifiOffIcon:bue,WifiZero:_ue,WifiZeroIcon:_ue,Wind:Nue,WindArrowDown:jue,WindArrowDownIcon:jue,WindIcon:Nue,Wine:Sue,WineIcon:Sue,WineOff:kue,WineOffIcon:kue,Workflow:i7,WorkflowIcon:i7,Worm:Cue,WormIcon:Cue,WrapText:Tue,WrapTextIcon:Tue,Wrench:A_,WrenchIcon:A_,X:$r,XCircle:ad,XCircleIcon:ad,XIcon:$r,XOctagon:s5,XOctagonIcon:s5,XSquare:xT,XSquareIcon:xT,Youtube:Eue,YoutubeIcon:Eue,Zap:zh,ZapIcon:zh,ZapOff:Aue,ZapOffIcon:Aue,ZoomIn:mS,ZoomInIcon:mS,ZoomOut:hP,ZoomOutIcon:hP,createLucideIcon:se,icons:i3t},Symbol.toStringTag,{value:"Module"})),u5e="-",o3t=s=>{const t=c3t(s),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=s;return{getClassGroupId:l=>{const o=l.split(u5e);return o[0]===""&&o.length!==1&&o.shift(),ret(o,t)||l3t(l)},getConflictingClassGroupIds:(l,o)=>{const c=r[l]||[];return o&&n[l]?[...c,...n[l]]:c}}},ret=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const r=s[0],n=t.nextPart.get(r),a=n?ret(s.slice(1),n):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(u5e);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},EOe=/^\[(.+)\]$/,l3t=s=>{if(EOe.test(s)){const t=EOe.exec(s)[1],r=t==null?void 0:t.substring(0,t.indexOf(":"));if(r)return"arbitrary.."+r}},c3t=s=>{const{theme:t,prefix:r}=s,n={nextPart:new Map,validators:[]};return u3t(Object.entries(s.classGroups),r).forEach(([i,l])=>{J2e(l,n,i,t)}),n},J2e=(s,t,r,n)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:AOe(t,a);i.classGroupId=r;return}if(typeof a=="function"){if(d3t(a)){J2e(a(n),t,r,n);return}t.validators.push({validator:a,classGroupId:r});return}Object.entries(a).forEach(([i,l])=>{J2e(l,AOe(t,i),r,n)})})},AOe=(s,t)=>{let r=s;return t.split(u5e).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},d3t=s=>s.isThemeGetter,u3t=(s,t)=>t?s.map(([r,n])=>{const a=n.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[t+l,o])):i);return[r,a]}):s,h3t=s=>{if(s<1)return{get:()=>{},set:()=>{}};let t=0,r=new Map,n=new Map;const a=(i,l)=>{r.set(i,l),t++,t>s&&(t=0,n=r,r=new Map)};return{get(i){let l=r.get(i);if(l!==void 0)return l;if((l=n.get(i))!==void 0)return a(i,l),l},set(i,l){r.has(i)?r.set(i,l):a(i,l)}}},net="!",m3t=s=>{const{separator:t,experimentalParseClassName:r}=s,n=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,u=0,m;for(let b=0;bu?m-u:void 0;return{modifiers:c,hasImportantModifier:x,baseClassName:y,maybePostfixModifierPosition:_}};return r?o=>r({className:o,parseClassName:l}):l},f3t=s=>{if(s.length<=1)return s;const t=[];let r=[];return s.forEach(n=>{n[0]==="["?(t.push(...r.sort(),n),r=[]):r.push(n)}),t.push(...r.sort()),t},p3t=s=>({cache:h3t(s.cacheSize),parseClassName:m3t(s),...o3t(s)}),x3t=/\s+/,g3t=(s,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(x3t);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:m,baseClassName:f,maybePostfixModifierPosition:x}=r(d);let y=!!x,_=n(y?f.substring(0,x):f);if(!_){if(!y){o=d+(o.length>0?" "+o:o);continue}if(_=n(f),!_){o=d+(o.length>0?" "+o:o);continue}y=!1}const b=f3t(u).join(":"),j=m?b+net:b,N=j+_;if(i.includes(N))continue;i.push(N);const C=a(_,y);for(let A=0;A0?" "+o:o)}return o};function y3t(){let s=0,t,r,n="";for(;s{if(typeof s=="string")return s;let t,r="";for(let n=0;nm(u),s());return r=p3t(d),n=r.cache.get,a=r.cache.set,i=o,o(c)}function o(c){const d=n(c);if(d)return d;const u=g3t(c,r);return a(c,u),u}return function(){return i(y3t.apply(null,arguments))}}const yd=s=>{const t=r=>r[s]||[];return t.isThemeGetter=!0,t},iet=/^\[(?:([a-z-]+):)?(.+)\]$/i,b3t=/^\d+\/\d+$/,_3t=new Set(["px","full","screen"]),w3t=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,j3t=/\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$/,N3t=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,k3t=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,S3t=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,hj=s=>mP(s)||_3t.has(s)||b3t.test(s),PN=s=>m8(s,"length",L3t),mP=s=>!!s&&!Number.isNaN(Number(s)),gbe=s=>m8(s,"number",mP),MR=s=>!!s&&Number.isInteger(Number(s)),C3t=s=>s.endsWith("%")&&mP(s.slice(0,-1)),Eo=s=>iet.test(s),LN=s=>w3t.test(s),T3t=new Set(["length","size","percentage"]),E3t=s=>m8(s,T3t,oet),A3t=s=>m8(s,"position",oet),M3t=new Set(["image","url"]),I3t=s=>m8(s,M3t,R3t),P3t=s=>m8(s,"",D3t),IR=()=>!0,m8=(s,t,r)=>{const n=iet.exec(s);return n?n[1]?typeof t=="string"?n[1]===t:t.has(n[1]):r(n[2]):!1},L3t=s=>j3t.test(s)&&!N3t.test(s),oet=()=>!1,D3t=s=>k3t.test(s),R3t=s=>S3t.test(s),O3t=()=>{const s=yd("colors"),t=yd("spacing"),r=yd("blur"),n=yd("brightness"),a=yd("borderColor"),i=yd("borderRadius"),l=yd("borderSpacing"),o=yd("borderWidth"),c=yd("contrast"),d=yd("grayscale"),u=yd("hueRotate"),m=yd("invert"),f=yd("gap"),x=yd("gradientColorStops"),y=yd("gradientColorStopPositions"),_=yd("inset"),b=yd("margin"),j=yd("opacity"),N=yd("padding"),C=yd("saturate"),A=yd("scale"),E=yd("sepia"),D=yd("skew"),R=yd("space"),F=yd("translate"),O=()=>["auto","contain","none"],B=()=>["auto","hidden","clip","visible","scroll"],K=()=>["auto",Eo,t],Z=()=>[Eo,t],Q=()=>["",hj,PN],W=()=>["auto",mP,Eo],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ne=()=>["solid","dashed","dotted","double","none"],ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ue=()=>["start","end","center","between","around","evenly","stretch"],me=()=>["","0",Eo],de=()=>["auto","avoid","all","avoid-page","page","left","right","column"],fe=()=>[mP,Eo];return{cacheSize:500,separator:":",theme:{colors:[IR],spacing:[hj,PN],blur:["none","",LN,Eo],brightness:fe(),borderColor:[s],borderRadius:["none","","full",LN,Eo],borderSpacing:Z(),borderWidth:Q(),contrast:fe(),grayscale:me(),hueRotate:fe(),invert:me(),gap:Z(),gradientColorStops:[s],gradientColorStopPositions:[C3t,PN],inset:K(),margin:K(),opacity:fe(),padding:Z(),saturate:fe(),scale:fe(),sepia:me(),skew:fe(),space:Z(),translate:Z()},classGroups:{aspect:[{aspect:["auto","square","video",Eo]}],container:["container"],columns:[{columns:[LN]}],"break-after":[{"break-after":de()}],"break-before":[{"break-before":de()}],"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:[...te(),Eo]}],overflow:[{overflow:B()}],"overflow-x":[{"overflow-x":B()}],"overflow-y":[{"overflow-y":B()}],overscroll:[{overscroll:O()}],"overscroll-x":[{"overscroll-x":O()}],"overscroll-y":[{"overscroll-y":O()}],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",MR,Eo]}],basis:[{basis:K()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Eo]}],grow:[{grow:me()}],shrink:[{shrink:me()}],order:[{order:["first","last","none",MR,Eo]}],"grid-cols":[{"grid-cols":[IR]}],"col-start-end":[{col:["auto",{span:["full",MR,Eo]},Eo]}],"col-start":[{"col-start":W()}],"col-end":[{"col-end":W()}],"grid-rows":[{"grid-rows":[IR]}],"row-start-end":[{row:["auto",{span:[MR,Eo]},Eo]}],"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",Eo]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Eo]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...ue()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ue(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ue(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[N]}],px:[{px:[N]}],py:[{py:[N]}],ps:[{ps:[N]}],pe:[{pe:[N]}],pt:[{pt:[N]}],pr:[{pr:[N]}],pb:[{pb:[N]}],pl:[{pl:[N]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[R]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[R]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Eo,t]}],"min-w":[{"min-w":[Eo,t,"min","max","fit"]}],"max-w":[{"max-w":[Eo,t,"none","full","min","max","fit","prose",{screen:[LN]},LN]}],h:[{h:[Eo,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Eo,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Eo,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Eo,t,"auto","min","max","fit"]}],"font-size":[{text:["base",LN,PN]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",gbe]}],"font-family":[{font:[IR]}],"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",Eo]}],"line-clamp":[{"line-clamp":["none",mP,gbe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",hj,Eo]}],"list-image":[{"list-image":["none",Eo]}],"list-style-type":[{list:["none","disc","decimal",Eo]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ne(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",hj,PN]}],"underline-offset":[{"underline-offset":["auto",hj,Eo]}],"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",Eo]}],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",Eo]}],"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:[...te(),A3t]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",E3t]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},I3t]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[y]}],"gradient-via-pos":[{via:[y]}],"gradient-to-pos":[{to:[y]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...ne(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[j]}],"divide-style":[{divide:ne()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...ne()]}],"outline-offset":[{"outline-offset":[hj,Eo]}],"outline-w":[{outline:[hj,PN]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:Q()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[hj,PN]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",LN,P3t]}],"shadow-color":[{shadow:[IR]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...ae(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":ae()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",LN,Eo]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[m]}],saturate:[{saturate:[C]}],sepia:[{sepia:[E]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"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",Eo]}],duration:[{duration:fe()}],ease:[{ease:["linear","in","out","in-out",Eo]}],delay:[{delay:fe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Eo]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[A]}],"scale-x":[{"scale-x":[A]}],"scale-y":[{"scale-y":[A]}],rotate:[{rotate:[MR,Eo]}],"translate-x":[{"translate-x":[F]}],"translate-y":[{"translate-y":[F]}],"skew-x":[{"skew-x":[D]}],"skew-y":[{"skew-y":[D]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Eo]}],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",Eo]}],"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",Eo]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[hj,PN,gbe]}],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"]}}},F3t=v3t(O3t);function zt(...s){return F3t(_o(s))}function nd(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 MOe(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function x9(s){return s?s.replace(/<[^>]*>/g,""):""}const z3t=r3t,cet=k.forwardRef(({className:s,...t},r)=>e.jsx(KJe,{ref:r,className:zt("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}));cet.displayName=KJe.displayName;const B3t=WA("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"}}),det=k.forwardRef(({className:s,variant:t,...r},n)=>e.jsx(YJe,{ref:n,className:zt(B3t({variant:t}),s),...r}));det.displayName=YJe.displayName;const $3t=k.forwardRef(({className:s,...t},r)=>e.jsx(QJe,{ref:r,className:zt("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}));$3t.displayName=QJe.displayName;const uet=k.forwardRef(({className:s,...t},r)=>e.jsx(JJe,{ref:r,className:zt("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($r,{className:"h-4 w-4"})}));uet.displayName=JJe.displayName;const het=k.forwardRef(({className:s,...t},r)=>e.jsx(ZJe,{ref:r,className:zt("text-sm font-semibold",s),...t}));het.displayName=ZJe.displayName;const met=k.forwardRef(({className:s,...t},r)=>e.jsx(XJe,{ref:r,className:zt("text-sm opacity-90",s),...t}));met.displayName=XJe.displayName;function U3t(){const{toasts:s}=Ba();return e.jsxs(z3t,{children:[s.map(function({id:t,title:r,description:n,action:a,...i}){return e.jsxs(det,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[r&&e.jsx(het,{children:r}),n&&e.jsx(met,{children:n})]}),a,e.jsx(uet,{})]},t)}),e.jsx(cet,{})]})}var IOe=["light","dark"],q3t="(prefers-color-scheme: dark)",V3t=k.createContext(void 0),H3t={setTheme:s=>{},themes:[]},G3t=()=>{var s;return(s=k.useContext(V3t))!=null?s:H3t};k.memo(({forcedTheme:s,storageKey:t,attribute:r,enableSystem:n,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(y=>`'${y}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,m=a?IOe.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",f=(y,_=!1,b=!0)=>{let j=l?l[y]:y,N=_?y+"|| ''":`'${j}'`,C="";return a&&b&&!_&&IOe.includes(y)&&(C+=`d.style.colorScheme = '${y}';`),r==="class"?_||j?C+=`c.add(${N})`:C+="null":j&&(C+=`d[s](n,${N})`),C},x=s?`!function(){${u}${f(s)}}()`:n?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${q3t}',m=window.matchMedia(t);if(m.media!==t||m.matches){${f("dark")}}else{${f("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${f(l?"x[e]":"e",!0)}}${d?"":"else{"+f(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${f(l?"x[e]":"e",!0)}}else{${f(i,!1,!1)};}${m}}catch(t){}}();`;return k.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:x}})});var W3t=s=>{switch(s){case"success":return Z3t;case"info":return Q3t;case"warning":return X3t;case"error":return J3t;default:return null}},K3t=Array(12).fill(0),Y3t=({visible:s,className:t})=>Ct.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Ct.createElement("div",{className:"sonner-spinner"},K3t.map((r,n)=>Ct.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),Z3t=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"})),X3t=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"})),Q3t=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"})),J3t=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"})),e5t=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"})),t5t=()=>{let[s,t]=Ct.useState(document.hidden);return Ct.useEffect(()=>{let r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),s},eNe=1,s5t=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let r=this.subscribers.indexOf(t);this.subscribers.splice(r,1)}),this.publish=t=>{this.subscribers.forEach(r=>r(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var r;let{message:n,...a}=t,i=typeof(t==null?void 0:t.id)=="number"||((r=t.id)==null?void 0:r.length)>0?t.id:eNe++,l=this.toasts.find(c=>c.id===i),o=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),l?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...t,id:i,title:n}),{...c,...t,id:i,dismissible:o,title:n}):c):this.addToast({title:n,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(r=>{this.subscribers.forEach(n=>n({id:r.id,dismiss:!0}))}),this.subscribers.forEach(r=>r({id:t,dismiss:!0})),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let n;r.loading!==void 0&&(n=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));let a=t instanceof Promise?t:t(),i=n!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],Ct.isValidElement(d))i=!1,this.create({id:n,type:"default",message:d});else if(n5t(d)&&!d.ok){i=!1;let u=typeof r.error=="function"?await r.error(`HTTP error! status: ${d.status}`):r.error,m=typeof r.description=="function"?await r.description(`HTTP error! status: ${d.status}`):r.description;this.create({id:n,type:"error",message:u,description:m})}else if(r.success!==void 0){i=!1;let u=typeof r.success=="function"?await r.success(d):r.success,m=typeof r.description=="function"?await r.description(d):r.description;this.create({id:n,type:"success",message:u,description:m})}}).catch(async d=>{if(l=["reject",d],r.error!==void 0){i=!1;let u=typeof r.error=="function"?await r.error(d):r.error,m=typeof r.description=="function"?await r.description(d):r.description;this.create({id:n,type:"error",message:u,description:m})}}).finally(()=>{var d;i&&(this.dismiss(n),n=void 0),(d=r.finally)==null||d.call(r)}),c=()=>new Promise((d,u)=>o.then(()=>l[0]==="reject"?u(l[1]):d(l[1])).catch(u));return typeof n!="string"&&typeof n!="number"?{unwrap:c}:Object.assign(n,{unwrap:c})},this.custom=(t,r)=>{let n=(r==null?void 0:r.id)||eNe++;return this.create({jsx:t(n),id:n,...r}),n},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},sg=new s5t,r5t=(s,t)=>{let r=(t==null?void 0:t.id)||eNe++;return sg.addToast({title:s,...t,id:r}),r},n5t=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",a5t=r5t,i5t=()=>sg.toasts,o5t=()=>sg.getActiveToasts(),he=Object.assign(a5t,{success:sg.success,info:sg.info,warning:sg.warning,error:sg.error,custom:sg.custom,message:sg.message,promise:sg.promise,dismiss:sg.dismiss,loading:sg.loading},{getHistory:i5t,getToasts:o5t});function l5t(s,{insertAt:t}={}){if(typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t==="top"&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=s:n.appendChild(document.createTextNode(s))}l5t(`: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 ZU(s){return s.label!==void 0}var c5t=3,d5t="32px",u5t="16px",POe=4e3,h5t=356,m5t=14,f5t=20,p5t=200;function Xv(...s){return s.filter(Boolean).join(" ")}function x5t(s){let[t,r]=s.split("-"),n=[];return t&&n.push(t),r&&n.push(r),n}var g5t=s=>{var t,r,n,a,i,l,o,c,d,u,m;let{invert:f,toast:x,unstyled:y,interacting:_,setHeights:b,visibleToasts:j,heights:N,index:C,toasts:A,expanded:E,removeToast:D,defaultRichColors:R,closeButton:F,style:O,cancelButtonStyle:B,actionButtonStyle:K,className:Z="",descriptionClassName:Q="",duration:W,position:te,gap:ne,loadingIcon:ae,expandByDefault:ue,classNames:me,icons:de,closeButtonAriaLabel:fe="Close toast",pauseWhenPageIsHidden:je}=s,[xe,Ee]=Ct.useState(null),[Me,Oe]=Ct.useState(null),[Ie,ze]=Ct.useState(!1),[Ve,Le]=Ct.useState(!1),[$e,ve]=Ct.useState(!1),[Qe,we]=Ct.useState(!1),[nt,Se]=Ct.useState(!1),[Ge,We]=Ct.useState(0),[Ce,qe]=Ct.useState(0),et=Ct.useRef(x.duration||W||POe),Ze=Ct.useRef(null),rt=Ct.useRef(null),ct=C===0,vt=C+1<=j,kt=x.type,St=x.dismissible!==!1,Yt=x.className||"",es=x.descriptionClassName||"",zs=Ct.useMemo(()=>N.findIndex(Sr=>Sr.toastId===x.id)||0,[N,x.id]),sr=Ct.useMemo(()=>{var Sr;return(Sr=x.closeButton)!=null?Sr:F},[x.closeButton,F]),ms=Ct.useMemo(()=>x.duration||W||POe,[x.duration,W]),gt=Ct.useRef(0),Ut=Ct.useRef(0),ht=Ct.useRef(0),Jt=Ct.useRef(null),[Ms,ts]=te.split("-"),Xs=Ct.useMemo(()=>N.reduce((Sr,Gr,Yr)=>Yr>=zs?Sr:Sr+Gr.height,0),[N,zs]),js=t5t(),$s=x.invert||f,Js=kt==="loading";Ut.current=Ct.useMemo(()=>zs*ne+Xs,[zs,Xs]),Ct.useEffect(()=>{et.current=ms},[ms]),Ct.useEffect(()=>{ze(!0)},[]),Ct.useEffect(()=>{let Sr=rt.current;if(Sr){let Gr=Sr.getBoundingClientRect().height;return qe(Gr),b(Yr=>[{toastId:x.id,height:Gr,position:x.position},...Yr]),()=>b(Yr=>Yr.filter(Fn=>Fn.toastId!==x.id))}},[b,x.id]),Ct.useLayoutEffect(()=>{if(!Ie)return;let Sr=rt.current,Gr=Sr.style.height;Sr.style.height="auto";let Yr=Sr.getBoundingClientRect().height;Sr.style.height=Gr,qe(Yr),b(Fn=>Fn.find(sa=>sa.toastId===x.id)?Fn.map(sa=>sa.toastId===x.id?{...sa,height:Yr}:sa):[{toastId:x.id,height:Yr,position:x.position},...Fn])},[Ie,x.title,x.description,b,x.id]);let or=Ct.useCallback(()=>{Le(!0),We(Ut.current),b(Sr=>Sr.filter(Gr=>Gr.toastId!==x.id)),setTimeout(()=>{D(x)},p5t)},[x,D,b,Ut]);Ct.useEffect(()=>{if(x.promise&&kt==="loading"||x.duration===1/0||x.type==="loading")return;let Sr;return E||_||je&&js?(()=>{if(ht.current{var Gr;(Gr=x.onAutoClose)==null||Gr.call(x,x),or()},et.current)),()=>clearTimeout(Sr)},[E,_,x,kt,je,js,or]),Ct.useEffect(()=>{x.delete&&or()},[or,x.delete]);function Er(){var Sr,Gr,Yr;return de!=null&&de.loading?Ct.createElement("div",{className:Xv(me==null?void 0:me.loader,(Sr=x==null?void 0:x.classNames)==null?void 0:Sr.loader,"sonner-loader"),"data-visible":kt==="loading"},de.loading):ae?Ct.createElement("div",{className:Xv(me==null?void 0:me.loader,(Gr=x==null?void 0:x.classNames)==null?void 0:Gr.loader,"sonner-loader"),"data-visible":kt==="loading"},ae):Ct.createElement(Y3t,{className:Xv(me==null?void 0:me.loader,(Yr=x==null?void 0:x.classNames)==null?void 0:Yr.loader),visible:kt==="loading"})}return Ct.createElement("li",{tabIndex:0,ref:rt,className:Xv(Z,Yt,me==null?void 0:me.toast,(t=x==null?void 0:x.classNames)==null?void 0:t.toast,me==null?void 0:me.default,me==null?void 0:me[kt],(r=x==null?void 0:x.classNames)==null?void 0:r[kt]),"data-sonner-toast":"","data-rich-colors":(n=x.richColors)!=null?n:R,"data-styled":!(x.jsx||x.unstyled||y),"data-mounted":Ie,"data-promise":!!x.promise,"data-swiped":nt,"data-removed":Ve,"data-visible":vt,"data-y-position":Ms,"data-x-position":ts,"data-index":C,"data-front":ct,"data-swiping":$e,"data-dismissible":St,"data-type":kt,"data-invert":$s,"data-swipe-out":Qe,"data-swipe-direction":Me,"data-expanded":!!(E||ue&&Ie),style:{"--index":C,"--toasts-before":C,"--z-index":A.length-C,"--offset":`${Ve?Ge:Ut.current}px`,"--initial-height":ue?"auto":`${Ce}px`,...O,...x.style},onDragEnd:()=>{ve(!1),Ee(null),Jt.current=null},onPointerDown:Sr=>{Js||!St||(Ze.current=new Date,We(Ut.current),Sr.target.setPointerCapture(Sr.pointerId),Sr.target.tagName!=="BUTTON"&&(ve(!0),Jt.current={x:Sr.clientX,y:Sr.clientY}))},onPointerUp:()=>{var Sr,Gr,Yr,Fn;if(Qe||!St)return;Jt.current=null;let sa=Number(((Sr=rt.current)==null?void 0:Sr.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),gs=Number(((Gr=rt.current)==null?void 0:Gr.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),mi=new Date().getTime()-((Yr=Ze.current)==null?void 0:Yr.getTime()),In=xe==="x"?sa:gs,Br=Math.abs(In)/mi;if(Math.abs(In)>=f5t||Br>.11){We(Ut.current),(Fn=x.onDismiss)==null||Fn.call(x,x),Oe(xe==="x"?sa>0?"right":"left":gs>0?"down":"up"),or(),we(!0),Se(!1);return}ve(!1),Ee(null)},onPointerMove:Sr=>{var Gr,Yr,Fn,sa;if(!Jt.current||!St||((Gr=window.getSelection())==null?void 0:Gr.toString().length)>0)return;let gs=Sr.clientY-Jt.current.y,mi=Sr.clientX-Jt.current.x,In=(Yr=s.swipeDirections)!=null?Yr:x5t(te);!xe&&(Math.abs(mi)>1||Math.abs(gs)>1)&&Ee(Math.abs(mi)>Math.abs(gs)?"x":"y");let Br={x:0,y:0};xe==="y"?(In.includes("top")||In.includes("bottom"))&&(In.includes("top")&&gs<0||In.includes("bottom")&&gs>0)&&(Br.y=gs):xe==="x"&&(In.includes("left")||In.includes("right"))&&(In.includes("left")&&mi<0||In.includes("right")&&mi>0)&&(Br.x=mi),(Math.abs(Br.x)>0||Math.abs(Br.y)>0)&&Se(!0),(Fn=rt.current)==null||Fn.style.setProperty("--swipe-amount-x",`${Br.x}px`),(sa=rt.current)==null||sa.style.setProperty("--swipe-amount-y",`${Br.y}px`)}},sr&&!x.jsx?Ct.createElement("button",{"aria-label":fe,"data-disabled":Js,"data-close-button":!0,onClick:Js||!St?()=>{}:()=>{var Sr;or(),(Sr=x.onDismiss)==null||Sr.call(x,x)},className:Xv(me==null?void 0:me.closeButton,(a=x==null?void 0:x.classNames)==null?void 0:a.closeButton)},(i=de==null?void 0:de.close)!=null?i:e5t):null,x.jsx||k.isValidElement(x.title)?x.jsx?x.jsx:typeof x.title=="function"?x.title():x.title:Ct.createElement(Ct.Fragment,null,kt||x.icon||x.promise?Ct.createElement("div",{"data-icon":"",className:Xv(me==null?void 0:me.icon,(l=x==null?void 0:x.classNames)==null?void 0:l.icon)},x.promise||x.type==="loading"&&!x.icon?x.icon||Er():null,x.type!=="loading"?x.icon||(de==null?void 0:de[kt])||W3t(kt):null):null,Ct.createElement("div",{"data-content":"",className:Xv(me==null?void 0:me.content,(o=x==null?void 0:x.classNames)==null?void 0:o.content)},Ct.createElement("div",{"data-title":"",className:Xv(me==null?void 0:me.title,(c=x==null?void 0:x.classNames)==null?void 0:c.title)},typeof x.title=="function"?x.title():x.title),x.description?Ct.createElement("div",{"data-description":"",className:Xv(Q,es,me==null?void 0:me.description,(d=x==null?void 0:x.classNames)==null?void 0:d.description)},typeof x.description=="function"?x.description():x.description):null),k.isValidElement(x.cancel)?x.cancel:x.cancel&&ZU(x.cancel)?Ct.createElement("button",{"data-button":!0,"data-cancel":!0,style:x.cancelButtonStyle||B,onClick:Sr=>{var Gr,Yr;ZU(x.cancel)&&St&&((Yr=(Gr=x.cancel).onClick)==null||Yr.call(Gr,Sr),or())},className:Xv(me==null?void 0:me.cancelButton,(u=x==null?void 0:x.classNames)==null?void 0:u.cancelButton)},x.cancel.label):null,k.isValidElement(x.action)?x.action:x.action&&ZU(x.action)?Ct.createElement("button",{"data-button":!0,"data-action":!0,style:x.actionButtonStyle||K,onClick:Sr=>{var Gr,Yr;ZU(x.action)&&((Yr=(Gr=x.action).onClick)==null||Yr.call(Gr,Sr),!Sr.defaultPrevented&&or())},className:Xv(me==null?void 0:me.actionButton,(m=x==null?void 0:x.classNames)==null?void 0:m.actionButton)},x.action.label):null))};function LOe(){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 y5t(s,t){let r={};return[s,t].forEach((n,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?u5t:d5t;function c(d){["top","right","bottom","left"].forEach(u=>{r[`${l}-${u}`]=typeof d=="number"?`${d}px`:d})}typeof n=="number"||typeof n=="string"?c(n):typeof n=="object"?["top","right","bottom","left"].forEach(d=>{n[d]===void 0?r[`${l}-${d}`]=o:r[`${l}-${d}`]=typeof n[d]=="number"?`${n[d]}px`:n[d]}):c(o)}),r}var v5t=k.forwardRef(function(s,t){let{invert:r,position:n="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:m,duration:f,style:x,visibleToasts:y=c5t,toastOptions:_,dir:b=LOe(),gap:j=m5t,loadingIcon:N,icons:C,containerAriaLabel:A="Notifications",pauseWhenPageIsHidden:E}=s,[D,R]=Ct.useState([]),F=Ct.useMemo(()=>Array.from(new Set([n].concat(D.filter(je=>je.position).map(je=>je.position)))),[D,n]),[O,B]=Ct.useState([]),[K,Z]=Ct.useState(!1),[Q,W]=Ct.useState(!1),[te,ne]=Ct.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ae=Ct.useRef(null),ue=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),me=Ct.useRef(null),de=Ct.useRef(!1),fe=Ct.useCallback(je=>{R(xe=>{var Ee;return(Ee=xe.find(Me=>Me.id===je.id))!=null&&Ee.delete||sg.dismiss(je.id),xe.filter(({id:Me})=>Me!==je.id)})},[]);return Ct.useEffect(()=>sg.subscribe(je=>{if(je.dismiss){R(xe=>xe.map(Ee=>Ee.id===je.id?{...Ee,delete:!0}:Ee));return}setTimeout(()=>{a5e.flushSync(()=>{R(xe=>{let Ee=xe.findIndex(Me=>Me.id===je.id);return Ee!==-1?[...xe.slice(0,Ee),{...xe[Ee],...je},...xe.slice(Ee+1)]:[je,...xe]})})})}),[]),Ct.useEffect(()=>{if(u!=="system"){ne(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ne("dark"):ne("light")),typeof window>"u")return;let je=window.matchMedia("(prefers-color-scheme: dark)");try{je.addEventListener("change",({matches:xe})=>{ne(xe?"dark":"light")})}catch{je.addListener(({matches:Ee})=>{try{ne(Ee?"dark":"light")}catch(Me){console.error(Me)}})}},[u]),Ct.useEffect(()=>{D.length<=1&&Z(!1)},[D]),Ct.useEffect(()=>{let je=xe=>{var Ee,Me;a.every(Oe=>xe[Oe]||xe.code===Oe)&&(Z(!0),(Ee=ae.current)==null||Ee.focus()),xe.code==="Escape"&&(document.activeElement===ae.current||(Me=ae.current)!=null&&Me.contains(document.activeElement))&&Z(!1)};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[a]),Ct.useEffect(()=>{if(ae.current)return()=>{me.current&&(me.current.focus({preventScroll:!0}),me.current=null,de.current=!1)}},[ae.current]),Ct.createElement("section",{ref:t,"aria-label":`${A} ${ue}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},F.map((je,xe)=>{var Ee;let[Me,Oe]=je.split("-");return D.length?Ct.createElement("ol",{key:je,dir:b==="auto"?LOe():b,tabIndex:-1,ref:ae,className:o,"data-sonner-toaster":!0,"data-theme":te,"data-y-position":Me,"data-lifted":K&&D.length>1&&!i,"data-x-position":Oe,style:{"--front-toast-height":`${((Ee=O[0])==null?void 0:Ee.height)||0}px`,"--width":`${h5t}px`,"--gap":`${j}px`,...x,...y5t(c,d)},onBlur:Ie=>{de.current&&!Ie.currentTarget.contains(Ie.relatedTarget)&&(de.current=!1,me.current&&(me.current.focus({preventScroll:!0}),me.current=null))},onFocus:Ie=>{Ie.target instanceof HTMLElement&&Ie.target.dataset.dismissible==="false"||de.current||(de.current=!0,me.current=Ie.relatedTarget)},onMouseEnter:()=>Z(!0),onMouseMove:()=>Z(!0),onMouseLeave:()=>{Q||Z(!1)},onDragEnd:()=>Z(!1),onPointerDown:Ie=>{Ie.target instanceof HTMLElement&&Ie.target.dataset.dismissible==="false"||W(!0)},onPointerUp:()=>W(!1)},D.filter(Ie=>!Ie.position&&xe===0||Ie.position===je).map((Ie,ze)=>{var Ve,Le;return Ct.createElement(g5t,{key:Ie.id,icons:C,index:ze,toast:Ie,defaultRichColors:m,duration:(Ve=_==null?void 0:_.duration)!=null?Ve:f,className:_==null?void 0:_.className,descriptionClassName:_==null?void 0:_.descriptionClassName,invert:r,visibleToasts:y,closeButton:(Le=_==null?void 0:_.closeButton)!=null?Le:l,interacting:Q,position:je,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:fe,toasts:D.filter($e=>$e.position==Ie.position),heights:O.filter($e=>$e.position==Ie.position),setHeights:B,expandByDefault:i,gap:j,loadingIcon:N,expanded:K,pauseWhenPageIsHidden:E,swipeDirections:s.swipeDirections})})):null}))});const b5t=({...s})=>{const{theme:t="system"}=G3t();return e.jsx(v5t,{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 _5t=f3e[" useId ".trim().toString()]||(()=>{}),w5t=0;function jm(s){const[t,r]=k.useState(_5t());return Gu(()=>{s||r(n=>n??String(w5t++))},[s]),s||(t?`radix-${t}`:"")}const j5t=["top","right","bottom","left"],AS=Math.min,x0=Math.max,Hhe=Math.round,XU=Math.floor,MS=s=>({x:s,y:s}),N5t={left:"right",right:"left",bottom:"top",top:"bottom"},k5t={start:"end",end:"start"};function tNe(s,t,r){return x0(s,AS(t,r))}function k2(s,t){return typeof s=="function"?s(t):s}function S2(s){return s.split("-")[0]}function f8(s){return s.split("-")[1]}function h5e(s){return s==="x"?"y":"x"}function m5e(s){return s==="y"?"height":"width"}function IS(s){return["top","bottom"].includes(S2(s))?"y":"x"}function f5e(s){return h5e(IS(s))}function S5t(s,t,r){r===void 0&&(r=!1);const n=f8(s),a=f5e(s),i=m5e(a);let l=a==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=Ghe(l)),[l,Ghe(l)]}function C5t(s){const t=Ghe(s);return[sNe(s),t,sNe(t)]}function sNe(s){return s.replace(/start|end/g,t=>k5t[t])}function T5t(s,t,r){const n=["left","right"],a=["right","left"],i=["top","bottom"],l=["bottom","top"];switch(s){case"top":case"bottom":return r?t?a:n:t?n:a;case"left":case"right":return t?i:l;default:return[]}}function E5t(s,t,r,n){const a=f8(s);let i=T5t(S2(s),r==="start",n);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(sNe)))),i}function Ghe(s){return s.replace(/left|right|bottom|top/g,t=>N5t[t])}function A5t(s){return{top:0,right:0,bottom:0,left:0,...s}}function fet(s){return typeof s!="number"?A5t(s):{top:s,right:s,bottom:s,left:s}}function Whe(s){const{x:t,y:r,width:n,height:a}=s;return{width:n,height:a,top:r,left:t,right:t+n,bottom:r+a,x:t,y:r}}function DOe(s,t,r){let{reference:n,floating:a}=s;const i=IS(t),l=f5e(t),o=m5e(l),c=S2(t),d=i==="y",u=n.x+n.width/2-a.width/2,m=n.y+n.height/2-a.height/2,f=n[o]/2-a[o]/2;let x;switch(c){case"top":x={x:u,y:n.y-a.height};break;case"bottom":x={x:u,y:n.y+n.height};break;case"right":x={x:n.x+n.width,y:m};break;case"left":x={x:n.x-a.width,y:m};break;default:x={x:n.x,y:n.y}}switch(f8(t)){case"start":x[l]-=f*(r&&d?-1:1);break;case"end":x[l]+=f*(r&&d?-1:1);break}return x}const M5t=async(s,t,r)=>{const{placement:n="bottom",strategy:a="absolute",middleware:i=[],platform:l}=r,o=i.filter(Boolean),c=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:s,floating:t,strategy:a}),{x:u,y:m}=DOe(d,n,c),f=n,x={},y=0;for(let _=0;_({name:"arrow",options:s,async fn(t){const{x:r,y:n,placement:a,rects:i,platform:l,elements:o,middlewareData:c}=t,{element:d,padding:u=0}=k2(s,t)||{};if(d==null)return{};const m=fet(u),f={x:r,y:n},x=f5e(a),y=m5e(x),_=await l.getDimensions(d),b=x==="y",j=b?"top":"left",N=b?"bottom":"right",C=b?"clientHeight":"clientWidth",A=i.reference[y]+i.reference[x]-f[x]-i.floating[y],E=f[x]-i.reference[x],D=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let R=D?D[C]:0;(!R||!await(l.isElement==null?void 0:l.isElement(D)))&&(R=o.floating[C]||i.floating[y]);const F=A/2-E/2,O=R/2-_[y]/2-1,B=AS(m[j],O),K=AS(m[N],O),Z=B,Q=R-_[y]-K,W=R/2-_[y]/2+F,te=tNe(Z,W,Q),ne=!c.arrow&&f8(a)!=null&&W!==te&&i.reference[y]/2-(WW<=0)){var K,Z;const W=(((K=i.flip)==null?void 0:K.index)||0)+1,te=R[W];if(te)return{data:{index:W,overflows:B},reset:{placement:te}};let ne=(Z=B.filter(ae=>ae.overflows[0]<=0).sort((ae,ue)=>ae.overflows[1]-ue.overflows[1])[0])==null?void 0:Z.placement;if(!ne)switch(x){case"bestFit":{var Q;const ae=(Q=B.filter(ue=>{if(D){const me=IS(ue.placement);return me===N||me==="y"}return!0}).map(ue=>[ue.placement,ue.overflows.filter(me=>me>0).reduce((me,de)=>me+de,0)]).sort((ue,me)=>ue[1]-me[1])[0])==null?void 0:Q[0];ae&&(ne=ae);break}case"initialPlacement":ne=o;break}if(a!==ne)return{reset:{placement:ne}}}return{}}}};function ROe(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function OOe(s){return j5t.some(t=>s[t]>=0)}const L5t=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:r}=t,{strategy:n="referenceHidden",...a}=k2(s,t);switch(n){case"referenceHidden":{const i=await g9(t,{...a,elementContext:"reference"}),l=ROe(i,r.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:OOe(l)}}}case"escaped":{const i=await g9(t,{...a,altBoundary:!0}),l=ROe(i,r.floating);return{data:{escapedOffsets:l,escaped:OOe(l)}}}default:return{}}}}};async function D5t(s,t){const{placement:r,platform:n,elements:a}=s,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),l=S2(r),o=f8(r),c=IS(r)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,m=k2(t,s);let{mainAxis:f,crossAxis:x,alignmentAxis:y}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:m.mainAxis||0,crossAxis:m.crossAxis||0,alignmentAxis:m.alignmentAxis};return o&&typeof y=="number"&&(x=o==="end"?y*-1:y),c?{x:x*u,y:f*d}:{x:f*d,y:x*u}}const R5t=function(s){return s===void 0&&(s=0),{name:"offset",options:s,async fn(t){var r,n;const{x:a,y:i,placement:l,middlewareData:o}=t,c=await D5t(t,s);return l===((r=o.offset)==null?void 0:r.placement)&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:l}}}}},O5t=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:r,y:n,placement:a}=t,{mainAxis:i=!0,crossAxis:l=!1,limiter:o={fn:b=>{let{x:j,y:N}=b;return{x:j,y:N}}},...c}=k2(s,t),d={x:r,y:n},u=await g9(t,c),m=IS(S2(a)),f=h5e(m);let x=d[f],y=d[m];if(i){const b=f==="y"?"top":"left",j=f==="y"?"bottom":"right",N=x+u[b],C=x-u[j];x=tNe(N,x,C)}if(l){const b=m==="y"?"top":"left",j=m==="y"?"bottom":"right",N=y+u[b],C=y-u[j];y=tNe(N,y,C)}const _=o.fn({...t,[f]:x,[m]:y});return{..._,data:{x:_.x-r,y:_.y-n,enabled:{[f]:i,[m]:l}}}}}},F5t=function(s){return s===void 0&&(s={}),{options:s,fn(t){const{x:r,y:n,placement:a,rects:i,middlewareData:l}=t,{offset:o=0,mainAxis:c=!0,crossAxis:d=!0}=k2(s,t),u={x:r,y:n},m=IS(a),f=h5e(m);let x=u[f],y=u[m];const _=k2(o,t),b=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(c){const C=f==="y"?"height":"width",A=i.reference[f]-i.floating[C]+b.mainAxis,E=i.reference[f]+i.reference[C]-b.mainAxis;xE&&(x=E)}if(d){var j,N;const C=f==="y"?"width":"height",A=["top","left"].includes(S2(a)),E=i.reference[m]-i.floating[C]+(A&&((j=l.offset)==null?void 0:j[m])||0)+(A?0:b.crossAxis),D=i.reference[m]+i.reference[C]+(A?0:((N=l.offset)==null?void 0:N[m])||0)-(A?b.crossAxis:0);yD&&(y=D)}return{[f]:x,[m]:y}}}},z5t=function(s){return s===void 0&&(s={}),{name:"size",options:s,async fn(t){var r,n;const{placement:a,rects:i,platform:l,elements:o}=t,{apply:c=()=>{},...d}=k2(s,t),u=await g9(t,d),m=S2(a),f=f8(a),x=IS(a)==="y",{width:y,height:_}=i.floating;let b,j;m==="top"||m==="bottom"?(b=m,j=f===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(j=m,b=f==="end"?"top":"bottom");const N=_-u.top-u.bottom,C=y-u.left-u.right,A=AS(_-u[b],N),E=AS(y-u[j],C),D=!t.middlewareData.shift;let R=A,F=E;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&(F=C),(n=t.middlewareData.shift)!=null&&n.enabled.y&&(R=N),D&&!f){const B=x0(u.left,0),K=x0(u.right,0),Z=x0(u.top,0),Q=x0(u.bottom,0);x?F=y-2*(B!==0||K!==0?B+K:x0(u.left,u.right)):R=_-2*(Z!==0||Q!==0?Z+Q:x0(u.top,u.bottom))}await c({...t,availableWidth:F,availableHeight:R});const O=await l.getDimensions(o.floating);return y!==O.width||_!==O.height?{reset:{rects:!0}}:{}}}};function wxe(){return typeof window<"u"}function p8(s){return pet(s)?(s.nodeName||"").toLowerCase():"#document"}function T0(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function X_(s){var t;return(t=(pet(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function pet(s){return wxe()?s instanceof Node||s instanceof T0(s).Node:!1}function R1(s){return wxe()?s instanceof Element||s instanceof T0(s).Element:!1}function F_(s){return wxe()?s instanceof HTMLElement||s instanceof T0(s).HTMLElement:!1}function FOe(s){return!wxe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof T0(s).ShadowRoot}function sB(s){const{overflow:t,overflowX:r,overflowY:n,display:a}=O1(s);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&!["inline","contents"].includes(a)}function B5t(s){return["table","td","th"].includes(p8(s))}function jxe(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function p5e(s){const t=x5e(),r=R1(s)?O1(s):s;return r.transform!=="none"||r.perspective!=="none"||(r.containerType?r.containerType!=="normal":!1)||!t&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!t&&(r.filter?r.filter!=="none":!1)||["transform","perspective","filter"].some(n=>(r.willChange||"").includes(n))||["paint","layout","strict","content"].some(n=>(r.contain||"").includes(n))}function $5t(s){let t=PS(s);for(;F_(t)&&!aL(t);){if(p5e(t))return t;if(jxe(t))return null;t=PS(t)}return null}function x5e(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function aL(s){return["html","body","#document"].includes(p8(s))}function O1(s){return T0(s).getComputedStyle(s)}function Nxe(s){return R1(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function PS(s){if(p8(s)==="html")return s;const t=s.assignedSlot||s.parentNode||FOe(s)&&s.host||X_(s);return FOe(t)?t.host:t}function xet(s){const t=PS(s);return aL(t)?s.ownerDocument?s.ownerDocument.body:s.body:F_(t)&&sB(t)?t:xet(t)}function y9(s,t,r){var n;t===void 0&&(t=[]),r===void 0&&(r=!0);const a=xet(s),i=a===((n=s.ownerDocument)==null?void 0:n.body),l=T0(a);if(i){const o=rNe(l);return t.concat(l,l.visualViewport||[],sB(a)?a:[],o&&r?y9(o):[])}return t.concat(a,y9(a,[],r))}function rNe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function get(s){const t=O1(s);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const a=F_(s),i=a?s.offsetWidth:r,l=a?s.offsetHeight:n,o=Hhe(r)!==i||Hhe(n)!==l;return o&&(r=i,n=l),{width:r,height:n,$:o}}function g5e(s){return R1(s)?s:s.contextElement}function fP(s){const t=g5e(s);if(!F_(t))return MS(1);const r=t.getBoundingClientRect(),{width:n,height:a,$:i}=get(t);let l=(i?Hhe(r.width):r.width)/n,o=(i?Hhe(r.height):r.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const U5t=MS(0);function yet(s){const t=T0(s);return!x5e()||!t.visualViewport?U5t:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function q5t(s,t,r){return t===void 0&&(t=!1),!r||t&&r!==T0(s)?!1:t}function pA(s,t,r,n){t===void 0&&(t=!1),r===void 0&&(r=!1);const a=s.getBoundingClientRect(),i=g5e(s);let l=MS(1);t&&(n?R1(n)&&(l=fP(n)):l=fP(s));const o=q5t(i,r,n)?yet(i):MS(0);let c=(a.left+o.x)/l.x,d=(a.top+o.y)/l.y,u=a.width/l.x,m=a.height/l.y;if(i){const f=T0(i),x=n&&R1(n)?T0(n):n;let y=f,_=rNe(y);for(;_&&n&&x!==y;){const b=fP(_),j=_.getBoundingClientRect(),N=O1(_),C=j.left+(_.clientLeft+parseFloat(N.paddingLeft))*b.x,A=j.top+(_.clientTop+parseFloat(N.paddingTop))*b.y;c*=b.x,d*=b.y,u*=b.x,m*=b.y,c+=C,d+=A,y=T0(_),_=rNe(y)}}return Whe({width:u,height:m,x:c,y:d})}function V5t(s){let{elements:t,rect:r,offsetParent:n,strategy:a}=s;const i=a==="fixed",l=X_(n),o=t?jxe(t.floating):!1;if(n===l||o&&i)return r;let c={scrollLeft:0,scrollTop:0},d=MS(1);const u=MS(0),m=F_(n);if((m||!m&&!i)&&((p8(n)!=="body"||sB(l))&&(c=Nxe(n)),F_(n))){const f=pA(n);d=fP(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+u.x,y:r.y*d.y-c.scrollTop*d.y+u.y}}function H5t(s){return Array.from(s.getClientRects())}function nNe(s,t){const r=Nxe(s).scrollLeft;return t?t.left+r:pA(X_(s)).left+r}function G5t(s){const t=X_(s),r=Nxe(s),n=s.ownerDocument.body,a=x0(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),i=x0(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let l=-r.scrollLeft+nNe(s);const o=-r.scrollTop;return O1(n).direction==="rtl"&&(l+=x0(t.clientWidth,n.clientWidth)-a),{width:a,height:i,x:l,y:o}}function W5t(s,t){const r=T0(s),n=X_(s),a=r.visualViewport;let i=n.clientWidth,l=n.clientHeight,o=0,c=0;if(a){i=a.width,l=a.height;const d=x5e();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function K5t(s,t){const r=pA(s,!0,t==="fixed"),n=r.top+s.clientTop,a=r.left+s.clientLeft,i=F_(s)?fP(s):MS(1),l=s.clientWidth*i.x,o=s.clientHeight*i.y,c=a*i.x,d=n*i.y;return{width:l,height:o,x:c,y:d}}function zOe(s,t,r){let n;if(t==="viewport")n=W5t(s,r);else if(t==="document")n=G5t(X_(s));else if(R1(t))n=K5t(t,r);else{const a=yet(s);n={...t,x:t.x-a.x,y:t.y-a.y}}return Whe(n)}function vet(s,t){const r=PS(s);return r===t||!R1(r)||aL(r)?!1:O1(r).position==="fixed"||vet(r,t)}function Y5t(s,t){const r=t.get(s);if(r)return r;let n=y9(s,[],!1).filter(o=>R1(o)&&p8(o)!=="body"),a=null;const i=O1(s).position==="fixed";let l=i?PS(s):s;for(;R1(l)&&!aL(l);){const o=O1(l),c=p5e(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||sB(l)&&!c&&vet(s,l))?n=n.filter(u=>u!==l):a=o,l=PS(l)}return t.set(s,n),n}function Z5t(s){let{element:t,boundary:r,rootBoundary:n,strategy:a}=s;const l=[...r==="clippingAncestors"?jxe(t)?[]:Y5t(t,this._c):[].concat(r),n],o=l[0],c=l.reduce((d,u)=>{const m=zOe(t,u,a);return d.top=x0(m.top,d.top),d.right=AS(m.right,d.right),d.bottom=AS(m.bottom,d.bottom),d.left=x0(m.left,d.left),d},zOe(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function X5t(s){const{width:t,height:r}=get(s);return{width:t,height:r}}function Q5t(s,t,r){const n=F_(t),a=X_(t),i=r==="fixed",l=pA(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=MS(0);if(n||!n&&!i)if((p8(t)!=="body"||sB(a))&&(o=Nxe(t)),n){const x=pA(t,!0,i,t);c.x=x.x+t.clientLeft,c.y=x.y+t.clientTop}else a&&(c.x=nNe(a));let d=0,u=0;if(a&&!n&&!i){const x=a.getBoundingClientRect();u=x.top+o.scrollTop,d=x.left+o.scrollLeft-nNe(a,x)}const m=l.left+o.scrollLeft-c.x-d,f=l.top+o.scrollTop-c.y-u;return{x:m,y:f,width:l.width,height:l.height}}function ybe(s){return O1(s).position==="static"}function BOe(s,t){if(!F_(s)||O1(s).position==="fixed")return null;if(t)return t(s);let r=s.offsetParent;return X_(s)===r&&(r=r.ownerDocument.body),r}function bet(s,t){const r=T0(s);if(jxe(s))return r;if(!F_(s)){let a=PS(s);for(;a&&!aL(a);){if(R1(a)&&!ybe(a))return a;a=PS(a)}return r}let n=BOe(s,t);for(;n&&B5t(n)&&ybe(n);)n=BOe(n,t);return n&&aL(n)&&ybe(n)&&!p5e(n)?r:n||$5t(s)||r}const J5t=async function(s){const t=this.getOffsetParent||bet,r=this.getDimensions,n=await r(s.floating);return{reference:Q5t(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function eTt(s){return O1(s).direction==="rtl"}const tTt={convertOffsetParentRelativeRectToViewportRelativeRect:V5t,getDocumentElement:X_,getClippingRect:Z5t,getOffsetParent:bet,getElementRects:J5t,getClientRects:H5t,getDimensions:X5t,getScale:fP,isElement:R1,isRTL:eTt};function sTt(s,t){let r=null,n;const a=X_(s);function i(){var o;clearTimeout(n),(o=r)==null||o.disconnect(),r=null}function l(o,c){o===void 0&&(o=!1),c===void 0&&(c=1),i();const{left:d,top:u,width:m,height:f}=s.getBoundingClientRect();if(o||t(),!m||!f)return;const x=XU(u),y=XU(a.clientWidth-(d+m)),_=XU(a.clientHeight-(u+f)),b=XU(d),N={rootMargin:-x+"px "+-y+"px "+-_+"px "+-b+"px",threshold:x0(0,AS(1,c))||1};let C=!0;function A(E){const D=E[0].intersectionRatio;if(D!==c){if(!C)return l();D?l(!1,D):n=setTimeout(()=>{l(!1,1e-7)},1e3)}C=!1}try{r=new IntersectionObserver(A,{...N,root:a.ownerDocument})}catch{r=new IntersectionObserver(A,N)}r.observe(s)}return l(!0),i}function rTt(s,t,r,n){n===void 0&&(n={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:c=!1}=n,d=g5e(s),u=a||i?[...d?y9(d):[],...y9(t)]:[];u.forEach(j=>{a&&j.addEventListener("scroll",r,{passive:!0}),i&&j.addEventListener("resize",r)});const m=d&&o?sTt(d,r):null;let f=-1,x=null;l&&(x=new ResizeObserver(j=>{let[N]=j;N&&N.target===d&&x&&(x.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var C;(C=x)==null||C.observe(t)})),r()}),d&&!c&&x.observe(d),x.observe(t));let y,_=c?pA(s):null;c&&b();function b(){const j=pA(s);_&&(j.x!==_.x||j.y!==_.y||j.width!==_.width||j.height!==_.height)&&r(),_=j,y=requestAnimationFrame(b)}return r(),()=>{var j;u.forEach(N=>{a&&N.removeEventListener("scroll",r),i&&N.removeEventListener("resize",r)}),m==null||m(),(j=x)==null||j.disconnect(),x=null,c&&cancelAnimationFrame(y)}}const nTt=R5t,aTt=O5t,iTt=P5t,oTt=z5t,lTt=L5t,$Oe=I5t,cTt=F5t,dTt=(s,t,r)=>{const n=new Map,a={platform:tTt,...r},i={...a.platform,_c:n};return M5t(s,t,{...a,platform:i})};var Mue=typeof document<"u"?k.useLayoutEffect:k.useEffect;function Khe(s,t){if(s===t)return!0;if(typeof s!=typeof t)return!1;if(typeof s=="function"&&s.toString()===t.toString())return!0;let r,n,a;if(s&&t&&typeof s=="object"){if(Array.isArray(s)){if(r=s.length,r!==t.length)return!1;for(n=r;n--!==0;)if(!Khe(s[n],t[n]))return!1;return!0}if(a=Object.keys(s),r=a.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!{}.hasOwnProperty.call(t,a[n]))return!1;for(n=r;n--!==0;){const i=a[n];if(!(i==="_owner"&&s.$$typeof)&&!Khe(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function _et(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function UOe(s,t){const r=_et(s);return Math.round(t*r)/r}function vbe(s){const t=k.useRef(s);return Mue(()=>{t.current=s}),t}function uTt(s){s===void 0&&(s={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[u,m]=k.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,x]=k.useState(n);Khe(f,n)||x(n);const[y,_]=k.useState(null),[b,j]=k.useState(null),N=k.useCallback(ue=>{ue!==D.current&&(D.current=ue,_(ue))},[]),C=k.useCallback(ue=>{ue!==R.current&&(R.current=ue,j(ue))},[]),A=i||y,E=l||b,D=k.useRef(null),R=k.useRef(null),F=k.useRef(u),O=c!=null,B=vbe(c),K=vbe(a),Z=vbe(d),Q=k.useCallback(()=>{if(!D.current||!R.current)return;const ue={placement:t,strategy:r,middleware:f};K.current&&(ue.platform=K.current),dTt(D.current,R.current,ue).then(me=>{const de={...me,isPositioned:Z.current!==!1};W.current&&!Khe(F.current,de)&&(F.current=de,vx.flushSync(()=>{m(de)}))})},[f,t,r,K,Z]);Mue(()=>{d===!1&&F.current.isPositioned&&(F.current.isPositioned=!1,m(ue=>({...ue,isPositioned:!1})))},[d]);const W=k.useRef(!1);Mue(()=>(W.current=!0,()=>{W.current=!1}),[]),Mue(()=>{if(A&&(D.current=A),E&&(R.current=E),A&&E){if(B.current)return B.current(A,E,Q);Q()}},[A,E,Q,B,O]);const te=k.useMemo(()=>({reference:D,floating:R,setReference:N,setFloating:C}),[N,C]),ne=k.useMemo(()=>({reference:A,floating:E}),[A,E]),ae=k.useMemo(()=>{const ue={position:r,left:0,top:0};if(!ne.floating)return ue;const me=UOe(ne.floating,u.x),de=UOe(ne.floating,u.y);return o?{...ue,transform:"translate("+me+"px, "+de+"px)",..._et(ne.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:me,top:de}},[r,o,ne.floating,u.x,u.y]);return k.useMemo(()=>({...u,update:Q,refs:te,elements:ne,floatingStyles:ae}),[u,Q,te,ne,ae])}const hTt=s=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:s,fn(r){const{element:n,padding:a}=typeof s=="function"?s(r):s;return n&&t(n)?n.current!=null?$Oe({element:n.current,padding:a}).fn(r):{}:n?$Oe({element:n,padding:a}).fn(r):{}}}},mTt=(s,t)=>({...nTt(s),options:[s,t]}),fTt=(s,t)=>({...aTt(s),options:[s,t]}),pTt=(s,t)=>({...cTt(s),options:[s,t]}),xTt=(s,t)=>({...iTt(s),options:[s,t]}),gTt=(s,t)=>({...oTt(s),options:[s,t]}),yTt=(s,t)=>({...lTt(s),options:[s,t]}),vTt=(s,t)=>({...hTt(s),options:[s,t]});var bTt="Arrow",wet=k.forwardRef((s,t)=>{const{children:r,width:n=10,height:a=5,...i}=s;return e.jsx(Yn.svg,{...i,ref:t,width:n,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:s.asChild?r:e.jsx("polygon",{points:"0,0 30,0 15,10"})})});wet.displayName=bTt;var _Tt=wet;function rB(s){const[t,r]=k.useState(void 0);return Gu(()=>{if(s){r({width:s.offsetWidth,height:s.offsetHeight});const n=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let l,o;if("borderBoxSize"in i){const c=i.borderBoxSize,d=Array.isArray(c)?c[0]:c;l=d.inlineSize,o=d.blockSize}else l=s.offsetWidth,o=s.offsetHeight;r({width:l,height:o})});return n.observe(s,{box:"border-box"}),()=>n.unobserve(s)}else r(void 0)},[s]),t}var y5e="Popper",[jet,Q_]=bu(y5e),[wTt,Net]=jet(y5e),ket=s=>{const{__scopePopper:t,children:r}=s,[n,a]=k.useState(null);return e.jsx(wTt,{scope:t,anchor:n,onAnchorChange:a,children:r})};ket.displayName=y5e;var Cet="PopperAnchor",Tet=k.forwardRef((s,t)=>{const{__scopePopper:r,virtualRef:n,...a}=s,i=Net(Cet,r),l=k.useRef(null),o=_i(t,l);return k.useEffect(()=>{i.onAnchorChange((n==null?void 0:n.current)||l.current)}),n?null:e.jsx(Yn.div,{...a,ref:o})});Tet.displayName=Cet;var v5e="PopperContent",[jTt,NTt]=jet(v5e),Eet=k.forwardRef((s,t)=>{var Ie,ze,Ve,Le,$e,ve;const{__scopePopper:r,side:n="bottom",sideOffset:a=0,align:i="center",alignOffset:l=0,arrowPadding:o=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:m="partial",hideWhenDetached:f=!1,updatePositionStrategy:x="optimized",onPlaced:y,..._}=s,b=Net(v5e,r),[j,N]=k.useState(null),C=_i(t,Qe=>N(Qe)),[A,E]=k.useState(null),D=rB(A),R=(D==null?void 0:D.width)??0,F=(D==null?void 0:D.height)??0,O=n+(i!=="center"?"-"+i:""),B=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},K=Array.isArray(d)?d:[d],Z=K.length>0,Q={padding:B,boundary:K.filter(STt),altBoundary:Z},{refs:W,floatingStyles:te,placement:ne,isPositioned:ae,middlewareData:ue}=uTt({strategy:"fixed",placement:O,whileElementsMounted:(...Qe)=>rTt(...Qe,{animationFrame:x==="always"}),elements:{reference:b.anchor},middleware:[mTt({mainAxis:a+F,alignmentAxis:l}),c&&fTt({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?pTt():void 0,...Q}),c&&xTt({...Q}),gTt({...Q,apply:({elements:Qe,rects:we,availableWidth:nt,availableHeight:Se})=>{const{width:Ge,height:We}=we.reference,Ce=Qe.floating.style;Ce.setProperty("--radix-popper-available-width",`${nt}px`),Ce.setProperty("--radix-popper-available-height",`${Se}px`),Ce.setProperty("--radix-popper-anchor-width",`${Ge}px`),Ce.setProperty("--radix-popper-anchor-height",`${We}px`)}}),A&&vTt({element:A,padding:o}),CTt({arrowWidth:R,arrowHeight:F}),f&&yTt({strategy:"referenceHidden",...Q})]}),[me,de]=Iet(ne),fe=$u(y);Gu(()=>{ae&&(fe==null||fe())},[ae,fe]);const je=(Ie=ue.arrow)==null?void 0:Ie.x,xe=(ze=ue.arrow)==null?void 0:ze.y,Ee=((Ve=ue.arrow)==null?void 0:Ve.centerOffset)!==0,[Me,Oe]=k.useState();return Gu(()=>{j&&Oe(window.getComputedStyle(j).zIndex)},[j]),e.jsx("div",{ref:W.setFloating,"data-radix-popper-content-wrapper":"",style:{...te,transform:ae?te.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Me,"--radix-popper-transform-origin":[(Le=ue.transformOrigin)==null?void 0:Le.x,($e=ue.transformOrigin)==null?void 0:$e.y].join(" "),...((ve=ue.hide)==null?void 0:ve.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(jTt,{scope:r,placedSide:me,onArrowChange:E,arrowX:je,arrowY:xe,shouldHideArrow:Ee,children:e.jsx(Yn.div,{"data-side":me,"data-align":de,..._,ref:C,style:{..._.style,animation:ae?void 0:"none"}})})})});Eet.displayName=v5e;var Aet="PopperArrow",kTt={top:"bottom",right:"left",bottom:"top",left:"right"},Met=k.forwardRef(function(t,r){const{__scopePopper:n,...a}=t,i=NTt(Aet,n),l=kTt[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(_Tt,{...a,ref:r,style:{...a.style,display:"block"}})})});Met.displayName=Aet;function STt(s){return s!==null}var CTt=s=>({name:"transformOrigin",options:s,fn(t){var b,j,N;const{placement:r,rects:n,middlewareData:a}=t,l=((b=a.arrow)==null?void 0:b.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=Iet(r),m={start:"0%",center:"50%",end:"100%"}[u],f=(((j=a.arrow)==null?void 0:j.x)??0)+o/2,x=(((N=a.arrow)==null?void 0:N.y)??0)+c/2;let y="",_="";return d==="bottom"?(y=l?m:`${f}px`,_=`${-c}px`):d==="top"?(y=l?m:`${f}px`,_=`${n.floating.height+c}px`):d==="right"?(y=`${-c}px`,_=l?m:`${x}px`):d==="left"&&(y=`${n.floating.width+c}px`,_=l?m:`${x}px`),{data:{x:y,y:_}}}});function Iet(s){const[t,r="center"]=s.split("-");return[t,r]}var nB=ket,x8=Tet,aB=Eet,iB=Met,[kxe,xnr]=bu("Tooltip",[Q_]),Sxe=Q_(),Pet="TooltipProvider",TTt=700,aNe="tooltip.open",[ETt,b5e]=kxe(Pet),Let=s=>{const{__scopeTooltip:t,delayDuration:r=TTt,skipDelayDuration:n=300,disableHoverableContent:a=!1,children:i}=s,l=k.useRef(!0),o=k.useRef(!1),c=k.useRef(0);return k.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(ETt,{scope:t,isOpenDelayedRef:l,delayDuration:r,onOpen:k.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:k.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,n)},[n]),isPointerInTransitRef:o,onPointerInTransitChange:k.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};Let.displayName=Pet;var v9="Tooltip",[ATt,Cxe]=kxe(v9),Det=s=>{const{__scopeTooltip:t,children:r,open:n,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=b5e(v9,s.__scopeTooltip),d=Sxe(t),[u,m]=k.useState(null),f=jm(),x=k.useRef(0),y=l??c.disableHoverableContent,_=o??c.delayDuration,b=k.useRef(!1),[j,N]=df({prop:n,defaultProp:a??!1,onChange:R=>{R?(c.onOpen(),document.dispatchEvent(new CustomEvent(aNe))):c.onClose(),i==null||i(R)},caller:v9}),C=k.useMemo(()=>j?b.current?"delayed-open":"instant-open":"closed",[j]),A=k.useCallback(()=>{window.clearTimeout(x.current),x.current=0,b.current=!1,N(!0)},[N]),E=k.useCallback(()=>{window.clearTimeout(x.current),x.current=0,N(!1)},[N]),D=k.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{b.current=!0,N(!0),x.current=0},_)},[_,N]);return k.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),e.jsx(nB,{...d,children:e.jsx(ATt,{scope:t,contentId:f,open:j,stateAttribute:C,trigger:u,onTriggerChange:m,onTriggerEnter:k.useCallback(()=>{c.isOpenDelayedRef.current?D():A()},[c.isOpenDelayedRef,D,A]),onTriggerLeave:k.useCallback(()=>{y?E():(window.clearTimeout(x.current),x.current=0)},[E,y]),onOpen:A,onClose:E,disableHoverableContent:y,children:r})})};Det.displayName=v9;var iNe="TooltipTrigger",Ret=k.forwardRef((s,t)=>{const{__scopeTooltip:r,...n}=s,a=Cxe(iNe,r),i=b5e(iNe,r),l=Sxe(r),o=k.useRef(null),c=_i(t,o,a.onTriggerChange),d=k.useRef(!1),u=k.useRef(!1),m=k.useCallback(()=>d.current=!1,[]);return k.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),e.jsx(x8,{asChild:!0,...l,children:e.jsx(Yn.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...n,ref:c,onPointerMove:dn(s.onPointerMove,f=>{f.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:dn(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:dn(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:dn(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:dn(s.onBlur,a.onClose),onClick:dn(s.onClick,a.onClose)})})});Ret.displayName=iNe;var MTt="TooltipPortal",[gnr,ITt]=kxe(MTt,{forceMount:void 0}),iL="TooltipContent",Oet=k.forwardRef((s,t)=>{const r=ITt(iL,s.__scopeTooltip),{forceMount:n=r.forceMount,side:a="top",...i}=s,l=Cxe(iL,s.__scopeTooltip);return e.jsx(yh,{present:n||l.open,children:l.disableHoverableContent?e.jsx(Fet,{side:a,...i,ref:t}):e.jsx(PTt,{side:a,...i,ref:t})})}),PTt=k.forwardRef((s,t)=>{const r=Cxe(iL,s.__scopeTooltip),n=b5e(iL,s.__scopeTooltip),a=k.useRef(null),i=_i(t,a),[l,o]=k.useState(null),{trigger:c,onClose:d}=r,u=a.current,{onPointerInTransitChange:m}=n,f=k.useCallback(()=>{o(null),m(!1)},[m]),x=k.useCallback((y,_)=>{const b=y.currentTarget,j={x:y.clientX,y:y.clientY},N=FTt(j,b.getBoundingClientRect()),C=zTt(j,N),A=BTt(_.getBoundingClientRect()),E=UTt([...C,...A]);o(E),m(!0)},[m]);return k.useEffect(()=>()=>f(),[f]),k.useEffect(()=>{if(c&&u){const y=b=>x(b,u),_=b=>x(b,c);return c.addEventListener("pointerleave",y),u.addEventListener("pointerleave",_),()=>{c.removeEventListener("pointerleave",y),u.removeEventListener("pointerleave",_)}}},[c,u,x,f]),k.useEffect(()=>{if(l){const y=_=>{const b=_.target,j={x:_.clientX,y:_.clientY},N=(c==null?void 0:c.contains(b))||(u==null?void 0:u.contains(b)),C=!$Tt(j,l);N?f():C&&(f(),d())};return document.addEventListener("pointermove",y),()=>document.removeEventListener("pointermove",y)}},[c,u,l,d,f]),e.jsx(Fet,{...s,ref:i})}),[LTt,DTt]=kxe(v9,{isInside:!1}),RTt=AJe("TooltipContent"),Fet=k.forwardRef((s,t)=>{const{__scopeTooltip:r,children:n,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=Cxe(iL,r),d=Sxe(r),{onClose:u}=c;return k.useEffect(()=>(document.addEventListener(aNe,u),()=>document.removeEventListener(aNe,u)),[u]),k.useEffect(()=>{if(c.trigger){const m=f=>{const x=f.target;x!=null&&x.contains(c.trigger)&&u()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[c.trigger,u]),e.jsx(WS,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:m=>m.preventDefault(),onDismiss:u,children:e.jsxs(aB,{"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(RTt,{children:n}),e.jsx(LTt,{scope:r,isInside:!0,children:e.jsx(zCt,{id:c.contentId,role:"tooltip",children:a||n})})]})})});Oet.displayName=iL;var zet="TooltipArrow",OTt=k.forwardRef((s,t)=>{const{__scopeTooltip:r,...n}=s,a=Sxe(r);return DTt(zet,r).isInside?null:e.jsx(iB,{...a,...n,ref:t})});OTt.displayName=zet;function FTt(s,t){const r=Math.abs(t.top-s.y),n=Math.abs(t.bottom-s.y),a=Math.abs(t.right-s.x),i=Math.abs(t.left-s.x);switch(Math.min(r,n,a,i)){case i:return"left";case a:return"right";case r:return"top";case n:return"bottom";default:throw new Error("unreachable")}}function zTt(s,t,r=5){const n=[];switch(t){case"top":n.push({x:s.x-r,y:s.y+r},{x:s.x+r,y:s.y+r});break;case"bottom":n.push({x:s.x-r,y:s.y-r},{x:s.x+r,y:s.y-r});break;case"left":n.push({x:s.x+r,y:s.y-r},{x:s.x+r,y:s.y+r});break;case"right":n.push({x:s.x-r,y:s.y-r},{x:s.x-r,y:s.y+r});break}return n}function BTt(s){const{top:t,right:r,bottom:n,left:a}=s;return[{x:a,y:t},{x:r,y:t},{x:r,y:n},{x:a,y:n}]}function $Tt(s,t){const{x:r,y:n}=s;let a=!1;for(let i=0,l=t.length-1;in!=f>n&&r<(m-d)*(n-u)/(f-u)+d&&(a=!a)}return a}function UTt(s){const t=s.slice();return t.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),qTt(t)}function qTt(s){if(s.length<=1)return s.slice();const t=[];for(let n=0;n=2;){const i=t[t.length-1],l=t[t.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))t.pop();else break}t.push(a)}t.pop();const r=[];for(let n=s.length-1;n>=0;n--){const a=s[n];for(;r.length>=2;){const i=r[r.length-1],l=r[r.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))r.pop();else break}r.push(a)}return r.pop(),t.length===1&&r.length===1&&t[0].x===r[0].x&&t[0].y===r[0].y?t:t.concat(r)}var VTt=Let,HTt=Det,GTt=Ret,Bet=Oet;const J_=VTt,Oc=HTt,Fc=GTt,Sc=k.forwardRef(({className:s,sideOffset:t=4,...r},n)=>e.jsx(Bet,{ref:n,sideOffset:t,className:zt("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r}));Sc.displayName=Bet.displayName;var g8=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(){}},xA=typeof window>"u"||"Deno"in globalThis;function xx(){}function WTt(s,t){return typeof s=="function"?s(t):s}function oNe(s){return typeof s=="number"&&s>=0&&s!==1/0}function $et(s,t){return Math.max(s+(t||0)-Date.now(),0)}function fS(s,t){return typeof s=="function"?s(t):s}function Iy(s,t){return typeof s=="function"?s(t):s}function qOe(s,t){const{type:r="all",exact:n,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(n){if(t.queryHash!==_5e(l,t.options))return!1}else if(!b9(t.queryKey,l))return!1}if(r!=="all"){const c=t.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function VOe(s,t){const{exact:r,status:n,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(r){if(gA(t.options.mutationKey)!==gA(i))return!1}else if(!b9(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||a&&!a(t))}function _5e(s,t){return((t==null?void 0:t.queryKeyHashFn)||gA)(s)}function gA(s){return JSON.stringify(s,(t,r)=>lNe(r)?Object.keys(r).sort().reduce((n,a)=>(n[a]=r[a],n),{}):r)}function b9(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(r=>b9(s[r],t[r])):!1}function Uet(s,t){if(s===t)return s;const r=HOe(s)&&HOe(t);if(r||lNe(s)&&lNe(t)){const n=r?s:Object.keys(s),a=n.length,i=r?t:Object.keys(t),l=i.length,o=r?[]:{},c=new Set(n);let d=0;for(let u=0;u{setTimeout(t,s)})}function cNe(s,t,r){return typeof r.structuralSharing=="function"?r.structuralSharing(s,t):r.structuralSharing!==!1?Uet(s,t):t}function YTt(s,t,r=0){const n=[...s,t];return r&&n.length>r?n.slice(1):n}function ZTt(s,t,r=0){const n=[t,...s];return r&&n.length>r?n.slice(0,-1):n}var w5e=Symbol();function qet(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===w5e?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function Vet(s,t){return typeof s=="function"?s(...t):!!s}var uE,Nk,BP,aXe,XTt=(aXe=class extends g8{constructor(){super();Mi(this,uE);Mi(this,Nk);Mi(this,BP);Da(this,BP,t=>{if(!xA&&window.addEventListener){const r=()=>t();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Vs(this,Nk)||this.setEventListener(Vs(this,BP))}onUnsubscribe(){var t;this.hasListeners()||((t=Vs(this,Nk))==null||t.call(this),Da(this,Nk,void 0))}setEventListener(t){var r;Da(this,BP,t),(r=Vs(this,Nk))==null||r.call(this),Da(this,Nk,t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(t){Vs(this,uE)!==t&&(Da(this,uE,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(r=>{r(t)})}isFocused(){var t;return typeof Vs(this,uE)=="boolean"?Vs(this,uE):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},uE=new WeakMap,Nk=new WeakMap,BP=new WeakMap,aXe),j5e=new XTt,$P,kk,UP,iXe,QTt=(iXe=class extends g8{constructor(){super();Mi(this,$P,!0);Mi(this,kk);Mi(this,UP);Da(this,UP,t=>{if(!xA&&window.addEventListener){const r=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",n)}}})}onSubscribe(){Vs(this,kk)||this.setEventListener(Vs(this,UP))}onUnsubscribe(){var t;this.hasListeners()||((t=Vs(this,kk))==null||t.call(this),Da(this,kk,void 0))}setEventListener(t){var r;Da(this,UP,t),(r=Vs(this,kk))==null||r.call(this),Da(this,kk,t(this.setOnline.bind(this)))}setOnline(t){Vs(this,$P)!==t&&(Da(this,$P,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return Vs(this,$P)}},$P=new WeakMap,kk=new WeakMap,UP=new WeakMap,iXe),Zhe=new QTt;function dNe(){let s,t;const r=new Promise((a,i)=>{s=a,t=i});r.status="pending",r.catch(()=>{});function n(a){Object.assign(r,a),delete r.resolve,delete r.reject}return r.resolve=a=>{n({status:"fulfilled",value:a}),s(a)},r.reject=a=>{n({status:"rejected",reason:a}),t(a)},r}function JTt(s){return Math.min(1e3*2**s,3e4)}function Het(s){return(s??"online")==="online"?Zhe.isOnline():!0}var Get=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function bbe(s){return s instanceof Get}function Wet(s){let t=!1,r=0,n=!1,a;const i=dNe(),l=_=>{var b;n||(f(new Get(_)),(b=s.abort)==null||b.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>j5e.isFocused()&&(s.networkMode==="always"||Zhe.isOnline())&&s.canRun(),u=()=>Het(s.networkMode)&&s.canRun(),m=_=>{var b;n||(n=!0,(b=s.onSuccess)==null||b.call(s,_),a==null||a(),i.resolve(_))},f=_=>{var b;n||(n=!0,(b=s.onError)==null||b.call(s,_),a==null||a(),i.reject(_))},x=()=>new Promise(_=>{var b;a=j=>{(n||d())&&_(j)},(b=s.onPause)==null||b.call(s)}).then(()=>{var _;a=void 0,n||(_=s.onContinue)==null||_.call(s)}),y=()=>{if(n)return;let _;const b=r===0?s.initialPromise:void 0;try{_=b??s.fn()}catch(j){_=Promise.reject(j)}Promise.resolve(_).then(m).catch(j=>{var D;if(n)return;const N=s.retry??(xA?0:3),C=s.retryDelay??JTt,A=typeof C=="function"?C(r,j):C,E=N===!0||typeof N=="number"&&rd()?void 0:x()).then(()=>{t?f(j):y()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?y():x().then(y),i)}}var eEt=s=>setTimeout(s,0);function tEt(){let s=[],t=0,r=o=>{o()},n=o=>{o()},a=eEt;const i=o=>{t?s.push(o):a(()=>{r(o)})},l=()=>{const o=s;s=[],o.length&&a(()=>{n(()=>{o.forEach(c=>{r(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||l()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{r=o},setBatchNotifyFunction:o=>{n=o},setScheduler:o=>{a=o}}}var cm=tEt(),hE,oXe,Ket=(oXe=class{constructor(){Mi(this,hE)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),oNe(this.gcTime)&&Da(this,hE,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(xA?1/0:5*60*1e3))}clearGcTimeout(){Vs(this,hE)&&(clearTimeout(Vs(this,hE)),Da(this,hE,void 0))}},hE=new WeakMap,oXe),qP,mE,My,fE,bp,Hz,pE,i1,Nj,lXe,sEt=(lXe=class extends Ket{constructor(t){super();Mi(this,i1);Mi(this,qP);Mi(this,mE);Mi(this,My);Mi(this,fE);Mi(this,bp);Mi(this,Hz);Mi(this,pE);Da(this,pE,!1),Da(this,Hz,t.defaultOptions),this.setOptions(t.options),this.observers=[],Da(this,fE,t.client),Da(this,My,Vs(this,fE).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Da(this,qP,rEt(this.options)),this.state=t.state??Vs(this,qP),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=Vs(this,bp))==null?void 0:t.promise}setOptions(t){this.options={...Vs(this,Hz),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Vs(this,My).remove(this)}setData(t,r){const n=cNe(this.state.data,t,this.options);return Lo(this,i1,Nj).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(t,r){Lo(this,i1,Nj).call(this,{type:"setState",state:t,setStateOptions:r})}cancel(t){var n,a;const r=(n=Vs(this,bp))==null?void 0:n.promise;return(a=Vs(this,bp))==null||a.cancel(t),r?r.then(xx).catch(xx):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Vs(this,qP))}isActive(){return this.observers.some(t=>Iy(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===w5e||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>fS(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:!$et(this.state.dataUpdatedAt,t)}onFocus(){var r;const t=this.observers.find(n=>n.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(r=Vs(this,bp))==null||r.continue()}onOnline(){var r;const t=this.observers.find(n=>n.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(r=Vs(this,bp))==null||r.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Vs(this,My).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(r=>r!==t),this.observers.length||(Vs(this,bp)&&(Vs(this,pE)?Vs(this,bp).cancel({revert:!0}):Vs(this,bp).cancelRetry()),this.scheduleGc()),Vs(this,My).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Lo(this,i1,Nj).call(this,{type:"invalidate"})}fetch(t,r){var d,u,m;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Vs(this,bp))return Vs(this,bp).continueRetry(),Vs(this,bp).promise}if(t&&this.setOptions(t),!this.options.queryFn){const f=this.observers.find(x=>x.options.queryFn);f&&this.setOptions(f.options)}const n=new AbortController,a=f=>{Object.defineProperty(f,"signal",{enumerable:!0,get:()=>(Da(this,pE,!0),n.signal)})},i=()=>{const f=qet(this.options,r),y=(()=>{const _={client:Vs(this,fE),queryKey:this.queryKey,meta:this.meta};return a(_),_})();return Da(this,pE,!1),this.options.persister?this.options.persister(f,y,this):f(y)},o=(()=>{const f={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Vs(this,fE),state:this.state,fetchFn:i};return a(f),f})();(d=this.options.behavior)==null||d.onFetch(o,this),Da(this,mE,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Lo(this,i1,Nj).call(this,{type:"fetch",meta:(m=o.fetchOptions)==null?void 0:m.meta});const c=f=>{var x,y,_,b;bbe(f)&&f.silent||Lo(this,i1,Nj).call(this,{type:"error",error:f}),bbe(f)||((y=(x=Vs(this,My).config).onError)==null||y.call(x,f,this),(b=(_=Vs(this,My).config).onSettled)==null||b.call(_,this.state.data,f,this)),this.scheduleGc()};return Da(this,bp,Wet({initialPromise:r==null?void 0:r.initialPromise,fn:o.fetchFn,abort:n.abort.bind(n),onSuccess:f=>{var x,y,_,b;if(f===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(f)}catch(j){c(j);return}(y=(x=Vs(this,My).config).onSuccess)==null||y.call(x,f,this),(b=(_=Vs(this,My).config).onSettled)==null||b.call(_,f,this.state.error,this),this.scheduleGc()},onError:c,onFail:(f,x)=>{Lo(this,i1,Nj).call(this,{type:"failed",failureCount:f,error:x})},onPause:()=>{Lo(this,i1,Nj).call(this,{type:"pause"})},onContinue:()=>{Lo(this,i1,Nj).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),Vs(this,bp).start()}},qP=new WeakMap,mE=new WeakMap,My=new WeakMap,fE=new WeakMap,bp=new WeakMap,Hz=new WeakMap,pE=new WeakMap,i1=new WeakSet,Nj=function(t){const r=n=>{switch(t.type){case"failed":return{...n,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Yet(n.data,this.options),fetchMeta:t.meta??null};case"success":return Da(this,mE,void 0),{...n,data:t.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const a=t.error;return bbe(a)&&a.revert&&Vs(this,mE)?{...Vs(this,mE),fetchStatus:"idle"}:{...n,error:a,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=r(this.state),cm.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Vs(this,My).notify({query:this,type:"updated",action:t})})},lXe);function Yet(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Het(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function rEt(s){const t=typeof s.initialData=="function"?s.initialData():s.initialData,r=t!==void 0,n=r?typeof s.initialDataUpdatedAt=="function"?s.initialDataUpdatedAt():s.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:r?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var Xb,cXe,nEt=(cXe=class extends g8{constructor(t={}){super();Mi(this,Xb);this.config=t,Da(this,Xb,new Map)}build(t,r,n){const a=r.queryKey,i=r.queryHash??_5e(a,r);let l=this.get(i);return l||(l=new sEt({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(r),state:n,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){Vs(this,Xb).has(t.queryHash)||(Vs(this,Xb).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const r=Vs(this,Xb).get(t.queryHash);r&&(t.destroy(),r===t&&Vs(this,Xb).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){cm.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Vs(this,Xb).get(t)}getAll(){return[...Vs(this,Xb).values()]}find(t){const r={exact:!0,...t};return this.getAll().find(n=>qOe(r,n))}findAll(t={}){const r=this.getAll();return Object.keys(t).length>0?r.filter(n=>qOe(t,n)):r}notify(t){cm.batch(()=>{this.listeners.forEach(r=>{r(t)})})}onFocus(){cm.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){cm.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Xb=new WeakMap,cXe),Qb,mx,xE,Jb,HN,dXe,aEt=(dXe=class extends Ket{constructor(t){super();Mi(this,Jb);Mi(this,Qb);Mi(this,mx);Mi(this,xE);this.mutationId=t.mutationId,Da(this,mx,t.mutationCache),Da(this,Qb,[]),this.state=t.state||Zet(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Vs(this,Qb).includes(t)||(Vs(this,Qb).push(t),this.clearGcTimeout(),Vs(this,mx).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Da(this,Qb,Vs(this,Qb).filter(r=>r!==t)),this.scheduleGc(),Vs(this,mx).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Vs(this,Qb).length||(this.state.status==="pending"?this.scheduleGc():Vs(this,mx).remove(this))}continue(){var t;return((t=Vs(this,xE))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,m,f,x,y,_,b,j,N,C,A,E,D,R,F;const r=()=>{Lo(this,Jb,HN).call(this,{type:"continue"})};Da(this,xE,Wet({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,B)=>{Lo(this,Jb,HN).call(this,{type:"failed",failureCount:O,error:B})},onPause:()=>{Lo(this,Jb,HN).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Vs(this,mx).canRun(this)}));const n=this.state.status==="pending",a=!Vs(this,xE).canStart();try{if(n)r();else{Lo(this,Jb,HN).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=Vs(this,mx).config).onMutate)==null?void 0:l.call(i,t,this));const B=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));B!==this.state.context&&Lo(this,Jb,HN).call(this,{type:"pending",context:B,variables:t,isPaused:a})}const O=await Vs(this,xE).start();return await((u=(d=Vs(this,mx).config).onSuccess)==null?void 0:u.call(d,O,t,this.state.context,this)),await((f=(m=this.options).onSuccess)==null?void 0:f.call(m,O,t,this.state.context)),await((y=(x=Vs(this,mx).config).onSettled)==null?void 0:y.call(x,O,null,this.state.variables,this.state.context,this)),await((b=(_=this.options).onSettled)==null?void 0:b.call(_,O,null,t,this.state.context)),Lo(this,Jb,HN).call(this,{type:"success",data:O}),O}catch(O){try{throw await((N=(j=Vs(this,mx).config).onError)==null?void 0:N.call(j,O,t,this.state.context,this)),await((A=(C=this.options).onError)==null?void 0:A.call(C,O,t,this.state.context)),await((D=(E=Vs(this,mx).config).onSettled)==null?void 0:D.call(E,void 0,O,this.state.variables,this.state.context,this)),await((F=(R=this.options).onSettled)==null?void 0:F.call(R,void 0,O,t,this.state.context)),O}finally{Lo(this,Jb,HN).call(this,{type:"error",error:O})}}finally{Vs(this,mx).runNext(this)}}},Qb=new WeakMap,mx=new WeakMap,xE=new WeakMap,Jb=new WeakSet,HN=function(t){const r=n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=r(this.state),cm.batch(()=>{Vs(this,Qb).forEach(n=>{n.onMutationUpdate(t)}),Vs(this,mx).notify({mutation:this,type:"updated",action:t})})},dXe);function Zet(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Bj,o1,Gz,uXe,iEt=(uXe=class extends g8{constructor(t={}){super();Mi(this,Bj);Mi(this,o1);Mi(this,Gz);this.config=t,Da(this,Bj,new Set),Da(this,o1,new Map),Da(this,Gz,0)}build(t,r,n){const a=new aEt({mutationCache:this,mutationId:++AU(this,Gz)._,options:t.defaultMutationOptions(r),state:n});return this.add(a),a}add(t){Vs(this,Bj).add(t);const r=QU(t);if(typeof r=="string"){const n=Vs(this,o1).get(r);n?n.push(t):Vs(this,o1).set(r,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Vs(this,Bj).delete(t)){const r=QU(t);if(typeof r=="string"){const n=Vs(this,o1).get(r);if(n)if(n.length>1){const a=n.indexOf(t);a!==-1&&n.splice(a,1)}else n[0]===t&&Vs(this,o1).delete(r)}}this.notify({type:"removed",mutation:t})}canRun(t){const r=QU(t);if(typeof r=="string"){const n=Vs(this,o1).get(r),a=n==null?void 0:n.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var n;const r=QU(t);if(typeof r=="string"){const a=(n=Vs(this,o1).get(r))==null?void 0:n.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){cm.batch(()=>{Vs(this,Bj).forEach(t=>{this.notify({type:"removed",mutation:t})}),Vs(this,Bj).clear(),Vs(this,o1).clear()})}getAll(){return Array.from(Vs(this,Bj))}find(t){const r={exact:!0,...t};return this.getAll().find(n=>VOe(r,n))}findAll(t={}){return this.getAll().filter(r=>VOe(t,r))}notify(t){cm.batch(()=>{this.listeners.forEach(r=>{r(t)})})}resumePausedMutations(){const t=this.getAll().filter(r=>r.state.isPaused);return cm.batch(()=>Promise.all(t.map(r=>r.continue().catch(xx))))}},Bj=new WeakMap,o1=new WeakMap,Gz=new WeakMap,uXe);function QU(s){var t;return(t=s.options.scope)==null?void 0:t.id}function Xhe(s){return{onFetch:(t,r)=>{var u,m,f,x,y;const n=t.options,a=(f=(m=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:m.fetchMore)==null?void 0:f.direction,i=((x=t.state.data)==null?void 0:x.pages)||[],l=((y=t.state.data)==null?void 0:y.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let _=!1;const b=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?_=!0:t.signal.addEventListener("abort",()=>{_=!0}),t.signal)})},j=qet(t.options,t.fetchOptions),N=async(C,A,E)=>{if(_)return Promise.reject();if(A==null&&C.pages.length)return Promise.resolve(C);const R=(()=>{const K={client:t.client,queryKey:t.queryKey,pageParam:A,direction:E?"backward":"forward",meta:t.options.meta};return b(K),K})(),F=await j(R),{maxPages:O}=t.options,B=E?ZTt:YTt;return{pages:B(C.pages,F,O),pageParams:B(C.pageParams,A,O)}};if(a&&i.length){const C=a==="backward",A=C?Xet:uNe,E={pages:i,pageParams:l},D=A(n,E);o=await N(E,D,C)}else{const C=s??i.length;do{const A=c===0?l[0]??n.initialPageParam:uNe(n,o);if(c>0&&A==null)break;o=await N(o,A),c++}while(c{var _,b;return(b=(_=t.options).persister)==null?void 0:b.call(_,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r)}:t.fetchFn=d}}}function uNe(s,{pages:t,pageParams:r}){const n=t.length-1;return t.length>0?s.getNextPageParam(t[n],t,r[n],r):void 0}function Xet(s,{pages:t,pageParams:r}){var n;return t.length>0?(n=s.getPreviousPageParam)==null?void 0:n.call(s,t[0],t,r[0],r):void 0}function oEt(s,t){return t?uNe(s,t)!=null:!1}function lEt(s,t){return!t||!s.getPreviousPageParam?!1:Xet(s,t)!=null}var Lu,Sk,Ck,VP,HP,Tk,GP,WP,hXe,cEt=(hXe=class{constructor(s={}){Mi(this,Lu);Mi(this,Sk);Mi(this,Ck);Mi(this,VP);Mi(this,HP);Mi(this,Tk);Mi(this,GP);Mi(this,WP);Da(this,Lu,s.queryCache||new nEt),Da(this,Sk,s.mutationCache||new iEt),Da(this,Ck,s.defaultOptions||{}),Da(this,VP,new Map),Da(this,HP,new Map),Da(this,Tk,0)}mount(){AU(this,Tk)._++,Vs(this,Tk)===1&&(Da(this,GP,j5e.subscribe(async s=>{s&&(await this.resumePausedMutations(),Vs(this,Lu).onFocus())})),Da(this,WP,Zhe.subscribe(async s=>{s&&(await this.resumePausedMutations(),Vs(this,Lu).onOnline())})))}unmount(){var s,t;AU(this,Tk)._--,Vs(this,Tk)===0&&((s=Vs(this,GP))==null||s.call(this),Da(this,GP,void 0),(t=Vs(this,WP))==null||t.call(this),Da(this,WP,void 0))}isFetching(s){return Vs(this,Lu).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return Vs(this,Sk).findAll({...s,status:"pending"}).length}getQueryData(s){var r;const t=this.defaultQueryOptions({queryKey:s});return(r=Vs(this,Lu).get(t.queryHash))==null?void 0:r.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),r=Vs(this,Lu).build(this,t),n=r.state.data;return n===void 0?this.fetchQuery(s):(s.revalidateIfStale&&r.isStaleByTime(fS(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(s){return Vs(this,Lu).findAll(s).map(({queryKey:t,state:r})=>{const n=r.data;return[t,n]})}setQueryData(s,t,r){const n=this.defaultQueryOptions({queryKey:s}),a=Vs(this,Lu).get(n.queryHash),i=a==null?void 0:a.state.data,l=WTt(t,i);if(l!==void 0)return Vs(this,Lu).build(this,n).setData(l,{...r,manual:!0})}setQueriesData(s,t,r){return cm.batch(()=>Vs(this,Lu).findAll(s).map(({queryKey:n})=>[n,this.setQueryData(n,t,r)]))}getQueryState(s){var r;const t=this.defaultQueryOptions({queryKey:s});return(r=Vs(this,Lu).get(t.queryHash))==null?void 0:r.state}removeQueries(s){const t=Vs(this,Lu);cm.batch(()=>{t.findAll(s).forEach(r=>{t.remove(r)})})}resetQueries(s,t){const r=Vs(this,Lu);return cm.batch(()=>(r.findAll(s).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const r={revert:!0,...t},n=cm.batch(()=>Vs(this,Lu).findAll(s).map(a=>a.cancel(r)));return Promise.all(n).then(xx).catch(xx)}invalidateQueries(s,t={}){return cm.batch(()=>(Vs(this,Lu).findAll(s).forEach(r=>{r.invalidate()}),(s==null?void 0:s.refetchType)==="none"?Promise.resolve():this.refetchQueries({...s,type:(s==null?void 0:s.refetchType)??(s==null?void 0:s.type)??"active"},t)))}refetchQueries(s,t={}){const r={...t,cancelRefetch:t.cancelRefetch??!0},n=cm.batch(()=>Vs(this,Lu).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,r);return r.throwOnError||(i=i.catch(xx)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(xx)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const r=Vs(this,Lu).build(this,t);return r.isStaleByTime(fS(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(xx).catch(xx)}fetchInfiniteQuery(s){return s.behavior=Xhe(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(xx).catch(xx)}ensureInfiniteQueryData(s){return s.behavior=Xhe(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return Zhe.isOnline()?Vs(this,Sk).resumePausedMutations():Promise.resolve()}getQueryCache(){return Vs(this,Lu)}getMutationCache(){return Vs(this,Sk)}getDefaultOptions(){return Vs(this,Ck)}setDefaultOptions(s){Da(this,Ck,s)}setQueryDefaults(s,t){Vs(this,VP).set(gA(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...Vs(this,VP).values()],r={};return t.forEach(n=>{b9(s,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(s,t){Vs(this,HP).set(gA(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...Vs(this,HP).values()],r={};return t.forEach(n=>{b9(s,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(s){if(s._defaulted)return s;const t={...Vs(this,Ck).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=_5e(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===w5e&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...Vs(this,Ck).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){Vs(this,Lu).clear(),Vs(this,Sk).clear()}},Lu=new WeakMap,Sk=new WeakMap,Ck=new WeakMap,VP=new WeakMap,HP=new WeakMap,Tk=new WeakMap,GP=new WeakMap,WP=new WeakMap,hXe),Jx,_l,Wz,fx,gE,KP,Ek,Ak,Kz,YP,ZP,yE,vE,Mk,XP,ac,CO,hNe,mNe,fNe,pNe,xNe,gNe,yNe,Jet,mXe,Qet=(mXe=class extends g8{constructor(t,r){super();Mi(this,ac);Mi(this,Jx);Mi(this,_l);Mi(this,Wz);Mi(this,fx);Mi(this,gE);Mi(this,KP);Mi(this,Ek);Mi(this,Ak);Mi(this,Kz);Mi(this,YP);Mi(this,ZP);Mi(this,yE);Mi(this,vE);Mi(this,Mk);Mi(this,XP,new Set);this.options=r,Da(this,Jx,t),Da(this,Ak,null),Da(this,Ek,dNe()),this.options.experimental_prefetchInRender||Vs(this,Ek).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Vs(this,_l).addObserver(this),WOe(Vs(this,_l),this.options)?Lo(this,ac,CO).call(this):this.updateResult(),Lo(this,ac,pNe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return vNe(Vs(this,_l),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return vNe(Vs(this,_l),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Lo(this,ac,xNe).call(this),Lo(this,ac,gNe).call(this),Vs(this,_l).removeObserver(this)}setOptions(t){const r=this.options,n=Vs(this,_l);if(this.options=Vs(this,Jx).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Iy(this.options.enabled,Vs(this,_l))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Lo(this,ac,yNe).call(this),Vs(this,_l).setOptions(this.options),r._defaulted&&!Yhe(this.options,r)&&Vs(this,Jx).getQueryCache().notify({type:"observerOptionsUpdated",query:Vs(this,_l),observer:this});const a=this.hasListeners();a&&KOe(Vs(this,_l),n,this.options,r)&&Lo(this,ac,CO).call(this),this.updateResult(),a&&(Vs(this,_l)!==n||Iy(this.options.enabled,Vs(this,_l))!==Iy(r.enabled,Vs(this,_l))||fS(this.options.staleTime,Vs(this,_l))!==fS(r.staleTime,Vs(this,_l)))&&Lo(this,ac,hNe).call(this);const i=Lo(this,ac,mNe).call(this);a&&(Vs(this,_l)!==n||Iy(this.options.enabled,Vs(this,_l))!==Iy(r.enabled,Vs(this,_l))||i!==Vs(this,Mk))&&Lo(this,ac,fNe).call(this,i)}getOptimisticResult(t){const r=Vs(this,Jx).getQueryCache().build(Vs(this,Jx),t),n=this.createResult(r,t);return uEt(this,n)&&(Da(this,fx,n),Da(this,KP,this.options),Da(this,gE,Vs(this,_l).state)),n}getCurrentResult(){return Vs(this,fx)}trackResult(t,r){return new Proxy(t,{get:(n,a)=>(this.trackProp(a),r==null||r(a),Reflect.get(n,a))})}trackProp(t){Vs(this,XP).add(t)}getCurrentQuery(){return Vs(this,_l)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const r=Vs(this,Jx).defaultQueryOptions(t),n=Vs(this,Jx).getQueryCache().build(Vs(this,Jx),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(t){return Lo(this,ac,CO).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Vs(this,fx)))}createResult(t,r){var O;const n=Vs(this,_l),a=this.options,i=Vs(this,fx),l=Vs(this,gE),o=Vs(this,KP),d=t!==n?t.state:Vs(this,Wz),{state:u}=t;let m={...u},f=!1,x;if(r._optimisticResults){const B=this.hasListeners(),K=!B&&WOe(t,r),Z=B&&KOe(t,n,r,a);(K||Z)&&(m={...m,...Yet(u.data,t.options)}),r._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:y,errorUpdatedAt:_,status:b}=m;x=m.data;let j=!1;if(r.placeholderData!==void 0&&x===void 0&&b==="pending"){let B;i!=null&&i.isPlaceholderData&&r.placeholderData===(o==null?void 0:o.placeholderData)?(B=i.data,j=!0):B=typeof r.placeholderData=="function"?r.placeholderData((O=Vs(this,ZP))==null?void 0:O.state.data,Vs(this,ZP)):r.placeholderData,B!==void 0&&(b="success",x=cNe(i==null?void 0:i.data,B,r),f=!0)}if(r.select&&x!==void 0&&!j)if(i&&x===(l==null?void 0:l.data)&&r.select===Vs(this,Kz))x=Vs(this,YP);else try{Da(this,Kz,r.select),x=r.select(x),x=cNe(i==null?void 0:i.data,x,r),Da(this,YP,x),Da(this,Ak,null)}catch(B){Da(this,Ak,B)}Vs(this,Ak)&&(y=Vs(this,Ak),x=Vs(this,YP),_=Date.now(),b="error");const N=m.fetchStatus==="fetching",C=b==="pending",A=b==="error",E=C&&N,D=x!==void 0,F={status:b,fetchStatus:m.fetchStatus,isPending:C,isSuccess:b==="success",isError:A,isInitialLoading:E,isLoading:E,data:x,dataUpdatedAt:m.dataUpdatedAt,error:y,errorUpdatedAt:_,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>d.dataUpdateCount||m.errorUpdateCount>d.errorUpdateCount,isFetching:N,isRefetching:N&&!C,isLoadingError:A&&!D,isPaused:m.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:A&&D,isStale:N5e(t,r),refetch:this.refetch,promise:Vs(this,Ek),isEnabled:Iy(r.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const B=Q=>{F.status==="error"?Q.reject(F.error):F.data!==void 0&&Q.resolve(F.data)},K=()=>{const Q=Da(this,Ek,F.promise=dNe());B(Q)},Z=Vs(this,Ek);switch(Z.status){case"pending":t.queryHash===n.queryHash&&B(Z);break;case"fulfilled":(F.status==="error"||F.data!==Z.value)&&K();break;case"rejected":(F.status!=="error"||F.error!==Z.reason)&&K();break}}return F}updateResult(){const t=Vs(this,fx),r=this.createResult(Vs(this,_l),this.options);if(Da(this,gE,Vs(this,_l).state),Da(this,KP,this.options),Vs(this,gE).data!==void 0&&Da(this,ZP,Vs(this,_l)),Yhe(r,t))return;Da(this,fx,r);const n=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!Vs(this,XP).size)return!0;const l=new Set(i??Vs(this,XP));return this.options.throwOnError&&l.add("error"),Object.keys(Vs(this,fx)).some(o=>{const c=o;return Vs(this,fx)[c]!==t[c]&&l.has(c)})};Lo(this,ac,Jet).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Lo(this,ac,pNe).call(this)}},Jx=new WeakMap,_l=new WeakMap,Wz=new WeakMap,fx=new WeakMap,gE=new WeakMap,KP=new WeakMap,Ek=new WeakMap,Ak=new WeakMap,Kz=new WeakMap,YP=new WeakMap,ZP=new WeakMap,yE=new WeakMap,vE=new WeakMap,Mk=new WeakMap,XP=new WeakMap,ac=new WeakSet,CO=function(t){Lo(this,ac,yNe).call(this);let r=Vs(this,_l).fetch(this.options,t);return t!=null&&t.throwOnError||(r=r.catch(xx)),r},hNe=function(){Lo(this,ac,xNe).call(this);const t=fS(this.options.staleTime,Vs(this,_l));if(xA||Vs(this,fx).isStale||!oNe(t))return;const n=$et(Vs(this,fx).dataUpdatedAt,t)+1;Da(this,yE,setTimeout(()=>{Vs(this,fx).isStale||this.updateResult()},n))},mNe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Vs(this,_l)):this.options.refetchInterval)??!1},fNe=function(t){Lo(this,ac,gNe).call(this),Da(this,Mk,t),!(xA||Iy(this.options.enabled,Vs(this,_l))===!1||!oNe(Vs(this,Mk))||Vs(this,Mk)===0)&&Da(this,vE,setInterval(()=>{(this.options.refetchIntervalInBackground||j5e.isFocused())&&Lo(this,ac,CO).call(this)},Vs(this,Mk)))},pNe=function(){Lo(this,ac,hNe).call(this),Lo(this,ac,fNe).call(this,Lo(this,ac,mNe).call(this))},xNe=function(){Vs(this,yE)&&(clearTimeout(Vs(this,yE)),Da(this,yE,void 0))},gNe=function(){Vs(this,vE)&&(clearInterval(Vs(this,vE)),Da(this,vE,void 0))},yNe=function(){const t=Vs(this,Jx).getQueryCache().build(Vs(this,Jx),this.options);if(t===Vs(this,_l))return;const r=Vs(this,_l);Da(this,_l,t),Da(this,Wz,t.state),this.hasListeners()&&(r==null||r.removeObserver(this),t.addObserver(this))},Jet=function(t){cm.batch(()=>{t.listeners&&this.listeners.forEach(r=>{r(Vs(this,fx))}),Vs(this,Jx).getQueryCache().notify({query:Vs(this,_l),type:"observerResultsUpdated"})})},mXe);function dEt(s,t){return Iy(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function WOe(s,t){return dEt(s,t)||s.state.data!==void 0&&vNe(s,t,t.refetchOnMount)}function vNe(s,t,r){if(Iy(t.enabled,s)!==!1&&fS(t.staleTime,s)!=="static"){const n=typeof r=="function"?r(s):r;return n==="always"||n!==!1&&N5e(s,t)}return!1}function KOe(s,t,r,n){return(s!==t||Iy(n.enabled,s)===!1)&&(!r.suspense||s.state.status!=="error")&&N5e(s,r)}function N5e(s,t){return Iy(t.enabled,s)!==!1&&s.isStaleByTime(fS(t.staleTime,s))}function uEt(s,t){return!Yhe(s.getCurrentResult(),t)}var hEt=class extends Qet{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:Xhe()})}getOptimisticResult(s){return s.behavior=Xhe(),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:r}=s,n=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=n,c=(_=(y=r.fetchMeta)==null?void 0:y.fetchMore)==null?void 0:_.direction,d=l&&c==="forward",u=a&&c==="forward",m=l&&c==="backward",f=a&&c==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:oEt(t,r.data),hasPreviousPage:lEt(t,r.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:m,isFetchingPreviousPage:f,isRefetchError:o&&!d&&!m,isRefetching:i&&!u&&!f}}},Ik,Pk,eg,$j,v2,Iue,bNe,fXe,mEt=(fXe=class extends g8{constructor(r,n){super();Mi(this,v2);Mi(this,Ik);Mi(this,Pk);Mi(this,eg);Mi(this,$j);Da(this,Ik,r),this.setOptions(n),this.bindMethods(),Lo(this,v2,Iue).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var a;const n=this.options;this.options=Vs(this,Ik).defaultMutationOptions(r),Yhe(this.options,n)||Vs(this,Ik).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Vs(this,eg),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&gA(n.mutationKey)!==gA(this.options.mutationKey)?this.reset():((a=Vs(this,eg))==null?void 0:a.state.status)==="pending"&&Vs(this,eg).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Vs(this,eg))==null||r.removeObserver(this)}onMutationUpdate(r){Lo(this,v2,Iue).call(this),Lo(this,v2,bNe).call(this,r)}getCurrentResult(){return Vs(this,Pk)}reset(){var r;(r=Vs(this,eg))==null||r.removeObserver(this),Da(this,eg,void 0),Lo(this,v2,Iue).call(this),Lo(this,v2,bNe).call(this)}mutate(r,n){var a;return Da(this,$j,n),(a=Vs(this,eg))==null||a.removeObserver(this),Da(this,eg,Vs(this,Ik).getMutationCache().build(Vs(this,Ik),this.options)),Vs(this,eg).addObserver(this),Vs(this,eg).execute(r)}},Ik=new WeakMap,Pk=new WeakMap,eg=new WeakMap,$j=new WeakMap,v2=new WeakSet,Iue=function(){var n;const r=((n=Vs(this,eg))==null?void 0:n.state)??Zet();Da(this,Pk,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},bNe=function(r){cm.batch(()=>{var n,a,i,l,o,c,d,u;if(Vs(this,$j)&&this.hasListeners()){const m=Vs(this,Pk).variables,f=Vs(this,Pk).context;(r==null?void 0:r.type)==="success"?((a=(n=Vs(this,$j)).onSuccess)==null||a.call(n,r.data,m,f),(l=(i=Vs(this,$j)).onSettled)==null||l.call(i,r.data,null,m,f)):(r==null?void 0:r.type)==="error"&&((c=(o=Vs(this,$j)).onError)==null||c.call(o,r.error,m,f),(u=(d=Vs(this,$j)).onSettled)==null||u.call(d,void 0,r.error,m,f))}this.listeners.forEach(m=>{m(Vs(this,Pk))})})},fXe),ett=k.createContext(void 0),is=s=>{const t=k.useContext(ett);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},fEt=({client:s,children:t})=>(k.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(ett.Provider,{value:s,children:t})),ttt=k.createContext(!1),pEt=()=>k.useContext(ttt);ttt.Provider;function xEt(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var gEt=k.createContext(xEt()),yEt=()=>k.useContext(gEt),vEt=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},bEt=s=>{k.useEffect(()=>{s.clearReset()},[s])},_Et=({result:s,errorResetBoundary:t,throwOnError:r,query:n,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&n&&(a&&s.data===void 0||Vet(r,[s.error,n])),wEt=s=>{if(s.suspense){const t=n=>n==="static"?n:Math.max(n??1e3,1e3),r=s.staleTime;s.staleTime=typeof r=="function"?(...n)=>t(r(...n)):t(r),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},jEt=(s,t)=>s.isLoading&&s.isFetching&&!t,NEt=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,YOe=(s,t,r)=>t.fetchOptimistic(s).catch(()=>{r.clearReset()});function stt(s,t,r){var m,f,x,y,_;const n=pEt(),a=yEt(),i=is(),l=i.defaultQueryOptions(s);(f=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||f.call(m,l),l._optimisticResults=n?"isRestoring":"optimistic",wEt(l),vEt(l,a),bEt(a);const o=!i.getQueryCache().get(l.queryHash),[c]=k.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!n&&s.subscribed!==!1;if(k.useSyncExternalStore(k.useCallback(b=>{const j=u?c.subscribe(cm.batchCalls(b)):xx;return c.updateResult(),j},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),k.useEffect(()=>{c.setOptions(l)},[l,c]),NEt(l,d))throw YOe(l,c,a);if(_Et({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((y=(x=i.getDefaultOptions().queries)==null?void 0:x._experimental_afterQuery)==null||y.call(x,l,d),l.experimental_prefetchInRender&&!xA&&jEt(d,n)){const b=o?YOe(l,c,a):(_=i.getQueryCache().get(l.queryHash))==null?void 0:_.promise;b==null||b.catch(xx).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function pt(s,t){return stt(s,Qet)}function Mt(s,t){const r=is(),[n]=k.useState(()=>new mEt(r,s));k.useEffect(()=>{n.setOptions(s)},[n,s]);const a=k.useSyncExternalStore(k.useCallback(l=>n.subscribe(cm.batchCalls(l)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=k.useCallback((l,o)=>{n.mutate(l,o).catch(xx)},[n]);if(a.error&&Vet(n.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function kEt(s,t){return stt(s,hEt)}/** * @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 _9(){return _9=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function rtt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function CEt(){return Math.random().toString(36).substr(2,8)}function XOe(s,t){return{usr:s.state,key:s.key,idx:t}}function _Ne(s,t,r,n){return r===void 0&&(r=null),_9({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?y8(t):t,{state:r,key:t&&t.key||n||CEt()})}function Qhe(s){let{pathname:t="/",search:r="",hash:n=""}=s;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),n&&n!=="#"&&(t+=n.charAt(0)==="#"?n:"#"+n),t}function y8(s){let t={};if(s){let r=s.indexOf("#");r>=0&&(t.hash=s.substr(r),s=s.substr(0,r));let n=s.indexOf("?");n>=0&&(t.search=s.substr(n),s=s.substr(0,n)),s&&(t.pathname=s)}return t}function TEt(s,t,r,n){n===void 0&&(n={});let{window:a=document.defaultView,v5Compat:i=!1}=n,l=a.history,o=Rk.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(_9({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function m(){o=Rk.Pop;let b=u(),j=b==null?null:b-d;d=b,c&&c({action:o,location:_.location,delta:j})}function f(b,j){o=Rk.Push;let N=_Ne(_.location,b,j);d=u()+1;let C=XOe(N,d),A=_.createHref(N);try{l.pushState(C,"",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 x(b,j){o=Rk.Replace;let N=_Ne(_.location,b,j);d=u();let C=XOe(N,d),A=_.createHref(N);l.replaceState(C,"",A),i&&c&&c({action:o,location:_.location,delta:0})}function y(b){let j=a.location.origin!=="null"?a.location.origin:a.location.href,N=typeof b=="string"?b:Qhe(b);return N=N.replace(/ $/,"%20"),xh(j,"No window.location.(origin|href) available to create URL for href: "+N),new URL(N,j)}let _={get action(){return o},get location(){return s(a,l)},listen(b){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(ZOe,m),c=b,()=>{a.removeEventListener(ZOe,m),c=null}},createHref(b){return t(a,b)},createURL:y,encodeLocation(b){let j=y(b);return{pathname:j.pathname,search:j.search,hash:j.hash}},push:f,replace:x,go(b){return l.go(b)}};return _}var QOe;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(QOe||(QOe={}));function EEt(s,t,r){return r===void 0&&(r="/"),AEt(s,t,r,!1)}function AEt(s,t,r,n){let a=typeof t=="string"?y8(t):t,i=k5e(a.pathname||"/",r);if(i==null)return null;let l=ntt(s);MEt(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("/")&&(xh(c.relativePath.startsWith(n),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(n.length));let d=pS([n,c.relativePath]),u=r.concat(c);i.children&&i.children.length>0&&(xh(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),ntt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:FEt(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 att(i.path))a(i,l,c)}),t}function att(s){let t=s.split("/");if(t.length===0)return[];let[r,...n]=t,a=r.endsWith("?"),i=r.replace(/\?$/,"");if(n.length===0)return a?[i,""]:[i];let l=att(n.join("/")),o=[];return o.push(...l.map(c=>c===""?i:[i,c].join("/"))),a&&o.push(...l),o.map(c=>s.startsWith("/")&&c===""?"/":c)}function MEt(s){s.sort((t,r)=>t.score!==r.score?r.score-t.score:zEt(t.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const IEt=/^:[\w-]+$/,PEt=3,LEt=2,DEt=1,REt=10,OEt=-2,JOe=s=>s==="*";function FEt(s,t){let r=s.split("/"),n=r.length;return r.some(JOe)&&(n+=OEt),t&&(n+=LEt),r.filter(a=>!JOe(a)).reduce((a,i)=>a+(IEt.test(i)?PEt:i===""?DEt:REt),n)}function zEt(s,t){return s.length===t.length&&s.slice(0,-1).every((n,a)=>n===t[a])?s[s.length-1]-t[t.length-1]:0}function BEt(s,t,r){let{routesMeta:n}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:f,isOptional:x}=u;if(f==="*"){let _=o[m]||"";l=i.slice(0,i.length-_.length).replace(/(.)\/+$/,"$1")}const y=o[m];return x&&!y?d[f]=void 0:d[f]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function $Et(s,t,r){t===void 0&&(t=!1),r===void 0&&(r=!0),rtt(s==="*"||!s.endsWith("*")||s.endsWith("/*"),'Route path "'+s+'" will be treated as if it were '+('"'+s.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+s.replace(/\*$/,"/*")+'".'));let n=[],a="^"+s.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(n.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return s.endsWith("*")?(n.push({paramName:"*"}),a+=s==="*"||s==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?a+="\\/*$":s!==""&&s!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),n]}function UEt(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return rtt(!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 k5e(s,t){if(t==="/")return s;if(!s.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,n=s.charAt(r);return n&&n!=="/"?null:s.slice(r)||"/"}function qEt(s,t){t===void 0&&(t="/");let{pathname:r,search:n="",hash:a=""}=typeof s=="string"?y8(s):s;return{pathname:r?r.startsWith("/")?r:VEt(r,t):t,search:WEt(n),hash:KEt(a)}}function VEt(s,t){let r=t.replace(/\/+$/,"").split("/");return s.split("/").forEach(a=>{a===".."?r.length>1&&r.pop():a!=="."&&r.push(a)}),r.length>1?r.join("/"):"/"}function _be(s,t,r,n){return"Cannot include a '"+s+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function HEt(s){return s.filter((t,r)=>r===0||t.route.path&&t.route.path.length>0)}function S5e(s,t){let r=HEt(s);return t?r.map((n,a)=>a===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function C5e(s,t,r,n){n===void 0&&(n=!1);let a;typeof s=="string"?a=y8(s):(a=_9({},s),xh(!a.pathname||!a.pathname.includes("?"),_be("?","pathname","search",a)),xh(!a.pathname||!a.pathname.includes("#"),_be("#","pathname","hash",a)),xh(!a.search||!a.search.includes("#"),_be("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=r;else{let m=t.length-1;if(!n&&l.startsWith("..")){let f=l.split("/");for(;f[0]==="..";)f.shift(),m-=1;a.pathname=f.join("/")}o=m>=0?t[m]:"/"}let c=qEt(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&r.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const pS=s=>s.join("/").replace(/\/\/+/g,"/"),GEt=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),WEt=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,KEt=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function YEt(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const itt=["post","put","patch","delete"];new Set(itt);const ZEt=["get",...itt];new Set(ZEt);/** * 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 w9(){return w9=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),k.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){n.go(d);return}let m=C5e(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(m.pathname=m.pathname==="/"?t:pS([t,m.pathname])),(u.replace?n.replace:n.push)(m,u.state,u)},[t,n,l,i,s])}const eAt=k.createContext(null);function tAt(s){let t=k.useContext(ew).outlet;return t&&k.createElement(eAt.Provider,{value:s},t)}function xo(){let{matches:s}=k.useContext(ew),t=s[s.length-1];return t?t.params:{}}function ctt(s,t){let{relative:r}=t===void 0?{}:t,{future:n}=k.useContext(KS),{matches:a}=k.useContext(ew),{pathname:i}=vc(),l=JSON.stringify(S5e(a,n.v7_relativeSplatPath));return k.useMemo(()=>C5e(s,JSON.parse(l),i,r==="path"),[s,l,i,r])}function sAt(s,t){return rAt(s,t)}function rAt(s,t,r,n){v8()||xh(!1);let{navigator:a}=k.useContext(KS),{matches:i}=k.useContext(ew),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=vc(),u;if(t){var m;let b=typeof t=="string"?y8(t):t;c==="/"||(m=b.pathname)!=null&&m.startsWith(c)||xh(!1),u=b}else u=d;let f=u.pathname||"/",x=f;if(c!=="/"){let b=c.replace(/^\//,"").split("/");x="/"+f.replace(/^\//,"").split("/").slice(b.length).join("/")}let y=EEt(s,{pathname:x}),_=lAt(y&&y.map(b=>Object.assign({},b,{params:Object.assign({},o,b.params),pathname:pS([c,a.encodeLocation?a.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:pS([c,a.encodeLocation?a.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,r,n);return t&&_?k.createElement(Txe.Provider,{value:{location:w9({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:Rk.Pop}},_):_}function nAt(){let s=hAt(),t=YEt(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),r=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return k.createElement(k.Fragment,null,k.createElement("h2",null,"Unexpected Application Error!"),k.createElement("h3",{style:{fontStyle:"italic"}},t),r?k.createElement("pre",{style:a},r):null,null)}const aAt=k.createElement(nAt,null);class iAt extends k.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?k.createElement(ew.Provider,{value:this.props.routeContext},k.createElement(ott.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function oAt(s){let{routeContext:t,match:r,children:n}=s,a=k.useContext(T5e);return a&&a.static&&a.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=r.route.id),k.createElement(ew.Provider,{value:t},n)}function lAt(s,t,r,n){var a;if(t===void 0&&(t=[]),r===void 0&&(r=null),n===void 0&&(n=null),s==null){var i;if(!r)return null;if(r.errors)s=r.matches;else if((i=n)!=null&&i.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)s=r.matches;else return null}let l=s,o=(a=r)==null?void 0:a.errors;if(o!=null){let u=l.findIndex(m=>m.route.id&&(o==null?void 0:o[m.route.id])!==void 0);u>=0||xh(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(r&&n&&n.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,m,f)=>{let x,y=!1,_=null,b=null;r&&(x=o&&m.route.id?o[m.route.id]:void 0,_=m.route.errorElement||aAt,c&&(d<0&&f===0?(y=!0,b=null):d===f&&(y=!0,b=m.route.hydrateFallbackElement||null)));let j=t.concat(l.slice(0,f+1)),N=()=>{let C;return x?C=_:y?C=b:m.route.Component?C=k.createElement(m.route.Component,null):m.route.element?C=m.route.element:C=u,k.createElement(oAt,{match:m,routeContext:{outlet:u,matches:j,isDataRoute:r!=null},children:C})};return r&&(m.route.ErrorBoundary||m.route.errorElement||f===0)?k.createElement(iAt,{location:r.location,revalidation:r.revalidation,component:_,error:x,children:N(),routeContext:{outlet:null,matches:j,isDataRoute:!0}}):N()},null)}var dtt=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(dtt||{}),Jhe=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}(Jhe||{});function cAt(s){let t=k.useContext(T5e);return t||xh(!1),t}function dAt(s){let t=k.useContext(XEt);return t||xh(!1),t}function uAt(s){let t=k.useContext(ew);return t||xh(!1),t}function utt(s){let t=uAt(),r=t.matches[t.matches.length-1];return r.route.id||xh(!1),r.route.id}function hAt(){var s;let t=k.useContext(ott),r=dAt(Jhe.UseRouteError),n=utt(Jhe.UseRouteError);return t!==void 0?t:(s=r.errors)==null?void 0:s[n]}function mAt(){let{router:s}=cAt(dtt.UseNavigateStable),t=utt(Jhe.UseNavigateStable),r=k.useRef(!1);return ltt(()=>{r.current=!0}),k.useCallback(function(a,i){i===void 0&&(i={}),r.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,w9({fromRouteId:t},i)))},[s,t])}function fAt(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function o7(s){let{to:t,replace:r,state:n,relative:a}=s;v8()||xh(!1);let{future:i,static:l}=k.useContext(KS),{matches:o}=k.useContext(ew),{pathname:c}=vc(),d=qr(),u=C5e(t,S5e(o,i.v7_relativeSplatPath),c,a==="path"),m=JSON.stringify(u);return k.useEffect(()=>d(JSON.parse(m),{replace:r,state:n,relative:a}),[d,m,a,r,n]),null}function pAt(s){return tAt(s.context)}function xs(s){xh(!1)}function xAt(s){let{basename:t="/",children:r=null,location:n,navigationType:a=Rk.Pop,navigator:i,static:l=!1,future:o}=s;v8()&&xh(!1);let c=t.replace(/^\/*/,"/"),d=k.useMemo(()=>({basename:c,navigator:i,static:l,future:w9({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof n=="string"&&(n=y8(n));let{pathname:u="/",search:m="",hash:f="",state:x=null,key:y="default"}=n,_=k.useMemo(()=>{let b=k5e(u,c);return b==null?null:{location:{pathname:b,search:m,hash:f,state:x,key:y},navigationType:a}},[c,u,m,f,x,y,a]);return _==null?null:k.createElement(KS.Provider,{value:d},k.createElement(Txe.Provider,{children:r,value:_}))}function eme(s){let{children:t,location:r}=s;return sAt(wNe(t),r)}new Promise(()=>{});function wNe(s,t){t===void 0&&(t=[]);let r=[];return k.Children.forEach(s,(n,a)=>{if(!k.isValidElement(n))return;let i=[...t,a];if(n.type===k.Fragment){r.push.apply(r,wNe(n.props.children,i));return}n.type!==xs&&xh(!1),!n.props.index||!n.props.children||xh(!1);let l={id:n.props.id||i.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(l.children=wNe(n.props.children,i)),r.push(l)}),r}/** * React Router DOM v6.30.1 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function jNe(){return jNe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(r[a]=s[a]);return r}function yAt(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function vAt(s,t){return s.button===0&&(!t||t==="_self")&&!yAt(s)}function NNe(s){return s===void 0&&(s=""),new URLSearchParams(typeof s=="string"||Array.isArray(s)||s instanceof URLSearchParams?s:Object.keys(s).reduce((t,r)=>{let n=s[r];return t.concat(Array.isArray(n)?n.map(a=>[r,a]):[[r,n]])},[]))}function bAt(s,t){let r=NNe(s);return t&&t.forEach((n,a)=>{r.has(a)||t.getAll(a).forEach(i=>{r.append(a,i)})}),r}const _At=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],wAt="6";try{window.__reactRouterVersion=wAt}catch{}const jAt="startTransition",tFe=f3e[jAt];function NAt(s){let{basename:t,children:r,future:n,window:a}=s,i=k.useRef();i.current==null&&(i.current=SEt({window:a,v5Compat:!0}));let l=i.current,[o,c]=k.useState({action:l.action,location:l.location}),{v7_startTransition:d}=n||{},u=k.useCallback(m=>{d&&tFe?tFe(()=>c(m)):c(m)},[c,d]);return k.useLayoutEffect(()=>l.listen(u),[l,u]),k.useEffect(()=>fAt(n),[n]),k.createElement(xAt,{basename:t,children:r,location:o.location,navigationType:o.action,navigator:l,future:n})}const kAt=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",SAt=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Vn=k.forwardRef(function(t,r){let{onClick:n,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:m}=t,f=gAt(t,_At),{basename:x}=k.useContext(KS),y,_=!1;if(typeof d=="string"&&SAt.test(d)&&(y=d,kAt))try{let C=new URL(window.location.href),A=d.startsWith("//")?new URL(C.protocol+d):new URL(d),E=k5e(A.pathname,x);A.origin===C.origin&&E!=null?d=E+A.search+A.hash:_=!0}catch{}let b=QEt(d,{relative:a}),j=CAt(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:m});function N(C){n&&n(C),C.defaultPrevented||j(C)}return k.createElement("a",jNe({},f,{href:y||b,onClick:_||i?n:N,ref:r,target:c}))});var sFe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(sFe||(sFe={}));var rFe;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(rFe||(rFe={}));function CAt(s,t){let{target:r,replace:n,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=qr(),d=vc(),u=ctt(s,{relative:l});return k.useCallback(m=>{if(vAt(m,r)){m.preventDefault();let f=n!==void 0?n:Qhe(d)===Qhe(u);c(s,{replace:f,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,n,a,r,s,i,l,o])}function ic(s){let t=k.useRef(NNe(s)),r=k.useRef(!1),n=vc(),a=k.useMemo(()=>bAt(n.search,r.current?null:t.current),[n.search]),i=qr(),l=k.useCallback((o,c)=>{const d=NNe(typeof o=="function"?o(a):o);r.current=!0,i("?"+d,c)},[i,a]);return[a,l]}var TAt=typeof Element<"u",EAt=typeof Map=="function",AAt=typeof Set=="function",MAt=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Pue(s,t){if(s===t)return!0;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(s.constructor!==t.constructor)return!1;var r,n,a;if(Array.isArray(s)){if(r=s.length,r!=t.length)return!1;for(n=r;n--!==0;)if(!Pue(s[n],t[n]))return!1;return!0}var i;if(EAt&&s instanceof Map&&t instanceof Map){if(s.size!==t.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!t.has(n.value[0]))return!1;for(i=s.entries();!(n=i.next()).done;)if(!Pue(n.value[1],t.get(n.value[0])))return!1;return!0}if(AAt&&s instanceof Set&&t instanceof Set){if(s.size!==t.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!t.has(n.value[0]))return!1;return!0}if(MAt&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(t)){if(r=s.length,r!=t.length)return!1;for(n=r;n--!==0;)if(s[n]!==t[n])return!1;return!0}if(s.constructor===RegExp)return s.source===t.source&&s.flags===t.flags;if(s.valueOf!==Object.prototype.valueOf&&typeof s.valueOf=="function"&&typeof t.valueOf=="function")return s.valueOf()===t.valueOf();if(s.toString!==Object.prototype.toString&&typeof s.toString=="function"&&typeof t.toString=="function")return s.toString()===t.toString();if(a=Object.keys(s),r=a.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[n]))return!1;if(TAt&&s instanceof Element)return!1;for(n=r;n--!==0;)if(!((a[n]==="_owner"||a[n]==="__v"||a[n]==="__o")&&s.$$typeof)&&!Pue(s[a[n]],t[a[n]]))return!1;return!0}return s!==s&&t!==t}var IAt=function(t,r){try{return Pue(t,r)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const PAt=gl(IAt);var LAt=function(s,t,r,n,a,i,l,o){if(!s){var c;if(t===void 0)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var d=[r,n,a,i,l,o],u=0;c=new Error(t.replace(/%s/g,function(){return d[u++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}},DAt=LAt;const nFe=gl(DAt);var RAt=function(t,r,n,a){var i=n?n.call(a,t,r):void 0;if(i!==void 0)return!!i;if(t===r)return!0;if(typeof t!="object"||!t||typeof r!="object"||!r)return!1;var l=Object.keys(t),o=Object.keys(r);if(l.length!==o.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(r),d=0;d(s.BASE="base",s.BODY="body",s.HEAD="head",s.HTML="html",s.LINK="link",s.META="meta",s.NOSCRIPT="noscript",s.SCRIPT="script",s.STYLE="style",s.TITLE="title",s.FRAGMENT="Symbol(react.fragment)",s))(htt||{}),wbe={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"]}},aFe=Object.values(htt),E5e={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},FAt=Object.entries(E5e).reduce((s,[t,r])=>(s[r]=t,s),{}),w1="data-rh",pP={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},xP=(s,t)=>{for(let r=s.length-1;r>=0;r-=1){const n=s[r];if(Object.prototype.hasOwnProperty.call(n,t))return n[t]}return null},zAt=s=>{let t=xP(s,"title");const r=xP(s,pP.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),r&&t)return r.replace(/%s/g,()=>t);const n=xP(s,pP.DEFAULT_TITLE);return t||n||void 0},BAt=s=>xP(s,pP.ON_CHANGE_CLIENT_STATE)||(()=>{}),jbe=(s,t)=>t.filter(r=>typeof r[s]<"u").map(r=>r[s]).reduce((r,n)=>({...r,...n}),{}),$At=(s,t)=>t.filter(r=>typeof r.base<"u").map(r=>r.base).reverse().reduce((r,n)=>{if(!r.length){const a=Object.keys(n);for(let i=0;iconsole&&typeof console.warn=="function"&&console.warn(s),PR=(s,t,r)=>{const n={};return r.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&UAt(`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 f=0;fa.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let r=0;r({baseTag:$At(["href"],s),bodyAttributes:jbe("bodyAttributes",s),defer:xP(s,pP.DEFER),encode:xP(s,pP.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:jbe("htmlAttributes",s),linkTags:PR("link",["rel","href"],s),metaTags:PR("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:PR("noscript",["innerHTML"],s),onChangeClientState:BAt(s),scriptTags:PR("script",["src","innerHTML"],s),styleTags:PR("style",["cssText"],s),title:zAt(s),titleAttributes:jbe("titleAttributes",s),prioritizeSeoTags:qAt(s,pP.PRIORITIZE_SEO_TAGS)}),mtt=s=>Array.isArray(s)?s.join(""):s,HAt=(s,t)=>{const r=Object.keys(s);for(let n=0;nArray.isArray(s)?s.reduce((r,n)=>(HAt(n,t)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:s,priority:[]},iFe=(s,t)=>({...s,[t]:void 0}),GAt=["noscript","script","style"],kNe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),ftt=s=>Object.keys(s).reduce((t,r)=>{const n=typeof s[r]<"u"?`${r}="${s[r]}"`:`${r}`;return t?`${t} ${n}`:n},""),WAt=(s,t,r,n)=>{const a=ftt(r),i=mtt(t);return a?`<${s} ${w1}="true" ${a}>${kNe(i,n)}`:`<${s} ${w1}="true">${kNe(i,n)}`},KAt=(s,t,r=!0)=>t.reduce((n,a)=>{const i=a,l=Object.keys(i).filter(d=>!(d==="innerHTML"||d==="cssText")).reduce((d,u)=>{const m=typeof i[u]>"u"?u:`${u}="${kNe(i[u],r)}"`;return d?`${d} ${m}`:m},""),o=i.innerHTML||i.cssText||"",c=GAt.indexOf(s)===-1;return`${n}<${s} ${w1}="true" ${l}${c?"/>":`>${o}`}`},""),ptt=(s,t={})=>Object.keys(s).reduce((r,n)=>{const a=E5e[n];return r[a||n]=s[n],r},t),YAt=(s,t,r)=>{const n={key:t,[w1]:!0},a=ptt(r,n);return[Ct.createElement("title",a,t)]},Lue=(s,t)=>t.map((r,n)=>{const a={key:n,[w1]:!0};return Object.keys(r).forEach(i=>{const o=E5e[i]||i;if(o==="innerHTML"||o==="cssText"){const c=r.innerHTML||r.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=r[i]}),Ct.createElement(s,a)}),Ay=(s,t,r=!0)=>{switch(s){case"title":return{toComponent:()=>YAt(s,t.title,t.titleAttributes),toString:()=>WAt(s,t.title,t.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>ptt(t),toString:()=>ftt(t)};default:return{toComponent:()=>Lue(s,t),toString:()=>KAt(s,t,r)}}},ZAt=({metaTags:s,linkTags:t,scriptTags:r,encode:n})=>{const a=Nbe(s,wbe.meta),i=Nbe(t,wbe.link),l=Nbe(r,wbe.script);return{priorityMethods:{toComponent:()=>[...Lue("meta",a.priority),...Lue("link",i.priority),...Lue("script",l.priority)],toString:()=>`${Ay("meta",a.priority,n)} ${Ay("link",i.priority,n)} ${Ay("script",l.priority,n)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},XAt=s=>{const{baseTag:t,bodyAttributes:r,encode:n=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:u,metaTags:m,scriptTags:f}=s,x={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:x,linkTags:u,metaTags:m,scriptTags:f}=ZAt(s)),{priority:x,base:Ay("base",t,n),bodyAttributes:Ay("bodyAttributes",r,n),htmlAttributes:Ay("htmlAttributes",a,n),link:Ay("link",u,n),meta:Ay("meta",m,n),noscript:Ay("noscript",i,n),script:Ay("script",f,n),style:Ay("style",l,n),title:Ay("title",{title:o,titleAttributes:c},n)}},SNe=XAt,JU=[],xtt=!!(typeof window<"u"&&window.document&&window.document.createElement),CNe=class{constructor(s,t){_a(this,"instances",[]);_a(this,"canUseDOM",xtt);_a(this,"context");_a(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?JU:this.instances,add:s=>{(this.canUseDOM?JU:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?JU:this.instances).indexOf(s);(this.canUseDOM?JU:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=SNe({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},QAt={},gtt=Ct.createContext(QAt),bE,ytt=(bE=class extends k.Component{constructor(r){super(r);_a(this,"helmetData");this.helmetData=new CNe(this.props.context||{},bE.canUseDOM)}render(){return Ct.createElement(gtt.Provider,{value:this.helmetData.value},this.props.children)}},_a(bE,"canUseDOM",xtt),bE),m6=(s,t)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${s}[${w1}]`),a=[].slice.call(n),i=[];let l;return t&&t.length&&t.forEach(o=>{const c=document.createElement(s);for(const d in o)if(Object.prototype.hasOwnProperty.call(o,d))if(d==="innerHTML")c.innerHTML=o.innerHTML;else if(d==="cssText")c.styleSheet?c.styleSheet.cssText=o.cssText:c.appendChild(document.createTextNode(o.cssText));else{const u=d,m=typeof o[u]>"u"?"":o[u];c.setAttribute(d,m)}c.setAttribute(w1,"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=>r.appendChild(o)),{oldTags:a,newTags:i}},TNe=(s,t)=>{const r=document.getElementsByTagName(s)[0];if(!r)return;const n=r.getAttribute(w1),a=n?n.split(","):[],i=[...a],l=Object.keys(t);for(const o of l){const c=t[o]||"";r.getAttribute(o)!==c&&r.setAttribute(o,c),a.indexOf(o)===-1&&a.push(o);const d=i.indexOf(o);d!==-1&&i.splice(d,1)}for(let o=i.length-1;o>=0;o-=1)r.removeAttribute(i[o]);a.length===i.length?r.removeAttribute(w1):r.getAttribute(w1)!==l.join(",")&&r.setAttribute(w1,l.join(","))},JAt=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=mtt(s)),TNe("title",t)},oFe=(s,t)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:u,title:m,titleAttributes:f}=s;TNe("body",n),TNe("html",a),JAt(m,f);const x={baseTag:m6("base",r),linkTags:m6("link",i),metaTags:m6("meta",l),noscriptTags:m6("noscript",o),scriptTags:m6("script",d),styleTags:m6("style",u)},y={},_={};Object.keys(x).forEach(b=>{const{newTags:j,oldTags:N}=x[b];j.length&&(y[b]=j),N.length&&(_[b]=x[b].oldTags)}),t&&t(),c(s,y,_)},LR=null,eMt=s=>{LR&&cancelAnimationFrame(LR),s.defer?LR=requestAnimationFrame(()=>{oFe(s,()=>{LR=null})}):(oFe(s),LR=null)},tMt=eMt,lFe=class extends k.Component{constructor(){super(...arguments);_a(this,"rendered",!1)}shouldComponentUpdate(t){return!OAt(t,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:t}=this.props.context;t.remove(this),this.emitChange()}emitChange(){const{helmetInstances:t,setHelmet:r}=this.props.context;let n=null;const a=VAt(t.get().map(i=>{const l={...i.props};return delete l.context,l}));ytt.canUseDOM?tMt(a):SNe&&(n=SNe(a)),r(n)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:t}=this.props.context;t.add(this),this.emitChange()}render(){return this.init(),null}},s2e,Yo=(s2e=class extends k.Component{shouldComponentUpdate(s){return!PAt(iFe(this.props,"helmetData"),iFe(s,"helmetData"))}mapNestedChildrenToProps(s,t){if(!t)return null;switch(s.type){case"script":case"noscript":return{innerHTML:t};case"style":return{cssText:t};default:throw new Error(`<${s.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(s,t,r,n){return{...t,[s.type]:[...t[s.type]||[],{...r,...this.mapNestedChildrenToProps(s,n)}]}}mapObjectTypeChildren(s,t,r,n){switch(s.type){case"title":return{...t,[s.type]:n,titleAttributes:{...r}};case"body":return{...t,bodyAttributes:{...r}};case"html":return{...t,htmlAttributes:{...r}};default:return{...t,[s.type]:{...r}}}}mapArrayTypeChildrenToProps(s,t){let r={...t};return Object.keys(s).forEach(n=>{r={...r,[n]:s[n]}}),r}warnOnInvalidChildren(s,t){return nFe(aFe.some(r=>s.type===r),typeof s.type=="function"?"You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${aFe.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),nFe(!t||typeof t=="string"||Array.isArray(t)&&!t.some(r=>typeof r!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(s,t){let r={};return Ct.Children.forEach(s,n=>{if(!n||!n.props)return;const{children:a,...i}=n.props,l=Object.keys(i).reduce((c,d)=>(c[FAt[d]||d]=i[d],c),{});let{type:o}=n;switch(typeof o=="symbol"?o=o.toString():this.warnOnInvalidChildren(n,a),o){case"Symbol(react.fragment)":t=this.mapChildrenToProps(a,t);break;case"link":case"meta":case"noscript":case"script":case"style":r=this.flattenArrayTypeChildren(n,r,l,a);break;default:t=this.mapObjectTypeChildren(n,t,l,a);break}}),this.mapArrayTypeChildrenToProps(r,t)}render(){const{children:s,...t}=this.props;let r={...t},{helmetData:n}=t;if(s&&(r=this.mapChildrenToProps(s,r)),n&&!(n instanceof CNe)){const a=n;n=new CNe(a.context,!0),delete r.helmetData}return n?Ct.createElement(lFe,{...r,context:n.value}):Ct.createElement(gtt.Consumer,null,a=>Ct.createElement(lFe,{...r,context:a}))}},_a(s2e,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),s2e);const sMt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>vi(async()=>{const{default:n}=await Promise.resolve().then(()=>b8);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)};class A5e extends Error{constructor(t,r="FunctionsError",n){super(t),this.name=r,this.context=n}}class rMt extends A5e{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class nMt extends A5e{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class aMt extends A5e{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var ENe;(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"})(ENe||(ENe={}));var iMt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(u){try{d(n.next(u))}catch(m){l(m)}}function c(u){try{d(n.throw(u))}catch(m){l(m)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class oMt{constructor(t,{headers:r={},customFetch:n,region:a=ENe.Any}={}){this.url=t,this.headers=r,this.region=a,this.fetch=sMt(n)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,r={}){var n;return iMt(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=r;let o={},{region:c}=r;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const 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 rMt(y)}),m=u.headers.get("x-relay-error");if(m&&m==="true")throw new nMt(u);if(!u.ok)throw new aMt(u);let f=((n=u.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),x;return f==="application/json"?x=yield u.json():f==="application/octet-stream"?x=yield u.blob():f==="text/event-stream"?x=u:f==="multipart/form-data"?x=yield u.formData():x=yield u.text(),{data:x,error:null}}catch(a){return{data:null,error:a}}})}}var ag={},M5e={},Exe={},oB={},Axe={},Mxe={},lMt=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")},oL=lMt();const cMt=oL.fetch,vtt=oL.fetch.bind(oL),btt=oL.Headers,dMt=oL.Request,uMt=oL.Response,b8=Object.freeze(Object.defineProperty({__proto__:null,Headers:btt,Request:dMt,Response:uMt,default:vtt,fetch:cMt},Symbol.toStringTag,{value:"Module"})),hMt=Bkt(b8);var Ixe={};Object.defineProperty(Ixe,"__esModule",{value:!0});let mMt=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};Ixe.default=mMt;var _tt=lh&&lh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Mxe,"__esModule",{value:!0});const fMt=_tt(hMt),pMt=_tt(Ixe);let xMt=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=fMt.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,r){return this.headers=Object.assign({},this.headers),this.headers[t]=r,this}then(t,r){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const n=this.fetch;let a=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,u=null,m=null,f=i.status,x=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)/),b=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");_&&b&&b.length>1&&(m=parseInt(b[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,m=null,f=406,x="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,f=200,x="OK")}catch{i.status===404&&_===""?(f=204,x="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,f=200,x="OK"),d&&this.shouldThrowOnError)throw new pMt.default(d)}return{error:d,data:u,count:m,status:f,statusText:x}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,r)}returns(){return this}overrideTypes(){return this}};Mxe.default=xMt;var gMt=lh&&lh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Axe,"__esModule",{value:!0});const yMt=gMt(Mxe);let vMt=class extends yMt.default{select(t){let r=!1;const n=(t??"*").split("").map(a=>/\s/.test(a)&&!r?"":(a==='"'&&(r=!r),a)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:r=!0,nullsFirst:n,foreignTable:a,referencedTable:i=a}={}){const l=i?`${i}.order`:"order",o=this.url.searchParams.get(l);return this.url.searchParams.set(l,`${o?`${o},`:""}${t}.${r?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:r,referencedTable:n=r}={}){const a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(a,`${t}`),this}range(t,r,{foreignTable:n,referencedTable:a=n}={}){const i=typeof a>"u"?"offset":`${a}.offset`,l=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(l,`${r-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:t=!1,verbose:r=!1,settings:n=!1,buffers:a=!1,wal:i=!1,format:l="text"}={}){var o;const c=[t?"analyze":null,r?"verbose":null,n?"settings":null,a?"buffers":null,i?"wal":null].filter(Boolean).join("|"),d=(o=this.headers.Accept)!==null&&o!==void 0?o:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${l}; for="${d}"; options=${c};`,l==="json"?this:this}rollback(){var t;return((t=this.headers.Prefer)!==null&&t!==void 0?t:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Axe.default=vMt;var bMt=lh&&lh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(oB,"__esModule",{value:!0});const _Mt=bMt(Axe);let wMt=class extends _Mt.default{eq(t,r){return this.url.searchParams.append(t,`eq.${r}`),this}neq(t,r){return this.url.searchParams.append(t,`neq.${r}`),this}gt(t,r){return this.url.searchParams.append(t,`gt.${r}`),this}gte(t,r){return this.url.searchParams.append(t,`gte.${r}`),this}lt(t,r){return this.url.searchParams.append(t,`lt.${r}`),this}lte(t,r){return this.url.searchParams.append(t,`lte.${r}`),this}like(t,r){return this.url.searchParams.append(t,`like.${r}`),this}likeAllOf(t,r){return this.url.searchParams.append(t,`like(all).{${r.join(",")}}`),this}likeAnyOf(t,r){return this.url.searchParams.append(t,`like(any).{${r.join(",")}}`),this}ilike(t,r){return this.url.searchParams.append(t,`ilike.${r}`),this}ilikeAllOf(t,r){return this.url.searchParams.append(t,`ilike(all).{${r.join(",")}}`),this}ilikeAnyOf(t,r){return this.url.searchParams.append(t,`ilike(any).{${r.join(",")}}`),this}is(t,r){return this.url.searchParams.append(t,`is.${r}`),this}in(t,r){const n=Array.from(new Set(r)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`in.(${n})`),this}contains(t,r){return typeof r=="string"?this.url.searchParams.append(t,`cs.${r}`):Array.isArray(r)?this.url.searchParams.append(t,`cs.{${r.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(r)}`),this}containedBy(t,r){return typeof r=="string"?this.url.searchParams.append(t,`cd.${r}`):Array.isArray(r)?this.url.searchParams.append(t,`cd.{${r.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(r)}`),this}rangeGt(t,r){return this.url.searchParams.append(t,`sr.${r}`),this}rangeGte(t,r){return this.url.searchParams.append(t,`nxl.${r}`),this}rangeLt(t,r){return this.url.searchParams.append(t,`sl.${r}`),this}rangeLte(t,r){return this.url.searchParams.append(t,`nxr.${r}`),this}rangeAdjacent(t,r){return this.url.searchParams.append(t,`adj.${r}`),this}overlaps(t,r){return typeof r=="string"?this.url.searchParams.append(t,`ov.${r}`):this.url.searchParams.append(t,`ov.{${r.join(",")}}`),this}textSearch(t,r,{config:n,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");const l=n===void 0?"":`(${n})`;return this.url.searchParams.append(t,`${i}fts${l}.${r}`),this}match(t){return Object.entries(t).forEach(([r,n])=>{this.url.searchParams.append(r,`eq.${n}`)}),this}not(t,r,n){return this.url.searchParams.append(t,`not.${r}.${n}`),this}or(t,{foreignTable:r,referencedTable:n=r}={}){const a=n?`${n}.or`:"or";return this.url.searchParams.append(a,`(${t})`),this}filter(t,r,n){return this.url.searchParams.append(t,`${r}.${n}`),this}};oB.default=wMt;var jMt=lh&&lh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Exe,"__esModule",{value:!0});const DR=jMt(oB);let NMt=class{constructor(t,{headers:r={},schema:n,fetch:a}){this.url=t,this.headers=r,this.schema=n,this.fetch=a}select(t,{head:r=!1,count:n}={}){const a=r?"HEAD":"GET";let i=!1;const l=(t??"*").split("").map(o=>/\s/.test(o)&&!i?"":(o==='"'&&(i=!i),o)).join("");return this.url.searchParams.set("select",l),n&&(this.headers.Prefer=`count=${n}`),new DR.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:r,defaultToNull:n=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),r&&i.push(`count=${r}`),n||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(t)){const l=t.reduce((o,c)=>o.concat(Object.keys(c)),[]);if(l.length>0){const o=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",o.join(","))}}return new DR.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:r,ignoreDuplicates:n=!1,count:a,defaultToNull:i=!0}={}){const l="POST",o=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),this.headers.Prefer&&o.push(this.headers.Prefer),a&&o.push(`count=${a}`),i||o.push("missing=default"),this.headers.Prefer=o.join(","),Array.isArray(t)){const c=t.reduce((d,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 DR.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:r}={}){const n="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),this.headers.Prefer=a.join(","),new DR.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const r="DELETE",n=[];return t&&n.push(`count=${t}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new DR.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Exe.default=NMt;var Pxe={},Lxe={};Object.defineProperty(Lxe,"__esModule",{value:!0});Lxe.version=void 0;Lxe.version="0.0.0-automated";Object.defineProperty(Pxe,"__esModule",{value:!0});Pxe.DEFAULT_HEADERS=void 0;const kMt=Lxe;Pxe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${kMt.version}`};var wtt=lh&&lh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(M5e,"__esModule",{value:!0});const SMt=wtt(Exe),CMt=wtt(oB),TMt=Pxe;let EMt=class jtt{constructor(t,{headers:r={},schema:n,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},TMt.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=a}from(t){const r=new URL(`${this.url}/${t}`);return new SMt.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new jtt(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,r={},{head:n=!1,get:a=!1,count:i}={}){let l;const o=new URL(`${this.url}/rpc/${t}`);let c;n||a?(l=n?"HEAD":"GET",Object.entries(r).filter(([u,m])=>m!==void 0).map(([u,m])=>[u,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([u,m])=>{o.searchParams.append(u,m)})):(l="POST",c=r);const d=Object.assign({},this.headers);return i&&(d.Prefer=`count=${i}`),new CMt.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};M5e.default=EMt;var _8=lh&&lh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ag,"__esModule",{value:!0});ag.PostgrestError=ag.PostgrestBuilder=ag.PostgrestTransformBuilder=ag.PostgrestFilterBuilder=ag.PostgrestQueryBuilder=ag.PostgrestClient=void 0;const Ntt=_8(M5e);ag.PostgrestClient=Ntt.default;const ktt=_8(Exe);ag.PostgrestQueryBuilder=ktt.default;const Stt=_8(oB);ag.PostgrestFilterBuilder=Stt.default;const Ctt=_8(Axe);ag.PostgrestTransformBuilder=Ctt.default;const Ttt=_8(Mxe);ag.PostgrestBuilder=Ttt.default;const Ett=_8(Ixe);ag.PostgrestError=Ett.default;var AMt=ag.default={PostgrestClient:Ntt.default,PostgrestQueryBuilder:ktt.default,PostgrestFilterBuilder:Stt.default,PostgrestTransformBuilder:Ctt.default,PostgrestBuilder:Ttt.default,PostgrestError:Ett.default};const{PostgrestClient:MMt,PostgrestQueryBuilder:Nnr,PostgrestFilterBuilder:knr,PostgrestTransformBuilder:Snr,PostgrestBuilder:Cnr,PostgrestError:Tnr}=AMt;let ANe;typeof window>"u"?ANe=require("ws"):ANe=window.WebSocket;const IMt=ANe,PMt="2.11.10",LMt={"X-Client-Info":`realtime-js/${PMt}`},DMt="1.0.0",Att=1e4,RMt=1e3;var gP;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(gP||(gP={}));var hx;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(hx||(hx={}));var c1;(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"})(c1||(c1={}));var MNe;(function(s){s.websocket="websocket"})(MNe||(MNe={}));var $T;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})($T||($T={}));class OMt{constructor(){this.HEADER_LENGTH=1}decode(t,r){return t.constructor===ArrayBuffer?r(this._binaryDecode(t)):r(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const r=new DataView(t),n=new TextDecoder;return this._decodeBroadcast(t,r,n)}_decodeBroadcast(t,r,n){const a=r.getUint8(1),i=r.getUint8(2);let l=this.HEADER_LENGTH+2;const o=n.decode(t.slice(l,l+a));l=l+a;const c=n.decode(t.slice(l,l+i));l=l+i;const d=JSON.parse(n.decode(t.slice(l,t.byteLength)));return{ref:null,topic:o,event:c,payload:d}}}class Mtt{constructor(t,r){this.callback=t,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var ed;(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"})(ed||(ed={}));const cFe=(s,t,r={})=>{var n;const a=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(t).reduce((i,l)=>(i[l]=FMt(l,s,t,a),i),{})},FMt=(s,t,r,n)=>{const a=t.find(o=>o.name===s),i=a==null?void 0:a.type,l=r[s];return i&&!n.includes(i)?Itt(i,l):INe(l)},Itt=(s,t)=>{if(s.charAt(0)==="_"){const r=s.slice(1,s.length);return UMt(t,r)}switch(s){case ed.bool:return zMt(t);case ed.float4:case ed.float8:case ed.int2:case ed.int4:case ed.int8:case ed.numeric:case ed.oid:return BMt(t);case ed.json:case ed.jsonb:return $Mt(t);case ed.timestamp:return qMt(t);case ed.abstime:case ed.date:case ed.daterange:case ed.int4range:case ed.int8range:case ed.money:case ed.reltime:case ed.text:case ed.time:case ed.timestamptz:case ed.timetz:case ed.tsrange:case ed.tstzrange:return INe(t);default:return INe(t)}},INe=s=>s,zMt=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},BMt=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},$Mt=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},UMt=(s,t)=>{if(typeof s!="string")return s;const r=s.length-1,n=s[r];if(s[0]==="{"&&n==="}"){let i;const l=s.slice(1,r);try{i=JSON.parse("["+l+"]")}catch{i=l?l.split(","):[]}return i.map(o=>Itt(t,o))}return s},qMt=s=>typeof s=="string"?s.replace(" ","T"):s,Ptt=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class kbe{constructor(t,r,n={},a=Att){this.channel=t,this.event=r,this.payload=n,this.timeout=a,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,r){var n;return this._hasReceived(t)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:t,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(r))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var dFe;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(dFe||(dFe={}));class l7{constructor(t,r){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=l7.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=l7.syncDiff(this.state,c,i,l)}),this.pendingDiffs=[],o()}),this.channel._on(n.diff,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=l7.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,r,n,a){const i=this.cloneDeep(t),l=this.transformState(r),o={},c={};return this.map(i,(d,u)=>{l[d]||(c[d]=u)}),this.map(l,(d,u)=>{const m=i[d];if(m){const f=u.map(b=>b.presence_ref),x=m.map(b=>b.presence_ref),y=u.filter(b=>x.indexOf(b.presence_ref)<0),_=m.filter(b=>f.indexOf(b.presence_ref)<0);y.length>0&&(o[d]=y),_.length>0&&(c[d]=_)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},n,a)}static syncDiff(t,r,n,a){const{joins:i,leaves:l}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const m=t[o].map(x=>x.presence_ref),f=u.filter(x=>m.indexOf(x.presence_ref)<0);t[o].unshift(...f)}n(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(m=>m.presence_ref);d=d.filter(m=>u.indexOf(m.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,r){return Object.getOwnPropertyNames(t).map(n=>r(n,t[n]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((r,n)=>{const a=t[n];return"metas"in a?r[n]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=a,r},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var uFe;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(uFe||(uFe={}));var hFe;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(hFe||(hFe={}));var Aj;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Aj||(Aj={}));class I5e{constructor(t,r={config:{}},n){this.topic=t,this.params=r,this.socket=n,this.bindings={},this.state=hx.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new kbe(this,c1.join,this.params,this.timeout),this.rejoinTimer=new Mtt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=hx.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=hx.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=hx.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=hx.errored,this.rejoinTimer.scheduleTimeout())}),this._on(c1.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new l7(this),this.broadcastEndpointURL=Ptt(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(t,r=this.timeout){var n,a;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:l,private:o}}=this.params;this._onError(u=>t==null?void 0:t(Aj.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(Aj.CLOSED));const c={},d={broadcast:i,presence:l,postgres_changes:(a=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.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(r),this.joinPush.receive("ok",async({postgres_changes:u})=>{var m;if(this.socket.setAuth(),u===void 0){t==null||t(Aj.SUBSCRIBED);return}else{const f=this.bindings.postgres_changes,x=(m=f==null?void 0:f.length)!==null&&m!==void 0?m:0,y=[];for(let _=0;_{this.state=hx.errored,t==null||t(Aj.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(Aj.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,r={}){return await this.send({type:"presence",event:"track",payload:t},r.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,r,n){return this._on(t,r,n)}async send(t,r={}){var n,a;if(!this._canPush()&&t.type==="broadcast"){const{event:i,payload:l}=t,c={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:l,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((a=d.body)===null||a===void 0?void 0:a.cancel()),d.ok?"ok":"error"}catch(d){return d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var l,o,c;const d=this._push(t.type,t,r.timeout||this.timeout);t.type==="broadcast"&&!(!((c=(o=(l=this.params)===null||l===void 0?void 0:l.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),d.receive("ok",()=>i("ok")),d.receive("error",()=>i("error")),d.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=hx.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(c1.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const a=new kbe(this,c1.leave,{},t);a.receive("ok",()=>{r(),n("ok")}).receive("timeout",()=>{r(),n("timed out")}).receive("error",()=>{n("error")}),a.send(),this._canPush()||a.trigger("ok",{})})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.rejoinTimer&&clearTimeout(this.rejoinTimer.timer),this.joinPush.destroy()}async _fetchWithTimeout(t,r,n){const a=new AbortController,i=setTimeout(()=>a.abort(),n),l=await this.socket.fetch(t,Object.assign(Object.assign({},r),{signal:a.signal}));return clearTimeout(i),l}_push(t,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let a=new kbe(this,t,r,n);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(t,r,n){return r}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,r,n){var a,i;const l=t.toLocaleLowerCase(),{close:o,error:c,leave:d,join:u}=c1;if(n&&[o,c,d,u].indexOf(l)>=0&&n!==this._joinRef())return;let f=this._onMessage(l,r,n);if(r&&!f)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(x=>{var y,_,b;return((y=x.filter)===null||y===void 0?void 0:y.event)==="*"||((b=(_=x.filter)===null||_===void 0?void 0:_.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===l}).map(x=>x.callback(f,n)):(i=this.bindings[l])===null||i===void 0||i.filter(x=>{var y,_,b,j,N,C;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in x){const A=x.id,E=(y=x.filter)===null||y===void 0?void 0:y.event;return A&&((_=r.ids)===null||_===void 0?void 0:_.includes(A))&&(E==="*"||(E==null?void 0:E.toLocaleLowerCase())===((b=r.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{const A=(N=(j=x==null?void 0:x.filter)===null||j===void 0?void 0:j.event)===null||N===void 0?void 0:N.toLocaleLowerCase();return A==="*"||A===((C=r==null?void 0:r.event)===null||C===void 0?void 0:C.toLocaleLowerCase())}else return x.type.toLocaleLowerCase()===l}).map(x=>{if(typeof f=="object"&&"ids"in f){const y=f.data,{schema:_,table:b,commit_timestamp:j,type:N,errors:C}=y;f=Object.assign(Object.assign({},{schema:_,table:b,commit_timestamp:j,eventType:N,new:{},old:{},errors:C}),this._getPayloadRecords(y))}x.callback(f,n)})}_isClosed(){return this.state===hx.closed}_isJoined(){return this.state===hx.joined}_isJoining(){return this.state===hx.joining}_isLeaving(){return this.state===hx.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,r,n){const a=t.toLocaleLowerCase(),i={type:a,filter:r,callback:n};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(t,r){const n=t.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&I5e.isEqual(a.filter,r))}),this}static isEqual(t,r){if(Object.keys(t).length!==Object.keys(r).length)return!1;for(const n in t)if(t[n]!==r[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(c1.close,{},t)}_onError(t){this._on(c1.error,{},r=>t(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=hx.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const r={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(r.new=cFe(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(r.old=cFe(t.columns,t.old_record)),r}}const mFe=()=>{},VMt=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class HMt{constructor(t,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=LMt,this.params={},this.timeout=Att,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=mFe,this.ref=0,this.logger=mFe,this.conn=null,this.sendBuffer=[],this.serializer=new OMt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>vi(async()=>{const{default:c}=await Promise.resolve().then(()=>b8);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${MNe.websocket}`,this.httpEndpoint=Ptt(t),r!=null&&r.transport?this.transport=r.transport:this.transport=null,r!=null&&r.params&&(this.params=r.params),r!=null&&r.headers&&(this.headers=Object.assign(Object.assign({},this.headers),r.headers)),r!=null&&r.timeout&&(this.timeout=r.timeout),r!=null&&r.logger&&(this.logger=r.logger),(r!=null&&r.logLevel||r!=null&&r.log_level)&&(this.logLevel=r.logLevel||r.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),r!=null&&r.heartbeatIntervalMs&&(this.heartbeatIntervalMs=r.heartbeatIntervalMs);const a=(n=r==null?void 0:r.params)===null||n===void 0?void 0:n.apikey;if(a&&(this.accessTokenValue=a,this.apiKey=a),this.reconnectAfterMs=r!=null&&r.reconnectAfterMs?r.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=r!=null&&r.encode?r.encode:(i,l)=>l(JSON.stringify(i)),this.decode=r!=null&&r.decode?r.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new Mtt(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(r==null?void 0:r.fetch),r!=null&&r.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(r==null?void 0:r.worker)||!1,this.workerUrl=r==null?void 0:r.workerUrl}this.accessToken=(r==null?void 0:r.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=IMt),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 GMt(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:DMt}))}disconnect(t,r){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,r??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(n=>n.teardown()))}getChannels(){return this.channels}async removeChannel(t){const r=await t.unsubscribe();return this.channels=this.channels.filter(n=>n._joinRef!==t._joinRef),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const t=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,r,n){this.logger(t,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case gP.connecting:return $T.Connecting;case gP.open:return $T.Open;case gP.closing:return $T.Closing;default:return $T.Closed}}isConnected(){return this.connectionState()===$T.Open}channel(t,r={config:{}}){const n=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===n);if(a)return a;{const i=new I5e(`realtime:${t}`,r,this);return this.channels.push(i),i}}push(t){const{topic:r,event:n,payload:a,ref:i}=t,l=()=>{this.encode(t,o=>{var c;(c=this.conn)===null||c===void 0||c.send(o)})};this.log("push",`${r} ${n} (${i})`,a),this.isConnected()?l():this.sendBuffer.push(l)}async setAuth(t=null){let r=t||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{r&&n.updateJoinPayload({access_token:r,version:this.headers&&this.headers["X-Client-Info"]}),n.joinedOnce&&n._isJoined()&&n._push(c1.access_token,{access_token:r})}))}async sendHeartbeat(){var t;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(t=this.conn)===null||t===void 0||t.close(RMt,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth()}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let r=this.channels.find(n=>n.topic===t&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${t}"`),r.unsubscribe())}_remove(t){this.channels=this.channels.filter(r=>r.topic!==t.topic)}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_onConnMessage(t){this.decode(t.data,r=>{let{topic:n,event:a,payload:i,ref:l}=r;n==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(r.payload.status=="ok"?"ok":"error"),l&&l===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${a} ${l&&"("+l+")"||""}`,i),Array.from(this.channels).filter(o=>o._isMember(n)).forEach(o=>o._trigger(a,i,l)),this.stateChangeCallbacks.message.forEach(o=>o(r))})}_onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this.workerRef.terminate()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(t=>t())}_onConnClose(t){this.log("transport","close",t),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(r=>r(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(r=>r(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(c1.error))}_appendParams(t,r){if(Object.keys(r).length===0)return t;const n=t.match(/\?/)?"&":"?",a=new URLSearchParams(r);return`${t}${n}${a}`}_workerObjectUrl(t){let r;if(t)r=t;else{const n=new Blob([VMt],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class GMt{constructor(t,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=gP.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=n.close}}class P5e extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function Zm(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class WMt extends P5e{constructor(t,r){super(t),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class PNe extends P5e{constructor(t,r){super(t),this.name="StorageUnknownError",this.originalError=r}}var KMt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(u){try{d(n.next(u))}catch(m){l(m)}}function c(u){try{d(n.throw(u))}catch(m){l(m)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const Ltt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>vi(async()=>{const{default:n}=await Promise.resolve().then(()=>b8);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)},YMt=()=>KMt(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield vi(()=>Promise.resolve().then(()=>b8),void 0)).Response:Response}),LNe=s=>{if(Array.isArray(s))return s.map(r=>LNe(r));if(typeof s=="function"||s!==Object(s))return s;const t={};return Object.entries(s).forEach(([r,n])=>{const a=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[a]=LNe(n)}),t};var KA=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(u){try{d(n.next(u))}catch(m){l(m)}}function c(u){try{d(n.throw(u))}catch(m){l(m)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const Sbe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),ZMt=(s,t,r)=>KA(void 0,void 0,void 0,function*(){const n=yield YMt();s instanceof n&&!(r!=null&&r.noResolveJson)?s.json().then(a=>{t(new WMt(Sbe(a),s.status||500))}).catch(a=>{t(new PNe(Sbe(a),a))}):t(new PNe(Sbe(s),s))}),XMt=(s,t,r,n)=>{const a={method:s,headers:(t==null?void 0:t.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),n&&(a.body=JSON.stringify(n)),Object.assign(Object.assign({},a),r))};function lB(s,t,r,n,a,i){return KA(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(r,XMt(t,n,a,i)).then(c=>{if(!c.ok)throw c;return n!=null&&n.noResolveJson?c:c.json()}).then(c=>l(c)).catch(c=>ZMt(c,o,n))})})}function tme(s,t,r,n){return KA(this,void 0,void 0,function*(){return lB(s,"GET",t,r,n)})}function rk(s,t,r,n,a){return KA(this,void 0,void 0,function*(){return lB(s,"POST",t,n,a,r)})}function QMt(s,t,r,n,a){return KA(this,void 0,void 0,function*(){return lB(s,"PUT",t,n,a,r)})}function JMt(s,t,r,n){return KA(this,void 0,void 0,function*(){return lB(s,"HEAD",t,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function Dtt(s,t,r,n,a){return KA(this,void 0,void 0,function*(){return lB(s,"DELETE",t,n,a,r)})}var Yx=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(u){try{d(n.next(u))}catch(m){l(m)}}function c(u){try{d(n.throw(u))}catch(m){l(m)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const e6t={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},fFe={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class t6t{constructor(t,r={},n,a){this.url=t,this.headers=r,this.bucketId=n,this.fetch=Ltt(a)}uploadOrUpdate(t,r,n,a){return Yx(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},fFe),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=n,o["cache-control"]=`max-age=${l.cacheControl}`,o["content-type"]=l.contentType,c&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),a!=null&&a.headers&&(o=Object.assign(Object.assign({},o),a.headers));const d=this._removeEmptyFolders(r),u=this._getFinalPath(d),m=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),f=yield m.json();return m.ok?{data:{path:d,id:f.Id,fullPath:f.Key},error:null}:{data:null,error:f}}catch(i){if(Zm(i))return{data:null,error:i};throw i}})}upload(t,r,n){return Yx(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,r,n)})}uploadToSignedUrl(t,r,n,a){return Yx(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(t),l=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${l}`);o.searchParams.set("token",r);try{let c;const d=Object.assign({upsert:fFe.upsert},a),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",n)):typeof FormData<"u"&&n instanceof FormData?(c=n,c.append("cacheControl",d.cacheControl)):(c=n,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType);const m=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:u}),f=yield m.json();return m.ok?{data:{path:i,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(Zm(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,r){return Yx(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t);const a=Object.assign({},this.headers);r!=null&&r.upsert&&(a["x-upsert"]="true");const i=yield rk(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:a}),l=new URL(this.url+i.url),o=l.searchParams.get("token");if(!o)throw new P5e("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(n){if(Zm(n))return{data:null,error:n};throw n}})}update(t,r,n){return Yx(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,r,n)})}move(t,r,n){return Yx(this,void 0,void 0,function*(){try{return{data:yield rk(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(Zm(a))return{data:null,error:a};throw a}})}copy(t,r,n){return Yx(this,void 0,void 0,function*(){try{return{data:{path:(yield rk(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(Zm(a))return{data:null,error:a};throw a}})}createSignedUrl(t,r,n){return Yx(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield rk(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:r},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers});const l=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${l}`)},{data:i,error:null}}catch(a){if(Zm(a))return{data:null,error:a};throw a}})}createSignedUrls(t,r,n){return Yx(this,void 0,void 0,function*(){try{const a=yield rk(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:t},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:a.map(l=>Object.assign(Object.assign({},l),{signedUrl:l.signedURL?encodeURI(`${this.url}${l.signedURL}${i}`):null})),error:null}}catch(a){if(Zm(a))return{data:null,error:a};throw a}})}download(t,r){return Yx(this,void 0,void 0,function*(){const a=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),l=i?`?${i}`:"";try{const o=this._getFinalPath(t);return{data:yield(yield tme(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(Zm(o))return{data:null,error:o};throw o}})}info(t){return Yx(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{const n=yield tme(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:LNe(n),error:null}}catch(n){if(Zm(n))return{data:null,error:n};throw n}})}exists(t){return Yx(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{return yield JMt(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(Zm(n)&&n instanceof PNe){const a=n.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:n}}throw n}})}getPublicUrl(t,r){const n=this._getFinalPath(t),a=[],i=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";i!==""&&a.push(i);const o=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",c=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});c!==""&&a.push(c);let d=a.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${n}${d}`)}}}remove(t){return Yx(this,void 0,void 0,function*(){try{return{data:yield Dtt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(r){if(Zm(r))return{data:null,error:r};throw r}})}list(t,r,n){return Yx(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},e6t),r),{prefix:t||""});return{data:yield rk(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},n),error:null}}catch(a){if(Zm(a))return{data:null,error:a};throw a}})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const r=[];return t.width&&r.push(`width=${t.width}`),t.height&&r.push(`height=${t.height}`),t.resize&&r.push(`resize=${t.resize}`),t.format&&r.push(`format=${t.format}`),t.quality&&r.push(`quality=${t.quality}`),r.join("&")}}const s6t="2.7.1",r6t={"X-Client-Info":`storage-js/${s6t}`};var f6=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(u){try{d(n.next(u))}catch(m){l(m)}}function c(u){try{d(n.throw(u))}catch(m){l(m)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class n6t{constructor(t,r={},n){this.url=t,this.headers=Object.assign(Object.assign({},r6t),r),this.fetch=Ltt(n)}listBuckets(){return f6(this,void 0,void 0,function*(){try{return{data:yield tme(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(Zm(t))return{data:null,error:t};throw t}})}getBucket(t){return f6(this,void 0,void 0,function*(){try{return{data:yield tme(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(r){if(Zm(r))return{data:null,error:r};throw r}})}createBucket(t,r={public:!1}){return f6(this,void 0,void 0,function*(){try{return{data:yield rk(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(Zm(n))return{data:null,error:n};throw n}})}updateBucket(t,r){return f6(this,void 0,void 0,function*(){try{return{data:yield QMt(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(Zm(n))return{data:null,error:n};throw n}})}emptyBucket(t){return f6(this,void 0,void 0,function*(){try{return{data:yield rk(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(Zm(r))return{data:null,error:r};throw r}})}deleteBucket(t){return f6(this,void 0,void 0,function*(){try{return{data:yield Dtt(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(r){if(Zm(r))return{data:null,error:r};throw r}})}}class a6t extends n6t{constructor(t,r={},n){super(t,r,n)}from(t){return new t6t(this.url,this.headers,t,this.fetch)}}const i6t="2.49.10";let TO="";typeof Deno<"u"?TO="deno":typeof document<"u"?TO="web":typeof navigator<"u"&&navigator.product==="ReactNative"?TO="react-native":TO="node";const o6t={"X-Client-Info":`supabase-js-${TO}/${i6t}`},l6t={headers:o6t},c6t={schema:"public"},d6t={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},u6t={};var h6t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(u){try{d(n.next(u))}catch(m){l(m)}}function c(u){try{d(n.throw(u))}catch(m){l(m)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const m6t=s=>{let t;return s?t=s:typeof fetch>"u"?t=vtt:t=fetch,(...r)=>t(...r)},f6t=()=>typeof Headers>"u"?btt:Headers,p6t=(s,t,r)=>{const n=m6t(r),a=f6t();return(i,l)=>h6t(void 0,void 0,void 0,function*(){var o;const c=(o=yield t())!==null&&o!==void 0?o:s;let d=new a(l==null?void 0:l.headers);return d.has("apikey")||d.set("apikey",s),d.has("Authorization")||d.set("Authorization",`Bearer ${c}`),n(i,Object.assign(Object.assign({},l),{headers:d}))})};var x6t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(u){try{d(n.next(u))}catch(m){l(m)}}function c(u){try{d(n.throw(u))}catch(m){l(m)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};function g6t(s){return s.endsWith("/")?s:s+"/"}function y6t(s,t){var r,n;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:u,global:m}=t,f={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({},m),o),{headers:Object.assign(Object.assign({},(r=m==null?void 0:m.headers)!==null&&r!==void 0?r:{}),(n=o==null?void 0:o.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>x6t(this,void 0,void 0,function*(){return""})};return s.accessToken?f.accessToken=s.accessToken:delete f.accessToken,f}const Rtt="2.69.1",X6=30*1e3,DNe=3,Cbe=DNe*X6,v6t="http://localhost:9999",b6t="supabase.auth.token",_6t={"X-Client-Info":`gotrue-js/${Rtt}`},RNe="X-Supabase-Api-Version",Ott={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},w6t=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,j6t=6e5;class L5e extends Error{constructor(t,r,n){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Ao(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class N6t extends L5e{constructor(t,r,n){super(t,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function k6t(s){return Ao(s)&&s.name==="AuthApiError"}class Ftt extends L5e{constructor(t,r){super(t),this.name="AuthUnknownError",this.originalError=r}}class YS extends L5e{constructor(t,r,n,a){super(t,n,a),this.name=r,this.status=n}}class GN extends YS{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function S6t(s){return Ao(s)&&s.name==="AuthSessionMissingError"}class Tbe extends YS{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class eq extends YS{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class tq extends YS{constructor(t,r=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function C6t(s){return Ao(s)&&s.name==="AuthImplicitGrantRedirectError"}class pFe extends YS{constructor(t,r=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class ONe extends YS{constructor(t,r){super(t,"AuthRetryableFetchError",r,void 0)}}function Ebe(s){return Ao(s)&&s.name==="AuthRetryableFetchError"}class xFe extends YS{constructor(t,r,n){super(t,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class c7 extends YS{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const gFe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),yFe=` \r=`.split(""),T6t=(()=>{const s=new Array(128);for(let t=0;t-1)for(t.queue=t.queue<<6|n,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function vFe(s){const t=[],r=l=>{t.push(String.fromCodePoint(l))},n={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{M6t(l,n,r)};for(let l=0;l>6),t(128|s&63);return}else if(s<=65535){t(224|s>>12),t(128|s>>6&63),t(128|s&63);return}else if(s<=1114111){t(240|s>>18),t(128|s>>12&63),t(128|s>>6&63),t(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function A6t(s,t){for(let r=0;r55295&&n<=56319){const a=(n-55296)*1024&65535;n=(s.charCodeAt(r+1)-56320&65535|a)+65536,r+=1}E6t(n,t)}}function M6t(s,t,r){if(t.utf8seq===0){if(s<=127){r(s);return}for(let n=1;n<6;n+=1)if(!(s>>7-n&1)){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=s&31;else if(t.utf8seq===3)t.codepoint=s&15;else if(t.utf8seq===4)t.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|s&63,t.utf8seq-=1,t.utf8seq===0&&r(t.codepoint)}}function I6t(s){const t=[],r={queue:0,queuedBits:0},n=a=>{t.push(a)};for(let a=0;at.push(r)),new Uint8Array(t)}function L6t(s){return Math.round(Date.now()/1e3)+s}function D6t(){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 Ub=()=>typeof window<"u"&&typeof document<"u",uC={tested:!1,writable:!1},d7=()=>{if(!Ub())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(uC.tested)return uC.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),uC.tested=!0,uC.writable=!0}catch{uC.tested=!0,uC.writable=!1}return uC.writable};function R6t(s){const t={},r=new URL(s);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((a,i)=>{t[i]=a})}catch{}return r.searchParams.forEach((n,a)=>{t[a]=n}),t}const Btt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>vi(async()=>{const{default:n}=await Promise.resolve().then(()=>b8);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)},O6t=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",$tt=async(s,t,r)=>{await s.setItem(t,JSON.stringify(r))},sq=async(s,t)=>{const r=await s.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return r}},rq=async(s,t)=>{await s.removeItem(t)};class Dxe{constructor(){this.promise=new Dxe.promiseConstructor((t,r)=>{this.resolve=t,this.reject=r})}}Dxe.promiseConstructor=Promise;function Abe(s){const t=s.split(".");if(t.length!==3)throw new c7("Invalid JWT structure");for(let n=0;n{setTimeout(()=>t(null),s)})}function z6t(s,t){return new Promise((n,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const l=await s(i);if(!t(i,null,l)){n(l);return}}catch(l){if(!t(i,l)){a(l);return}}})()})}function B6t(s){return("0"+s.toString(16)).substr(-2)}function $6t(){const t=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let a="";for(let i=0;i<56;i++)a+=r.charAt(Math.floor(Math.random()*n));return a}return crypto.getRandomValues(t),Array.from(t,B6t).join("")}async function U6t(s){const r=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",r),a=new Uint8Array(n);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function q6t(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;const r=await U6t(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function p6(s,t,r=!1){const n=$6t();let a=n;r&&(a+="/PASSWORD_RECOVERY"),await $tt(s,`${t}-code-verifier`,a);const i=await q6t(n);return[i,n===i?"plain":"s256"]}const V6t=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function H6t(s){const t=s.headers.get(RNe);if(!t||!t.match(V6t))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function G6t(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 W6t(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 K6t=function(s,t){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);as.msg||s.message||s.error_description||s.error||JSON.stringify(s),Y6t=[502,503,504];async function bFe(s){var t;if(!O6t(s))throw new ONe(PT(s),0);if(Y6t.includes(s.status))throw new ONe(PT(s),s.status);let r;try{r=await s.json()}catch(i){throw new Ftt(PT(i),i)}let n;const a=H6t(s);if(a&&a.getTime()>=Ott["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new xFe(PT(r),s.status,((t=r.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(n==="session_not_found")throw new GN}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,l)=>i&&typeof l=="string",!0))throw new xFe(PT(r),s.status,r.weak_password.reasons);throw new N6t(PT(r),s.status||500,n)}const Z6t=(s,t,r,n)=>{const a={method:s,headers:(t==null?void 0:t.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),a.body=JSON.stringify(n),Object.assign(Object.assign({},a),r))};async function pl(s,t,r,n){var a;const i=Object.assign({},n==null?void 0:n.headers);i[RNe]||(i[RNe]=Ott["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);const l=(a=n==null?void 0:n.query)!==null&&a!==void 0?a:{};n!=null&&n.redirectTo&&(l.redirect_to=n.redirectTo);const o=Object.keys(l).length?"?"+new URLSearchParams(l).toString():"",c=await X6t(s,t,r+o,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(c):{data:Object.assign({},c),error:null}}async function X6t(s,t,r,n,a,i){const l=Z6t(t,n,a,i);let o;try{o=await s(r,Object.assign({},l))}catch(c){throw console.error(c),new ONe(PT(c),0)}if(o.ok||await bFe(o),n!=null&&n.noResolveJson)return o;try{return await o.json()}catch(c){await bFe(c)}}function WN(s){var t;let r=null;tIt(s)&&(r=Object.assign({},s),s.expires_at||(r.expires_at=L6t(s.expires_in)));const n=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:r,user:n},error:null}}function _Fe(s){const t=WN(s);return!t.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(t.data.weak_password=s.weak_password),t}function gk(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function Q6t(s){return{data:s,error:null}}function J6t(s){const{action_link:t,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i}=s,l=K6t(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:t,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i},c=Object.assign({},l);return{data:{properties:o,user:c},error:null}}function eIt(s){return s}function tIt(s){return s.access_token&&s.refresh_token&&s.expires_in}var sIt=function(s,t){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);a0&&(x.forEach(y=>{const _=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);d[`${b}Page`]=_}),d.total=parseInt(f)),{data:Object.assign(Object.assign({},m),d),error:null}}catch(d){if(Ao(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await pl(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:gk})}catch(r){if(Ao(r))return{data:{user:null},error:r};throw r}}async updateUserById(t,r){try{return await pl(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:r,headers:this.headers,xform:gk})}catch(n){if(Ao(n))return{data:{user:null},error:n};throw n}}async deleteUser(t,r=!1){try{return await pl(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:r},xform:gk})}catch(n){if(Ao(n))return{data:{user:null},error:n};throw n}}async _listFactors(t){try{const{data:r,error:n}=await pl(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:r,error:n}}catch(r){if(Ao(r))return{data:null,error:r};throw r}}async _deleteFactor(t){try{return{data:await pl(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(r){if(Ao(r))return{data:null,error:r};throw r}}}const nIt={getItem:s=>d7()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{d7()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{d7()&&globalThis.localStorage.removeItem(s)}};function wFe(s={}){return{getItem:t=>s[t]||null,setItem:(t,r)=>{s[t]=r},removeItem:t=>{delete s[t]}}}function aIt(){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 x6={debug:!!(globalThis&&d7()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Utt extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class iIt extends Utt{}async function oIt(s,t,r){x6.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),x6.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async a=>{if(a){x6.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await r()}finally{x6.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw x6.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new iIt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(x6.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}aIt();const lIt={url:v6t,storageKey:b6t,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:_6t,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function jFe(s,t,r){return await r()}class j9{constructor(t){var r,n;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=j9.nextInstanceID,j9.nextInstanceID+=1,this.instanceID>0&&Ub()&&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({},lIt),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 rIt({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=Btt(a.fetch),this.lock=a.lock||jFe,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:Ub()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=oIt:this.lock=jFe,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:d7()?this.storage=nIt:(this.memoryStorage={},this.storage=wFe(this.memoryStorage)):(this.memoryStorage={},this.storage=wFe(this.memoryStorage)),Ub()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Rtt}) ${new Date().toISOString()}`,...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{const r=R6t(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),Ub()&&this.detectSessionInUrl&&n!=="none"){const{data:a,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),C6t(i)){const c=(t=i.details)===null||t===void 0?void 0:t.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:l,redirectType:o}=a;return this._debug("#_initialize()","detected session in URL",l,"redirect type",o),await this._saveSession(l),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",l):await this._notifyAllSubscribers("SIGNED_IN",l)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return Ao(r)?{error:r}:{error:new Ftt("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var r,n,a;try{const i=await pl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=t==null?void 0:t.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.captchaToken}},xform:WN}),{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(Ao(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var r,n,a;try{let i;if("email"in t){const{email:u,password:m,options:f}=t;let x=null,y=null;this.flowType==="pkce"&&([x,y]=await p6(this.storage,this.storageKey)),i=await pl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:u,password:m,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:x,code_challenge_method:y},xform:WN})}else if("phone"in t){const{phone:u,password:m,options:f}=t;i=await pl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:m,data:(n=f==null?void 0:f.data)!==null&&n!==void 0?n:{},channel:(a=f==null?void 0:f.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:WN})}else throw new eq("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(Ao(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(t){try{let r;if("email"in t){const{email:i,password:l,options:o}=t;r=await pl(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:_Fe})}else if("phone"in t){const{phone:i,password:l,options:o}=t;r=await pl(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:_Fe})}else throw new eq("You must provide either an email or phone number and a password");const{data:n,error:a}=r;return a?{data:{user:null,session:null},error:a}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new Tbe}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:a})}catch(r){if(Ao(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOAuth(t){var r,n,a,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(r=t.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=t.options)===null||n===void 0?void 0:n.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async _exchangeCodeForSession(t){const r=await sq(this.storage,`${this.storageKey}-code-verifier`),[n,a]=(r??"").split("/");try{const{data:i,error:l}=await pl(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:n},xform:WN});if(await rq(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Tbe}:(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(Ao(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(t){try{const{options:r,provider:n,token:a,access_token:i,nonce:l}=t,o=await pl(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:a,access_token:i,nonce:l,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:WN}),{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 Tbe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(r){if(Ao(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(t){var r,n,a,i,l;try{if("email"in t){const{email:o,options:c}=t;let d=null,u=null;this.flowType==="pkce"&&([d,u]=await p6(this.storage,this.storageKey));const{error:m}=await pl(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:d,code_challenge_method:u},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in t){const{phone:o,options:c}=t,{data:d,error:u}=await pl(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 eq("You must provide either an email or phone number.")}catch(o){if(Ao(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(t){var r,n;try{let a,i;"options"in t&&(a=(r=t.options)===null||r===void 0?void 0:r.redirectTo,i=(n=t.options)===null||n===void 0?void 0:n.captchaToken);const{data:l,error:o}=await pl(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:WN});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(Ao(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(t){var r,n,a;try{let i=null,l=null;return this.flowType==="pkce"&&([i,l]=await p6(this.storage,this.storageKey)),await pl(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(n=(r=t.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((a=t==null?void 0:t.options)===null||a===void 0)&&a.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:l}),headers:this.headers,xform:Q6t})}catch(i){if(Ao(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;if(n)throw n;if(!r)throw new GN;const{error:a}=await pl(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Ao(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{const r=`${this.url}/resend`;if("email"in t){const{email:n,type:a,options:i}=t,{error:l}=await pl(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:l}}else if("phone"in t){const{phone:n,type:a,options:i}=t,{data:l,error:o}=await pl(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:o}}throw new eq("You must provide either an email or phone number and a type")}catch(r){if(Ao(r))return{data:{user:null,session:null},error:r};throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async r=>r))}async _acquireLock(t,r){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await a}catch{}})()),a}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await t(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const r=await sq(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const n=t.expires_at?t.expires_at*1e3-Date.now()(!l&&d==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),l=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,d,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 pl(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:gk}):await this._useSession(async r=>{var n,a,i;const{data:l,error:o}=r;if(o)throw o;return!(!((n=l.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new GN}:await pl(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:gk})})}catch(r){if(Ao(r))return S6t(r)&&(await this._removeSession(),await rq(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:r};throw r}}async updateUser(t,r={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,r))}async _updateUser(t,r={}){try{return await this._useSession(async n=>{const{data:a,error:i}=n;if(i)throw i;if(!a.session)throw new GN;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await p6(this.storage,this.storageKey));const{data:d,error:u}=await pl(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:o,code_challenge_method:c}),jwt:l.access_token,xform:gk});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(n){if(Ao(n))return{data:{user:null},error:n};throw n}}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new GN;const r=Date.now()/1e3;let n=r,a=!0,i=null;const{payload:l}=Abe(t.access_token);if(l.exp&&(n=l.exp,a=n<=r),a){const{session:o,error:c}=await this._callRefreshToken(t.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:c}=await this._getUser(t.access_token);if(c)throw c;i={access_token:t.access_token,refresh_token:t.refresh_token,user:o.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(r){if(Ao(r))return{data:{session:null,user:null},error:r};throw r}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async r=>{var n;if(!t){const{data:l,error:o}=r;if(o)throw o;t=(n=l.session)!==null&&n!==void 0?n:void 0}if(!(t!=null&&t.refresh_token))throw new GN;const{session:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{user:null,session:null},error:i}:a?{data:{user:a.user,session:a},error:null}:{data:{user:null,session:null},error:null}})}catch(r){if(Ao(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(t,r){try{if(!Ub())throw new tq("No browser detected.");if(t.error||t.error_description||t.error_code)throw new tq(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new pFe("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new tq("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new pFe("No code detected.");const{data:N,error:C}=await this._exchangeCodeForSession(t.code);if(C)throw C;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:N.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:a,access_token:i,refresh_token:l,expires_in:o,expires_at:c,token_type:d}=t;if(!i||!o||!l||!d)throw new tq("No session defined in URL");const u=Math.round(Date.now()/1e3),m=parseInt(o);let f=u+m;c&&(f=parseInt(c));const x=f-u;x*1e3<=X6&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${x}s, should have been closer to ${m}s`);const y=f-m;u-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,f,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,f,u);const{data:_,error:b}=await this._getUser(i);if(b)throw b;const j={provider_token:n,provider_refresh_token:a,access_token:i,expires_in:m,expires_at:f,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(n){if(Ao(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(t){return!!(t.access_token||t.error_description)}async _isPKCECallback(t){const r=await sq(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&r)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{error:i};const l=(n=a.session)===null||n===void 0?void 0:n.access_token;if(l){const{error:o}=await this.admin.signOut(l,t);if(o&&!(k6t(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await rq(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const r=D6t(),n={id:r,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(t){return await this._useSession(async r=>{var n,a;try{const{data:{session:i},error:l}=r;if(l)throw l;await((n=this.stateChangeEmitters.get(t))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,r={}){let n=null,a=null;this.flowType==="pkce"&&([n,a]=await p6(this.storage,this.storageKey,!0));try{return await pl(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:n,code_challenge_method:a,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(Ao(i))return{data:null,error:i};throw i}}async getUserIdentities(){var t;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(t=r.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(r){if(Ao(r))return{data:null,error:r};throw r}}async linkIdentity(t){var r;try{const{data:n,error:a}=await this._useSession(async i=>{var l,o,c,d,u;const{data:m,error:f}=i;if(f)throw f;const x=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 pl(this.fetch,"GET",x,{headers:this.headers,jwt:(u=(d=m.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return Ub()&&!(!((r=t.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:t.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(Ao(n))return{data:{provider:t.provider,url:null},error:n};throw n}}async unlinkIdentity(t){try{return await this._useSession(async r=>{var n,a;const{data:i,error:l}=r;if(l)throw l;return await pl(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(a=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&a!==void 0?a:void 0})})}catch(r){if(Ao(r))return{data:null,error:r};throw r}}async _refreshAccessToken(t){const r=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await z6t(async a=>(a>0&&await F6t(200*Math.pow(2,a-1)),this._debug(r,"refreshing attempt",a),await pl(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:WN})),(a,i)=>{const l=200*Math.pow(2,a);return i&&Ebe(i)&&Date.now()+l-n{try{await o.callback(t,r)}catch(c){i.push(c)}});if(await Promise.all(l),i.length>0){for(let o=0;othis._autoRefreshTokenTick(),X6);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((n.expires_at*1e3-t)/X6);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${X6}ms, refresh threshold is ${DNe} ticks`),a<=DNe&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof Utt)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ub()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const r=`#_onVisibilityChanged(${t})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,r,n){const a=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&a.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&a.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[i,l]=await p6(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(l)}`});a.push(o.toString())}if(n!=null&&n.queryParams){const i=new URLSearchParams(n.queryParams);a.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&a.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${t}?${a.join("&")}`}async _unenroll(t){try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await pl(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(Ao(r))return{data:null,error:r};throw r}}async _enroll(t){try{return await this._useSession(async r=>{var n,a;const{data:i,error:l}=r;if(l)return{data:null,error:l};const o=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:{issuer:t.issuer}),{data:c,error:d}=await pl(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return d?{data:null,error:d}:(t.factorType==="totp"&&(!((a=c==null?void 0:c.totp)===null||a===void 0)&&a.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(r){if(Ao(r))return{data:null,error:r};throw r}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{data:null,error:i};const{data:l,error:o}=await pl(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),{data:l,error:o})})}catch(r){if(Ao(r))return{data:null,error:r};throw r}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await pl(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:{channel:t.channel},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(Ao(r))return{data:null,error:r};throw r}})}async _challengeAndVerify(t){const{data:r,error:n}=await this._challenge({factorId:t.factorId});return n?{data:null,error:n}:await this._verify({factorId:t.factorId,challengeId:r.id,code:t.code})}async _listFactors(){const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const n=(t==null?void 0:t.factors)||[],a=n.filter(l=>l.factor_type==="totp"&&l.status==="verified"),i=n.filter(l=>l.factor_type==="phone"&&l.status==="verified");return{data:{all:n,totp:a,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var r,n;const{data:{session:a},error:i}=t;if(i)return{data:null,error:i};if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Abe(a.access_token);let o=null;l.aal&&(o=l.aal);let c=o;((n=(r=a.user.factors)===null||r===void 0?void 0:r.filter(m=>m.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(c="aal2");const u=l.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(t,r={keys:[]}){let n=r.keys.find(l=>l.kid===t);if(n||(n=this.jwks.keys.find(l=>l.kid===t),n&&this.jwks_cached_at+j6t>Date.now()))return n;const{data:a,error:i}=await pl(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 c7("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),n=a.keys.find(l=>l.kid===t),!n)throw new c7("No matching signing key found in JWKS");return n}async getClaims(t,r={keys:[]}){try{let n=t;if(!n){const{data:x,error:y}=await this.getSession();if(y||!x.session)return{data:null,error:y};n=x.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=Abe(n);if(G6t(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:x}=await this.getUser(n);if(x)throw x;return{data:{claims:i,header:a,signature:l},error:null}}const d=W6t(a.alg),u=await this.fetchJwk(a.kid,r),m=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,m,l,P6t(`${o}.${c}`)))throw new c7("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(n){if(Ao(n))return{data:null,error:n};throw n}}}j9.nextInstanceID=0;const cIt=j9;class dIt extends cIt{constructor(t){super(t)}}var uIt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(u){try{d(n.next(u))}catch(m){l(m)}}function c(u){try{d(n.throw(u))}catch(m){l(m)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class hIt{constructor(t,r,n){var a,i,l;if(this.supabaseUrl=t,this.supabaseKey=r,!t)throw new Error("supabaseUrl is required.");if(!r)throw new Error("supabaseKey is required.");const o=g6t(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:c6t,realtime:u6t,auth:Object.assign(Object.assign({},d6t),{storageKey:d}),global:l6t},m=y6t(n??{},u);this.storageKey=(a=m.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=m.global.headers)!==null&&i!==void 0?i:{},m.accessToken?(this.accessToken=m.accessToken,this.auth=new Proxy({},{get:(f,x)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(x)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=m.auth)!==null&&l!==void 0?l:{},this.headers,m.global.fetch),this.fetch=p6t(r,this._getAccessToken.bind(this),m.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},m.realtime)),this.rest=new MMt(new URL("rest/v1",c).href,{headers:this.headers,schema:m.db.schema,fetch:this.fetch}),m.accessToken||this._listenForAuthEvents()}get functions(){return new oMt(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new a6t(this.storageUrl.href,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,r={},n={}){return this.rest.rpc(t,r,n)}channel(t,r={config:{}}){return this.realtime.channel(t,r)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,r;return uIt(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:n}=yield this.auth.getSession();return(r=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&r!==void 0?r:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:a,storageKey:i,flowType:l,lock:o,debug:c},d,u){const m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new dIt({url:this.authUrl.href,headers:Object.assign(Object.assign({},m),d),storageKey:i,autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:a,flowType:l,lock:o,debug:c,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(t){return new HMt(this.realtimeUrl.href,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,n)=>{this._handleTokenChanged(r,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(t,r,n){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:t==="SIGNED_OUT"&&(this.realtime.setAuth(),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const mIt=(s,t,r)=>new hIt(s,t,r),fIt="https://relzejiswnotikjgvjhz.supabase.co",pIt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",U=mIt(fIt,pIt,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),xIt=Object.freeze(Object.defineProperty({__proto__:null,supabase:U},Symbol.toStringTag,{value:"Module"})),qtt=k.createContext(void 0),gIt=({children:s})=>{const[t,r]=k.useState(null),[n,a]=k.useState(null),[i,l]=k.useState(!0),[o,c]=k.useState(!0),[d,u]=k.useState(!1),[m,f]=k.useState(!1),[x,y]=k.useState(!1),[_,b]=k.useState(null),[j,N]=k.useState([]),[C,A]=k.useState(null),E=k.useRef(null),D=k.useRef(!1),R=k.useRef(!1),F=qr(),O=()=>{u(!1),f(!1),y(!1),b(null),N([]),A(null),E.current=null,D.current=!1},B=async W=>{if(!(D.current&&E.current===W)&&!R.current){R.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",W);const[{data:te,error:ne},{data:ae,error:ue},{data:me,error:de}]=await Promise.all([U.rpc("has_role",{_user_id:W,_role:"admin"}),U.rpc("has_role",{_user_id:W,_role:"brokerage_manager"}),U.rpc("has_role",{_user_id:W,_role:"coach"})]);if(ne||ue)console.error("Role RPC errors:",{isAdminError:ne,isBrokerError:ue,isCoachError:de}),u(!1),f(!1),y(!1);else{const xe=!!te,Ee=!!ae,Me=!!me;console.log("RPC roles result:",{adminValue:xe,brokerValue:Ee,coachValue:Me}),u(xe),f(Ee),y(Me)}const{data:fe,error:je}=await U.from("profiles").select("brokerage_id").eq("id",W).single();if(b(!je&&fe?fe.brokerage_id:null),ae){console.log("Fetching managed brokerages for user:",W);const{data:xe,error:Ee}=await U.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",W);if(console.log("Managed brokerage assignments result:",{assignments:xe,assignmentsError:Ee}),Ee||!xe){console.error("Error fetching managed brokerage assignments:",Ee),N([]);return}const Me=Array.from(new Set(xe.map(Ve=>Ve.brokerage_id).filter(Boolean)));if(Me.length===0){N([]);return}const{data:Oe,error:Ie}=await U.from("brokerages").select("id, name").in("id",Me);if(console.log("Managed brokerages details result:",{brokeragesData:Oe,brokeragesError:Ie}),Ie||!Oe){console.error("Error fetching managed brokerages details:",Ie),N([]);return}const ze=Oe.map(Ve=>({id:Ve.id,name:Ve.name})).sort((Ve,Le)=>Me.indexOf(Ve.id)-Me.indexOf(Le.id));console.log("Parsed managed brokerages:",ze),N(ze),ze.length>0&&A(Ve=>Ve??ze[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),N([]);E.current=W,D.current=!0}catch(te){console.error("Unexpected error in checkRoles:",te),O()}finally{R.current=!1,c(!1)}}};k.useEffect(()=>{let W=!0,te=!1;const ne=()=>{!W||te||(te=!0,l(!1))},{data:{subscription:ae}}=U.auth.onAuthStateChange((de,fe)=>{console.log("Auth event:",de),W&&(a(fe),r((fe==null?void 0:fe.user)??null),ne(),de==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{F("/profile?reset=true")},100)),fe!=null&&fe.user?(!D.current||E.current!==fe.user.id)&&setTimeout(()=>{B(fe.user.id)},0):(O(),c(!1)))}),ue=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),ne()},4e3);return(async()=>{try{const{data:{session:de}}=await U.auth.getSession();if(!W)return;a(de),r((de==null?void 0:de.user)??null),de!=null&&de.user?await B(de.user.id):O()}catch(de){console.error("Error restoring auth session:",de),W&&(a(null),r(null),O())}finally{ne()}})(),()=>{W=!1,window.clearTimeout(ue),ae.unsubscribe()}},[]);const K=async(W,te)=>{const{error:ne}=await U.auth.signInWithPassword({email:W,password:te});if(ne)throw he.error(ne.message),ne;he.success("Welcome back!")},Z=async(W,te,ne)=>{var fe;const ae=`${window.location.origin}/dashboard`,ue=localStorage.getItem("levelup_referral_code")||null,{data:me,error:de}=await U.auth.signUp({email:W,password:te,options:{emailRedirectTo:ae,data:{name:ne,referred_by_code:ue}}});if(de)throw he.error(de.message),de;if(ue&&((fe=me.user)!=null&&fe.id))try{await U.from("profiles").update({referred_by_code:ue}).eq("id",me.user.id),localStorage.removeItem("levelup_referral_code")}catch(je){console.warn("Failed to attach referral code to profile",je)}he.success("Account created! Welcome to LevelUp."),F("/dashboard")},Q=async()=>{try{const{data:{session:W}}=await U.auth.getSession();if(W){const{error:te}=await U.auth.signOut();te?te.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",te.message):(console.error("Sign out error:",te),he.error(te.message)):he.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),a(null),u(!1),f(!1),b(null),N([]),A(null),F("/auth")}catch(W){console.error("Unexpected sign out error:",W),F("/auth")}};return e.jsx(qtt.Provider,{value:{user:t,session:n,loading:i,rolesLoading:o,signIn:K,signUp:Z,signOut:Q,isAdmin:d,isBrokerageManager:m,isCoach:x,brokerageId:_,managedBrokerages:j,selectedBrokerageId:C,setSelectedBrokerageId:A},children:s})},Cs=()=>{const s=k.useContext(qtt);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},Vtt=k.createContext({onlineUsers:[],totalOnline:0}),yIt=async s=>{try{const{data:t}=await U.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:r}=U.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return r.publicUrl}}catch{}},vIt=({children:s})=>{const{user:t,brokerageId:r,isAdmin:n}=Cs(),[a,i]=k.useState([]),[l,o]=k.useState(null);k.useEffect(()=>{if(!t)return;let d=!1;U.auth.getSession().then(({data:m})=>{var x;const f=(x=m.session)==null?void 0:x.access_token;if(f)try{U.realtime.setAuth(f)}catch{}});const u=U.channel("app-presence-v2",{config:{presence:{key:t.id},broadcast:{self:!0}}});return u.on("presence",{event:"sync"},()=>{const m=u.presenceState(),f=[];Object.entries(m).forEach(([x,y])=>{if(y&&y.length>0){const _=y[0];f.push({id:x,name:_.name||"Unknown",avatarUrl:_.avatarUrl,brokerageId:_.brokerageId,onlineSince:_.onlineSince})}}),console.log("[Presence] sync, users:",f.length,f),i(f)}).on("presence",{event:"join"},({key:m,newPresences:f})=>{console.log("[Presence] join",m,f)}).on("presence",{event:"leave"},({key:m})=>{console.log("[Presence] leave",m)}).subscribe(async(m,f)=>{var x;if(console.log("[Presence] subscribe status:",m,f),m==="SUBSCRIBED"&&!d){const{data:y}=await U.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),_=await yIt(t.id),b=await u.track({name:(y==null?void 0:y.name)||((x=t.email)==null?void 0:x.split("@")[0])||"User",avatarUrl:_,brokerageId:y==null?void 0:y.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",b)}}),o(u),()=>{d=!0;try{u.untrack()}catch{}U.removeChannel(u)}},[t==null?void 0:t.id]);const c=a.filter(d=>d.id===(t==null?void 0:t.id)?!1:!!(n||r&&d.brokerageId===r||!r&&!d.brokerageId));return e.jsx(Vtt.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},Htt=()=>k.useContext(Vtt),Gtt=k.createContext(void 0),hC="levelup_admin_session",DN="levelup_impersonation",Mbe="levelup_impersonation_return",bIt=({children:s})=>{const[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(!1);k.useEffect(()=>{const d=sessionStorage.getItem(DN);if(d)try{const u=JSON.parse(d);r(!0),a(u)}catch{sessionStorage.removeItem(DN)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:m}}=await U.auth.getSession();if(!m)return he.error("No active session found"),!1;const f={access_token:m.access_token,refresh_token:m.refresh_token};sessionStorage.setItem(hC,JSON.stringify(f)),u&&sessionStorage.setItem(Mbe,u);const x=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m.access_token}`},body:JSON.stringify({targetUserId:d})}),y=await x.json();if(!x.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(DN,JSON.stringify(_)),y.method==="session"){const{error:b}=await U.auth.setSession({access_token:y.access_token,refresh_token:y.refresh_token});if(b)throw console.error("Set session error:",b),sessionStorage.removeItem(hC),sessionStorage.removeItem(DN),new Error("Failed to establish impersonation session")}else{const b=y.type||"recovery",{error:j}=await U.auth.verifyOtp({token_hash:y.token_hash,type:b});if(j)throw console.error("Verify OTP error:",j),sessionStorage.removeItem(hC),sessionStorage.removeItem(DN),new Error("Failed to establish impersonation session")}return r(!0),a(_),he.success(`Now viewing as ${_.name}`),window.location.href="/dashboard",!0}catch(m){return console.error("Impersonation error:",m),he.error(m.message||"Failed to impersonate user"),sessionStorage.removeItem(hC),sessionStorage.removeItem(DN),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(hC);if(!d){await U.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await U.auth.signOut();const{error:m}=await U.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(hC),sessionStorage.removeItem(DN),m){console.error("Failed to restore admin session:",m),he.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),a(null),he.success("Returned to your account");const f=sessionStorage.getItem(Mbe)||"/admin/members";sessionStorage.removeItem(Mbe),window.location.href=f}catch(d){console.error("Stop impersonation error:",d),he.error("Failed to restore admin session"),sessionStorage.removeItem(hC),sessionStorage.removeItem(DN),window.location.href="/auth"}finally{l(!1)}};return e.jsx(Gtt.Provider,{value:{isImpersonating:t,impersonatedUser:n,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},Rxe=()=>{const s=k.useContext(Gtt);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},lL=WA("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"}}),q=k.forwardRef(({className:s,variant:t,size:r,asChild:n=!1,...a},i)=>{const l=n?i5e:"button";return e.jsx(l,{className:zt(lL({variant:t,size:r,className:s})),ref:i,...a})});q.displayName="Button";const _It=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:r,isLoading:n}=Rxe();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(du,{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(q,{size:"sm",variant:"secondary",onClick:r,disabled:n,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:n?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx($r,{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"})]})})]})})},Wtt=k.createContext(void 0),g6="levelup_acting_as",nq="levelup_acting_as_self",wIt=({children:s})=>{const{user:t}=Cs(),[r,n]=k.useState(!1),[a,i]=k.useState([]),[l,o]=k.useState(null),[c,d]=k.useState({}),[u,m]=k.useState(!0),[f,x]=k.useState(()=>sessionStorage.getItem(nq)==="true");k.useEffect(()=>{if(!(t!=null&&t.id)){n(!1),i([]),o(null),d({}),m(!1);return}(async()=>{m(!0);try{const{data:C}=await U.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!C){n(!1),i([]),o(null),d({}),m(!1);return}n(!0);const{data:A,error:E}=await U.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(E||!A||A.length===0){i([]),m(!1);return}const D=A.map(O=>O.agent_id),{data:R}=await U.from("profiles").select("id, name, email, avatar_url").in("id",D),F=(R||[]).map(O=>({id:O.id,name:O.name||O.email||"Unknown",email:O.email||"",avatar_url:O.avatar_url}));if(i(F),sessionStorage.getItem(nq)==="true")x(!0),o(null),d({});else{const O=sessionStorage.getItem(g6);if(O){const B=F.find(K=>K.id===O);if(B){o(B);const K=A.find(Z=>Z.agent_id===O);d((K==null?void 0:K.permissions)||{})}else if(F.length>0){o(F[0]);const K=A.find(Z=>Z.agent_id===F[0].id);d((K==null?void 0:K.permissions)||{}),sessionStorage.setItem(g6,F[0].id)}}else if(F.length>0){o(F[0]);const B=A.find(K=>K.agent_id===F[0].id);d((B==null?void 0:B.permissions)||{}),sessionStorage.setItem(g6,F[0].id)}}}catch(C){console.error("Error loading assistant data:",C)}finally{m(!1)}})()},[t==null?void 0:t.id]);const y=N=>{o(N),x(!1),sessionStorage.removeItem(nq),N?(sessionStorage.setItem(g6,N.id),U.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",N.id).single().then(({data:C})=>{d((C==null?void 0:C.permissions)||{})})):(sessionStorage.removeItem(g6),d({}))},_=()=>{x(!0),o(null),d({}),sessionStorage.setItem(nq,"true"),sessionStorage.removeItem(g6)},b=N=>!r||f?!0:c[N]===!0,j=r&&l&&!f?l.id:(t==null?void 0:t.id)||null;return e.jsx(Wtt.Provider,{value:{isAssistant:r,assignedAgents:a,actingAsAgent:l,setActingAsAgent:y,effectiveUserId:j,permissions:c,hasPermission:b,isLoading:u,isActingAsSelf:f,setActingAsSelf:_},children:s})},D5e=()=>{const s=k.useContext(Wtt);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},xa=()=>{const{effectiveUserId:s}=D5e();return s};var Ktt={exports:{}},Ytt={};/** * @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 cL=k;function jIt(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var NIt=typeof Object.is=="function"?Object.is:jIt,kIt=cL.useState,SIt=cL.useEffect,CIt=cL.useLayoutEffect,TIt=cL.useDebugValue;function EIt(s,t){var r=t(),n=kIt({inst:{value:r,getSnapshot:t}}),a=n[0].inst,i=n[1];return CIt(function(){a.value=r,a.getSnapshot=t,Ibe(a)&&i({inst:a})},[s,r,t]),SIt(function(){return Ibe(a)&&i({inst:a}),s(function(){Ibe(a)&&i({inst:a})})},[s]),TIt(r),r}function Ibe(s){var t=s.getSnapshot;s=s.value;try{var r=t();return!NIt(s,r)}catch{return!0}}function AIt(s,t){return t()}var MIt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?AIt:EIt;Ytt.useSyncExternalStore=cL.useSyncExternalStore!==void 0?cL.useSyncExternalStore:MIt;Ktt.exports=Ytt;var IIt=Ktt.exports;function PIt(){return IIt.useSyncExternalStore(LIt,()=>!0,()=>!1)}function LIt(){return()=>{}}var R5e="Avatar",[DIt,Enr]=bu(R5e),[RIt,Ztt]=DIt(R5e),Xtt=k.forwardRef((s,t)=>{const{__scopeAvatar:r,...n}=s,[a,i]=k.useState("idle");return e.jsx(RIt,{scope:r,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(Yn.span,{...n,ref:t})})});Xtt.displayName=R5e;var Qtt="AvatarImage",Jtt=k.forwardRef((s,t)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:a=()=>{},...i}=s,l=Ztt(Qtt,r),o=OIt(n,i),c=$u(d=>{a(d),l.onImageLoadingStatusChange(d)});return Gu(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(Yn.img,{...i,ref:t,src:n}):null});Jtt.displayName=Qtt;var est="AvatarFallback",tst=k.forwardRef((s,t)=>{const{__scopeAvatar:r,delayMs:n,...a}=s,i=Ztt(est,r),[l,o]=k.useState(n===void 0);return k.useEffect(()=>{if(n!==void 0){const c=window.setTimeout(()=>o(!0),n);return()=>window.clearTimeout(c)}},[n]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(Yn.span,{...a,ref:t}):null});tst.displayName=est;function NFe(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function OIt(s,{referrerPolicy:t,crossOrigin:r}){const n=PIt(),a=k.useRef(null),i=n?(a.current||(a.current=new window.Image),a.current):null,[l,o]=k.useState(()=>NFe(i,s));return Gu(()=>{o(NFe(i,s))},[i,s]),Gu(()=>{const c=m=>()=>{o(m)};if(!i)return;const d=c("loaded"),u=c("error");return i.addEventListener("load",d),i.addEventListener("error",u),t&&(i.referrerPolicy=t),typeof r=="string"&&(i.crossOrigin=r),()=>{i.removeEventListener("load",d),i.removeEventListener("error",u)}},[i,r,t]),l}var sst=Xtt,rst=Jtt,nst=tst;const Wn=k.forwardRef(({className:s,...t},r)=>e.jsx(sst,{ref:r,className:zt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Wn.displayName=sst.displayName;const Xa=k.forwardRef(({className:s,...t},r)=>e.jsx(rst,{ref:r,className:zt("aspect-square h-full w-full",s),...t}));Xa.displayName=rst.displayName;const Kn=k.forwardRef(({className:s,...t},r)=>e.jsx(nst,{ref:r,className:zt("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));Kn.displayName=nst.displayName;const FIt=WA("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 Xe({className:s,variant:t,...r}){return e.jsx("div",{className:zt(FIt({variant:t}),s),...r})}var zIt=k.createContext(void 0);function ZS(s){const t=k.useContext(zIt);return s||t||"ltr"}var Pbe=0;function Oxe(){k.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??kFe()),document.body.insertAdjacentElement("beforeend",s[1]??kFe()),Pbe++,()=>{Pbe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Pbe--}},[])}function kFe(){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 Lbe="focusScope.autoFocusOnMount",Dbe="focusScope.autoFocusOnUnmount",SFe={bubbles:!1,cancelable:!0},BIt="FocusScope",cB=k.forwardRef((s,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=k.useState(null),d=$u(a),u=$u(i),m=k.useRef(null),f=_i(t,_=>c(_)),x=k.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;k.useEffect(()=>{if(n){let _=function(C){if(x.paused||!o)return;const A=C.target;o.contains(A)?m.current=A:KN(m.current,{select:!0})},b=function(C){if(x.paused||!o)return;const A=C.relatedTarget;A!==null&&(o.contains(A)||KN(m.current,{select:!0}))},j=function(C){if(document.activeElement===document.body)for(const E of C)E.removedNodes.length>0&&KN(o)};document.addEventListener("focusin",_),document.addEventListener("focusout",b);const N=new MutationObserver(j);return o&&N.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",_),document.removeEventListener("focusout",b),N.disconnect()}}},[n,o,x.paused]),k.useEffect(()=>{if(o){TFe.add(x);const _=document.activeElement;if(!o.contains(_)){const j=new CustomEvent(Lbe,SFe);o.addEventListener(Lbe,d),o.dispatchEvent(j),j.defaultPrevented||($It(GIt(ast(o)),{select:!0}),document.activeElement===_&&KN(o))}return()=>{o.removeEventListener(Lbe,d),setTimeout(()=>{const j=new CustomEvent(Dbe,SFe);o.addEventListener(Dbe,u),o.dispatchEvent(j),j.defaultPrevented||KN(_??document.body,{select:!0}),o.removeEventListener(Dbe,u),TFe.remove(x)},0)}}},[o,d,u,x]);const y=k.useCallback(_=>{if(!r&&!n||x.paused)return;const b=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,j=document.activeElement;if(b&&j){const N=_.currentTarget,[C,A]=UIt(N);C&&A?!_.shiftKey&&j===A?(_.preventDefault(),r&&KN(C,{select:!0})):_.shiftKey&&j===C&&(_.preventDefault(),r&&KN(A,{select:!0})):j===N&&_.preventDefault()}},[r,n,x.paused]);return e.jsx(Yn.div,{tabIndex:-1,...l,ref:f,onKeyDown:y})});cB.displayName=BIt;function $It(s,{select:t=!1}={}){const r=document.activeElement;for(const n of s)if(KN(n,{select:t}),document.activeElement!==r)return}function UIt(s){const t=ast(s),r=CFe(t,s),n=CFe(t.reverse(),s);return[r,n]}function ast(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function CFe(s,t){for(const r of s)if(!qIt(r,{upTo:t}))return r}function qIt(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 VIt(s){return s instanceof HTMLInputElement&&"select"in s}function KN(s,{select:t=!1}={}){if(s&&s.focus){const r=document.activeElement;s.focus({preventScroll:!0}),s!==r&&VIt(s)&&t&&s.select()}}var TFe=HIt();function HIt(){let s=[];return{add(t){const r=s[0];t!==r&&(r==null||r.pause()),s=EFe(s,t),s.unshift(t)},remove(t){var r;s=EFe(s,t),(r=s[0])==null||r.resume()}}}function EFe(s,t){const r=[...s],n=r.indexOf(t);return n!==-1&&r.splice(n,1),r}function GIt(s){return s.filter(t=>t.tagName!=="A")}var Rbe="rovingFocusGroup.onEntryFocus",WIt={bubbles:!1,cancelable:!0},dB="RovingFocusGroup",[FNe,ist,KIt]=eB(dB),[YIt,XS]=bu(dB,[KIt]),[ZIt,XIt]=YIt(dB),ost=k.forwardRef((s,t)=>e.jsx(FNe.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(FNe.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(QIt,{...s,ref:t})})}));ost.displayName=dB;var QIt=k.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...m}=s,f=k.useRef(null),x=_i(t,f),y=ZS(i),[_,b]=df({prop:l,defaultProp:o??null,onChange:c,caller:dB}),[j,N]=k.useState(!1),C=$u(d),A=ist(r),E=k.useRef(!1),[D,R]=k.useState(0);return k.useEffect(()=>{const F=f.current;if(F)return F.addEventListener(Rbe,C),()=>F.removeEventListener(Rbe,C)},[C]),e.jsx(ZIt,{scope:r,orientation:n,dir:y,loop:a,currentTabStopId:_,onItemFocus:k.useCallback(F=>b(F),[b]),onItemShiftTab:k.useCallback(()=>N(!0),[]),onFocusableItemAdd:k.useCallback(()=>R(F=>F+1),[]),onFocusableItemRemove:k.useCallback(()=>R(F=>F-1),[]),children:e.jsx(Yn.div,{tabIndex:j||D===0?-1:0,"data-orientation":n,...m,ref:x,style:{outline:"none",...s.style},onMouseDown:dn(s.onMouseDown,()=>{E.current=!0}),onFocus:dn(s.onFocus,F=>{const O=!E.current;if(F.target===F.currentTarget&&O&&!j){const B=new CustomEvent(Rbe,WIt);if(F.currentTarget.dispatchEvent(B),!B.defaultPrevented){const K=A().filter(ne=>ne.focusable),Z=K.find(ne=>ne.active),Q=K.find(ne=>ne.id===_),te=[Z,Q,...K].filter(Boolean).map(ne=>ne.ref.current);dst(te,u)}}E.current=!1}),onBlur:dn(s.onBlur,()=>N(!1))})})}),lst="RovingFocusGroupItem",cst=k.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=jm(),d=i||c,u=XIt(lst,r),m=u.currentTabStopId===d,f=ist(r),{onFocusableItemAdd:x,onFocusableItemRemove:y,currentTabStopId:_}=u;return k.useEffect(()=>{if(n)return x(),()=>y()},[n,x,y]),e.jsx(FNe.ItemSlot,{scope:r,id:d,focusable:n,active:a,children:e.jsx(Yn.span,{tabIndex:m?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:dn(s.onMouseDown,b=>{n?u.onItemFocus(d):b.preventDefault()}),onFocus:dn(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:dn(s.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){u.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const j=tPt(b,u.orientation,u.dir);if(j!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let C=f().filter(A=>A.focusable).map(A=>A.ref.current);if(j==="last")C.reverse();else if(j==="prev"||j==="next"){j==="prev"&&C.reverse();const A=C.indexOf(b.currentTarget);C=u.loop?sPt(C,A+1):C.slice(A+1)}setTimeout(()=>dst(C))}}),children:typeof l=="function"?l({isCurrentTabStop:m,hasTabStop:_!=null}):l})})});cst.displayName=lst;var JIt={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ePt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function tPt(s,t,r){const n=ePt(s.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return JIt[n]}function dst(s,t=!1){const r=document.activeElement;for(const n of s)if(n===r||(n.focus({preventScroll:t}),document.activeElement!==r))return}function sPt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}var Fxe=ost,zxe=cst,rPt=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},y6=new WeakMap,aq=new WeakMap,iq={},Obe=0,ust=function(s){return s&&(s.host||ust(s.parentNode))},nPt=function(s,t){return t.map(function(r){if(s.contains(r))return r;var n=ust(r);return n&&s.contains(n)?n:(console.error("aria-hidden",r,"in not contained inside",s,". Doing nothing"),null)}).filter(function(r){return!!r})},aPt=function(s,t,r,n){var a=nPt(t,Array.isArray(s)?s:[s]);iq[r]||(iq[r]=new WeakMap);var i=iq[r],l=[],o=new Set,c=new Set(a),d=function(m){!m||o.has(m)||(o.add(m),d(m.parentNode))};a.forEach(d);var u=function(m){!m||c.has(m)||Array.prototype.forEach.call(m.children,function(f){if(o.has(f))u(f);else try{var x=f.getAttribute(n),y=x!==null&&x!=="false",_=(y6.get(f)||0)+1,b=(i.get(f)||0)+1;y6.set(f,_),i.set(f,b),l.push(f),_===1&&y&&aq.set(f,!0),b===1&&f.setAttribute(r,"true"),y||f.setAttribute(n,"true")}catch(j){console.error("aria-hidden: cannot operate on ",f,j)}})};return u(t),o.clear(),Obe++,function(){l.forEach(function(m){var f=y6.get(m)-1,x=i.get(m)-1;y6.set(m,f),i.set(m,x),f||(aq.has(m)||m.removeAttribute(n),aq.delete(m)),x||m.removeAttribute(r)}),Obe--,Obe||(y6=new WeakMap,y6=new WeakMap,aq=new WeakMap,iq={})}},Bxe=function(s,t,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(s)?s:[s]),a=rPt(s);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live]"))),aPt(n,a,r,"aria-hidden")):function(){return null}},a_=function(){return a_=Object.assign||function(t){for(var r,n=1,a=arguments.length;n"u")return wPt;var t=jPt(s),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},kPt=pst(),yP="data-scroll-locked",SPt=function(s,t,r,n){var a=s.left,i=s.top,l=s.right,o=s.gap;return r===void 0&&(r="margin"),` .`.concat(oPt,` { overflow: hidden `).concat(n,`; padding-right: `).concat(o,"px ").concat(n,`; } body[`).concat(yP,`] { overflow: hidden `).concat(n,`; overscroll-behavior: contain; `).concat([t&&"position: relative ".concat(n,";"),r==="margin"&&` padding-left: `.concat(a,`px; padding-top: `).concat(i,`px; padding-right: `).concat(l,`px; margin-left:0; margin-top:0; margin-right: `).concat(o,"px ").concat(n,`; `),r==="padding"&&"padding-right: ".concat(o,"px ").concat(n,";")].filter(Boolean).join(""),` } .`).concat(Due,` { right: `).concat(o,"px ").concat(n,`; } .`).concat(Rue,` { margin-right: `).concat(o,"px ").concat(n,`; } .`).concat(Due," .").concat(Due,` { right: 0 `).concat(n,`; } .`).concat(Rue," .").concat(Rue,` { margin-right: 0 `).concat(n,`; } body[`).concat(yP,`] { `).concat(lPt,": ").concat(o,`px; } `)},MFe=function(){var s=parseInt(document.body.getAttribute(yP)||"0",10);return isFinite(s)?s:0},CPt=function(){k.useEffect(function(){return document.body.setAttribute(yP,(MFe()+1).toString()),function(){var s=MFe()-1;s<=0?document.body.removeAttribute(yP):document.body.setAttribute(yP,s.toString())}},[])},TPt=function(s){var t=s.noRelative,r=s.noImportant,n=s.gapMode,a=n===void 0?"margin":n;CPt();var i=k.useMemo(function(){return NPt(a)},[a]);return k.createElement(kPt,{styles:SPt(i,!t,a,r?"":"!important")})},zNe=!1;if(typeof window<"u")try{var oq=Object.defineProperty({},"passive",{get:function(){return zNe=!0,!0}});window.addEventListener("test",oq,oq),window.removeEventListener("test",oq,oq)}catch{zNe=!1}var v6=zNe?{passive:!1}:!1,EPt=function(s){return s.tagName==="TEXTAREA"},xst=function(s,t){if(!(s instanceof Element))return!1;var r=window.getComputedStyle(s);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!EPt(s)&&r[t]==="visible")},APt=function(s){return xst(s,"overflowY")},MPt=function(s){return xst(s,"overflowX")},IFe=function(s,t){var r=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=gst(s,n);if(a){var i=yst(s,n),l=i[1],o=i[2];if(l>o)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},IPt=function(s){var t=s.scrollTop,r=s.scrollHeight,n=s.clientHeight;return[t,r,n]},PPt=function(s){var t=s.scrollLeft,r=s.scrollWidth,n=s.clientWidth;return[t,r,n]},gst=function(s,t){return s==="v"?APt(t):MPt(t)},yst=function(s,t){return s==="v"?IPt(t):PPt(t)},LPt=function(s,t){return s==="h"&&t==="rtl"?-1:1},DPt=function(s,t,r,n,a){var i=LPt(s,window.getComputedStyle(t).direction),l=i*n,o=r.target,c=t.contains(o),d=!1,u=l>0,m=0,f=0;do{if(!o)break;var x=yst(s,o),y=x[0],_=x[1],b=x[2],j=_-b-i*y;(y||j)&&gst(s,o)&&(m+=j,f+=y);var N=o.parentNode;o=N&&N.nodeType===Node.DOCUMENT_FRAGMENT_NODE?N.host:N}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&(Math.abs(m)<1||!a)||!u&&(Math.abs(f)<1||!a))&&(d=!0),d},lq=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},PFe=function(s){return[s.deltaX,s.deltaY]},LFe=function(s){return s&&"current"in s?s.current:s},RPt=function(s,t){return s[0]===t[0]&&s[1]===t[1]},OPt=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},FPt=0,b6=[];function zPt(s){var t=k.useRef([]),r=k.useRef([0,0]),n=k.useRef(),a=k.useState(FPt++)[0],i=k.useState(pst)[0],l=k.useRef(s);k.useEffect(function(){l.current=s},[s]),k.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var _=iPt([s.lockRef.current],(s.shards||[]).map(LFe),!0).filter(Boolean);return _.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),_.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=k.useCallback(function(_,b){if("touches"in _&&_.touches.length===2||_.type==="wheel"&&_.ctrlKey)return!l.current.allowPinchZoom;var j=lq(_),N=r.current,C="deltaX"in _?_.deltaX:N[0]-j[0],A="deltaY"in _?_.deltaY:N[1]-j[1],E,D=_.target,R=Math.abs(C)>Math.abs(A)?"h":"v";if("touches"in _&&R==="h"&&D.type==="range")return!1;var F=IFe(R,D);if(!F)return!0;if(F?E=R:(E=R==="v"?"h":"v",F=IFe(R,D)),!F)return!1;if(!n.current&&"changedTouches"in _&&(C||A)&&(n.current=E),!E)return!0;var O=n.current||E;return DPt(O,b,_,O==="h"?C:A,!0)},[]),c=k.useCallback(function(_){var b=_;if(!(!b6.length||b6[b6.length-1]!==i)){var j="deltaY"in b?PFe(b):lq(b),N=t.current.filter(function(E){return E.name===b.type&&(E.target===b.target||b.target===E.shadowParent)&&RPt(E.delta,j)})[0];if(N&&N.should){b.cancelable&&b.preventDefault();return}if(!N){var C=(l.current.shards||[]).map(LFe).filter(Boolean).filter(function(E){return E.contains(b.target)}),A=C.length>0?o(b,C[0]):!l.current.noIsolation;A&&b.cancelable&&b.preventDefault()}}},[]),d=k.useCallback(function(_,b,j,N){var C={name:_,delta:b,target:j,should:N,shadowParent:BPt(j)};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(A){return A!==C})},1)},[]),u=k.useCallback(function(_){r.current=lq(_),n.current=void 0},[]),m=k.useCallback(function(_){d(_.type,PFe(_),_.target,o(_,s.lockRef.current))},[]),f=k.useCallback(function(_){d(_.type,lq(_),_.target,o(_,s.lockRef.current))},[]);k.useEffect(function(){return b6.push(i),s.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:f}),document.addEventListener("wheel",c,v6),document.addEventListener("touchmove",c,v6),document.addEventListener("touchstart",u,v6),function(){b6=b6.filter(function(_){return _!==i}),document.removeEventListener("wheel",c,v6),document.removeEventListener("touchmove",c,v6),document.removeEventListener("touchstart",u,v6)}},[]);var x=s.removeScrollBar,y=s.inert;return k.createElement(k.Fragment,null,y?k.createElement(i,{styles:OPt(a)}):null,x?k.createElement(TPt,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function BPt(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const $Pt=pPt(fst,zPt);var uB=k.forwardRef(function(s,t){return k.createElement($xe,a_({},s,{ref:t,sideCar:$Pt}))});uB.classNames=$xe.classNames;var BNe=["Enter"," "],UPt=["ArrowDown","PageUp","Home"],vst=["ArrowUp","PageDown","End"],qPt=[...UPt,...vst],VPt={ltr:[...BNe,"ArrowRight"],rtl:[...BNe,"ArrowLeft"]},HPt={ltr:["ArrowLeft"],rtl:["ArrowRight"]},hB="Menu",[N9,GPt,WPt]=eB(hB),[YA,bst]=bu(hB,[WPt,Q_,XS]),Uxe=Q_(),_st=XS(),[KPt,ZA]=YA(hB),[YPt,mB]=YA(hB),wst=s=>{const{__scopeMenu:t,open:r=!1,children:n,dir:a,onOpenChange:i,modal:l=!0}=s,o=Uxe(t),[c,d]=k.useState(null),u=k.useRef(!1),m=$u(i),f=ZS(a);return k.useEffect(()=>{const x=()=>{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",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",y,{capture:!0}),document.removeEventListener("pointermove",y,{capture:!0})}},[]),e.jsx(nB,{...o,children:e.jsx(KPt,{scope:t,open:r,onOpenChange:m,content:c,onContentChange:d,children:e.jsx(YPt,{scope:t,onClose:k.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:u,dir:f,modal:l,children:n})})})};wst.displayName=hB;var ZPt="MenuAnchor",O5e=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s,a=Uxe(r);return e.jsx(x8,{...a,...n,ref:t})});O5e.displayName=ZPt;var F5e="MenuPortal",[XPt,jst]=YA(F5e,{forceMount:void 0}),Nst=s=>{const{__scopeMenu:t,forceMount:r,children:n,container:a}=s,i=ZA(F5e,t);return e.jsx(XPt,{scope:t,forceMount:r,children:e.jsx(yh,{present:r||i.open,children:e.jsx(h8,{asChild:!0,container:a,children:n})})})};Nst.displayName=F5e;var tv="MenuContent",[QPt,z5e]=YA(tv),kst=k.forwardRef((s,t)=>{const r=jst(tv,s.__scopeMenu),{forceMount:n=r.forceMount,...a}=s,i=ZA(tv,s.__scopeMenu),l=mB(tv,s.__scopeMenu);return e.jsx(N9.Provider,{scope:s.__scopeMenu,children:e.jsx(yh,{present:n||i.open,children:e.jsx(N9.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(JPt,{...a,ref:t}):e.jsx(eLt,{...a,ref:t})})})})}),JPt=k.forwardRef((s,t)=>{const r=ZA(tv,s.__scopeMenu),n=k.useRef(null),a=_i(t,n);return k.useEffect(()=>{const i=n.current;if(i)return Bxe(i)},[]),e.jsx(B5e,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:dn(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),eLt=k.forwardRef((s,t)=>{const r=ZA(tv,s.__scopeMenu);return e.jsx(B5e,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),tLt=ES("MenuContent.ScrollLock"),B5e=k.forwardRef((s,t)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:m,onInteractOutside:f,onDismiss:x,disableOutsideScroll:y,..._}=s,b=ZA(tv,r),j=mB(tv,r),N=Uxe(r),C=_st(r),A=GPt(r),[E,D]=k.useState(null),R=k.useRef(null),F=_i(t,R,b.onContentChange),O=k.useRef(0),B=k.useRef(""),K=k.useRef(0),Z=k.useRef(null),Q=k.useRef("right"),W=k.useRef(0),te=y?uB:k.Fragment,ne=y?{as:tLt,allowPinchZoom:!0}:void 0,ae=me=>{var Ie,ze;const de=B.current+me,fe=A().filter(Ve=>!Ve.disabled),je=document.activeElement,xe=(Ie=fe.find(Ve=>Ve.ref.current===je))==null?void 0:Ie.textValue,Ee=fe.map(Ve=>Ve.textValue),Me=mLt(Ee,de,xe),Oe=(ze=fe.find(Ve=>Ve.textValue===Me))==null?void 0:ze.ref.current;(function Ve(Le){B.current=Le,window.clearTimeout(O.current),Le!==""&&(O.current=window.setTimeout(()=>Ve(""),1e3))})(de),Oe&&setTimeout(()=>Oe.focus())};k.useEffect(()=>()=>window.clearTimeout(O.current),[]),Oxe();const ue=k.useCallback(me=>{var fe,je;return Q.current===((fe=Z.current)==null?void 0:fe.side)&&pLt(me,(je=Z.current)==null?void 0:je.area)},[]);return e.jsx(QPt,{scope:r,searchRef:B,onItemEnter:k.useCallback(me=>{ue(me)&&me.preventDefault()},[ue]),onItemLeave:k.useCallback(me=>{var de;ue(me)||((de=R.current)==null||de.focus(),D(null))},[ue]),onTriggerLeave:k.useCallback(me=>{ue(me)&&me.preventDefault()},[ue]),pointerGraceTimerRef:K,onPointerGraceIntentChange:k.useCallback(me=>{Z.current=me},[]),children:e.jsx(te,{...ne,children:e.jsx(cB,{asChild:!0,trapped:a,onMountAutoFocus:dn(i,me=>{var de;me.preventDefault(),(de=R.current)==null||de.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(WS,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:m,onInteractOutside:f,onDismiss:x,children:e.jsx(Fxe,{asChild:!0,...C,dir:j.dir,orientation:"vertical",loop:n,currentTabStopId:E,onCurrentTabStopIdChange:D,onEntryFocus:dn(c,me=>{j.isUsingKeyboardRef.current||me.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(aB,{role:"menu","aria-orientation":"vertical","data-state":$st(b.open),"data-radix-menu-content":"",dir:j.dir,...N,..._,ref:F,style:{outline:"none",..._.style},onKeyDown:dn(_.onKeyDown,me=>{const fe=me.target.closest("[data-radix-menu-content]")===me.currentTarget,je=me.ctrlKey||me.altKey||me.metaKey,xe=me.key.length===1;fe&&(me.key==="Tab"&&me.preventDefault(),!je&&xe&&ae(me.key));const Ee=R.current;if(me.target!==Ee||!qPt.includes(me.key))return;me.preventDefault();const Oe=A().filter(Ie=>!Ie.disabled).map(Ie=>Ie.ref.current);vst.includes(me.key)&&Oe.reverse(),uLt(Oe)}),onBlur:dn(s.onBlur,me=>{me.currentTarget.contains(me.target)||(window.clearTimeout(O.current),B.current="")}),onPointerMove:dn(s.onPointerMove,k9(me=>{const de=me.target,fe=W.current!==me.clientX;if(me.currentTarget.contains(de)&&fe){const je=me.clientX>W.current?"right":"left";Q.current=je,W.current=me.clientX}}))})})})})})})});kst.displayName=tv;var sLt="MenuGroup",$5e=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(Yn.div,{role:"group",...n,ref:t})});$5e.displayName=sLt;var rLt="MenuLabel",Sst=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(Yn.div,{...n,ref:t})});Sst.displayName=rLt;var sme="MenuItem",DFe="menu.itemSelect",qxe=k.forwardRef((s,t)=>{const{disabled:r=!1,onSelect:n,...a}=s,i=k.useRef(null),l=mB(sme,s.__scopeMenu),o=z5e(sme,s.__scopeMenu),c=_i(t,i),d=k.useRef(!1),u=()=>{const m=i.current;if(!r&&m){const f=new CustomEvent(DFe,{bubbles:!0,cancelable:!0});m.addEventListener(DFe,x=>n==null?void 0:n(x),{once:!0}),o5e(m,f),f.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(Cst,{...a,ref:c,disabled:r,onClick:dn(s.onClick,u),onPointerDown:m=>{var f;(f=s.onPointerDown)==null||f.call(s,m),d.current=!0},onPointerUp:dn(s.onPointerUp,m=>{var f;d.current||(f=m.currentTarget)==null||f.click()}),onKeyDown:dn(s.onKeyDown,m=>{const f=o.searchRef.current!=="";r||f&&m.key===" "||BNe.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})});qxe.displayName=sme;var Cst=k.forwardRef((s,t)=>{const{__scopeMenu:r,disabled:n=!1,textValue:a,...i}=s,l=z5e(sme,r),o=_st(r),c=k.useRef(null),d=_i(t,c),[u,m]=k.useState(!1),[f,x]=k.useState("");return k.useEffect(()=>{const y=c.current;y&&x((y.textContent??"").trim())},[i.children]),e.jsx(N9.ItemSlot,{scope:r,disabled:n,textValue:a??f,children:e.jsx(zxe,{asChild:!0,...o,focusable:!n,children:e.jsx(Yn.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...i,ref:d,onPointerMove:dn(s.onPointerMove,k9(y=>{n?l.onItemLeave(y):(l.onItemEnter(y),y.defaultPrevented||y.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:dn(s.onPointerLeave,k9(y=>l.onItemLeave(y))),onFocus:dn(s.onFocus,()=>m(!0)),onBlur:dn(s.onBlur,()=>m(!1))})})})}),nLt="MenuCheckboxItem",Tst=k.forwardRef((s,t)=>{const{checked:r=!1,onCheckedChange:n,...a}=s;return e.jsx(Pst,{scope:s.__scopeMenu,checked:r,children:e.jsx(qxe,{role:"menuitemcheckbox","aria-checked":rme(r)?"mixed":r,...a,ref:t,"data-state":q5e(r),onSelect:dn(a.onSelect,()=>n==null?void 0:n(rme(r)?!0:!r),{checkForDefaultPrevented:!1})})})});Tst.displayName=nLt;var Est="MenuRadioGroup",[aLt,iLt]=YA(Est,{value:void 0,onValueChange:()=>{}}),Ast=k.forwardRef((s,t)=>{const{value:r,onValueChange:n,...a}=s,i=$u(n);return e.jsx(aLt,{scope:s.__scopeMenu,value:r,onValueChange:i,children:e.jsx($5e,{...a,ref:t})})});Ast.displayName=Est;var Mst="MenuRadioItem",Ist=k.forwardRef((s,t)=>{const{value:r,...n}=s,a=iLt(Mst,s.__scopeMenu),i=r===a.value;return e.jsx(Pst,{scope:s.__scopeMenu,checked:i,children:e.jsx(qxe,{role:"menuitemradio","aria-checked":i,...n,ref:t,"data-state":q5e(i),onSelect:dn(n.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,r)},{checkForDefaultPrevented:!1})})})});Ist.displayName=Mst;var U5e="MenuItemIndicator",[Pst,oLt]=YA(U5e,{checked:!1}),Lst=k.forwardRef((s,t)=>{const{__scopeMenu:r,forceMount:n,...a}=s,i=oLt(U5e,r);return e.jsx(yh,{present:n||rme(i.checked)||i.checked===!0,children:e.jsx(Yn.span,{...a,ref:t,"data-state":q5e(i.checked)})})});Lst.displayName=U5e;var lLt="MenuSeparator",Dst=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(Yn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:t})});Dst.displayName=lLt;var cLt="MenuArrow",Rst=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s,a=Uxe(r);return e.jsx(iB,{...a,...n,ref:t})});Rst.displayName=cLt;var dLt="MenuSub",[Anr,Ost]=YA(dLt),EO="MenuSubTrigger",Fst=k.forwardRef((s,t)=>{const r=ZA(EO,s.__scopeMenu),n=mB(EO,s.__scopeMenu),a=Ost(EO,s.__scopeMenu),i=z5e(EO,s.__scopeMenu),l=k.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=k.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return k.useEffect(()=>u,[u]),k.useEffect(()=>{const m=o.current;return()=>{window.clearTimeout(m),c(null)}},[o,c]),e.jsx(O5e,{asChild:!0,...d,children:e.jsx(Cst,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":a.contentId,"data-state":$st(r.open),...s,ref:N2(t,a.onTriggerChange),onClick:m=>{var f;(f=s.onClick)==null||f.call(s,m),!(s.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:dn(s.onPointerMove,k9(m=>{i.onItemEnter(m),!m.defaultPrevented&&!s.disabled&&!r.open&&!l.current&&(i.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{r.onOpenChange(!0),u()},100))})),onPointerLeave:dn(s.onPointerLeave,k9(m=>{var x,y;u();const f=(x=r.content)==null?void 0:x.getBoundingClientRect();if(f){const _=(y=r.content)==null?void 0:y.dataset.side,b=_==="right",j=b?-5:5,N=f[b?"left":"right"],C=f[b?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+j,y:m.clientY},{x:N,y:f.top},{x:C,y:f.top},{x:C,y:f.bottom},{x:N,y:f.bottom}],side:_}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:dn(s.onKeyDown,m=>{var x;const f=i.searchRef.current!=="";s.disabled||f&&m.key===" "||VPt[n.dir].includes(m.key)&&(r.onOpenChange(!0),(x=r.content)==null||x.focus(),m.preventDefault())})})})});Fst.displayName=EO;var zst="MenuSubContent",Bst=k.forwardRef((s,t)=>{const r=jst(tv,s.__scopeMenu),{forceMount:n=r.forceMount,...a}=s,i=ZA(tv,s.__scopeMenu),l=mB(tv,s.__scopeMenu),o=Ost(zst,s.__scopeMenu),c=k.useRef(null),d=_i(t,c);return e.jsx(N9.Provider,{scope:s.__scopeMenu,children:e.jsx(yh,{present:n||i.open,children:e.jsx(N9.Slot,{scope:s.__scopeMenu,children:e.jsx(B5e,{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 m;l.isUsingKeyboardRef.current&&((m=c.current)==null||m.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:dn(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:dn(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:dn(s.onKeyDown,u=>{var x;const m=u.currentTarget.contains(u.target),f=HPt[l.dir].includes(u.key);m&&f&&(i.onOpenChange(!1),(x=o.trigger)==null||x.focus(),u.preventDefault())})})})})})});Bst.displayName=zst;function $st(s){return s?"open":"closed"}function rme(s){return s==="indeterminate"}function q5e(s){return rme(s)?"indeterminate":s?"checked":"unchecked"}function uLt(s){const t=document.activeElement;for(const r of s)if(r===t||(r.focus(),document.activeElement!==t))return}function hLt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}function mLt(s,t,r){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=r?s.indexOf(r):-1;let l=hLt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==r));const c=l.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return c!==r?c:void 0}function fLt(s,t){const{x:r,y:n}=s;let a=!1;for(let i=0,l=t.length-1;in!=f>n&&r<(m-d)*(n-u)/(f-u)+d&&(a=!a)}return a}function pLt(s,t){if(!t)return!1;const r={x:s.clientX,y:s.clientY};return fLt(r,t)}function k9(s){return t=>t.pointerType==="mouse"?s(t):void 0}var xLt=wst,gLt=O5e,yLt=Nst,vLt=kst,bLt=$5e,_Lt=Sst,wLt=qxe,jLt=Tst,NLt=Ast,kLt=Ist,SLt=Lst,CLt=Dst,TLt=Rst,ELt=Fst,ALt=Bst,Vxe="DropdownMenu",[MLt,Mnr]=bu(Vxe,[bst]),Dx=bst(),[ILt,Ust]=MLt(Vxe),qst=s=>{const{__scopeDropdownMenu:t,children:r,dir:n,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=Dx(t),d=k.useRef(null),[u,m]=df({prop:a,defaultProp:i??!1,onChange:l,caller:Vxe});return e.jsx(ILt,{scope:t,triggerId:jm(),triggerRef:d,contentId:jm(),open:u,onOpenChange:m,onOpenToggle:k.useCallback(()=>m(f=>!f),[m]),modal:o,children:e.jsx(xLt,{...c,open:u,onOpenChange:m,dir:n,modal:o,children:r})})};qst.displayName=Vxe;var Vst="DropdownMenuTrigger",Hst=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...a}=s,i=Ust(Vst,r),l=Dx(r);return e.jsx(gLt,{asChild:!0,...l,children:e.jsx(Yn.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...a,ref:N2(t,i.triggerRef),onPointerDown:dn(s.onPointerDown,o=>{!n&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:dn(s.onKeyDown,o=>{n||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});Hst.displayName=Vst;var PLt="DropdownMenuPortal",Gst=s=>{const{__scopeDropdownMenu:t,...r}=s,n=Dx(t);return e.jsx(yLt,{...n,...r})};Gst.displayName=PLt;var Wst="DropdownMenuContent",Kst=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Ust(Wst,r),i=Dx(r),l=k.useRef(!1);return e.jsx(vLt,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...n,ref:t,onCloseAutoFocus:dn(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:dn(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)"}})});Kst.displayName=Wst;var LLt="DropdownMenuGroup",DLt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(bLt,{...a,...n,ref:t})});DLt.displayName=LLt;var RLt="DropdownMenuLabel",Yst=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(_Lt,{...a,...n,ref:t})});Yst.displayName=RLt;var OLt="DropdownMenuItem",Zst=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(wLt,{...a,...n,ref:t})});Zst.displayName=OLt;var FLt="DropdownMenuCheckboxItem",Xst=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(jLt,{...a,...n,ref:t})});Xst.displayName=FLt;var zLt="DropdownMenuRadioGroup",BLt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(NLt,{...a,...n,ref:t})});BLt.displayName=zLt;var $Lt="DropdownMenuRadioItem",Qst=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(kLt,{...a,...n,ref:t})});Qst.displayName=$Lt;var ULt="DropdownMenuItemIndicator",Jst=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(SLt,{...a,...n,ref:t})});Jst.displayName=ULt;var qLt="DropdownMenuSeparator",ert=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(CLt,{...a,...n,ref:t})});ert.displayName=qLt;var VLt="DropdownMenuArrow",HLt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(TLt,{...a,...n,ref:t})});HLt.displayName=VLt;var GLt="DropdownMenuSubTrigger",trt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(ELt,{...a,...n,ref:t})});trt.displayName=GLt;var WLt="DropdownMenuSubContent",srt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=Dx(r);return e.jsx(ALt,{...a,...n,ref:t,style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});srt.displayName=WLt;var KLt=qst,YLt=Hst,ZLt=Gst,rrt=Kst,nrt=Yst,art=Zst,irt=Xst,ort=Qst,lrt=Jst,crt=ert,drt=trt,urt=srt;const Gd=KLt,Wd=YLt,XLt=k.forwardRef(({className:s,inset:t,children:r,...n},a)=>e.jsxs(drt,{ref:a,className:zt("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",t&&"pl-8",s),...n,children:[r,e.jsx(Ia,{className:"ml-auto h-4 w-4"})]}));XLt.displayName=drt.displayName;const QLt=k.forwardRef(({className:s,...t},r)=>e.jsx(urt,{ref:r,className:zt("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}));QLt.displayName=urt.displayName;const Sd=k.forwardRef(({className:s,sideOffset:t=4,...r},n)=>e.jsx(ZLt,{children:e.jsx(rrt,{ref:n,sideOffset:t,className:zt("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r})}));Sd.displayName=rrt.displayName;const ti=k.forwardRef(({className:s,inset:t,...r},n)=>e.jsx(art,{ref:n,className:zt("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t&&"pl-8",s),...r}));ti.displayName=art.displayName;const JLt=k.forwardRef(({className:s,children:t,checked:r,...n},a)=>e.jsxs(irt,{ref:a,className:zt("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),checked:r,...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(lrt,{children:e.jsx(la,{className:"h-4 w-4"})})}),t]}));JLt.displayName=irt.displayName;const e8t=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(ort,{ref:n,className:zt("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(lrt,{children:e.jsx(Rh,{className:"h-2 w-2 fill-current"})})}),t]}));e8t.displayName=ort.displayName;const S9=k.forwardRef(({className:s,inset:t,...r},n)=>e.jsx(nrt,{ref:n,className:zt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...r}));S9.displayName=nrt.displayName;const z_=k.forwardRef(({className:s,...t},r)=>e.jsx(crt,{ref:r,className:zt("-mx-1 my-1 h-px bg-muted",s),...t}));z_.displayName=crt.displayName;const t8t=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:a,setActingAsSelf:i}=D5e();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(qi,{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(Dr,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{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(qi,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Wn,{className:"h-5 w-5",children:[e.jsx(Xa,{src:t.avatar_url||void 0}),e.jsx(Kn,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(Co,{className:"h-3 w-3"})]})}),e.jsxs(Sd,{align:"start",className:"z-[2147483647]",children:[e.jsxs(ti,{onClick:i,className:"gap-2",children:[e.jsx(qi,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(Xe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(z_,{}),r.map(o=>e.jsxs(ti,{onClick:()=>n(o),className:"gap-2",children:[e.jsxs(Wn,{className:"h-6 w-6",children:[e.jsx(Xa,{src:o.avatar_url||void 0}),e.jsx(Kn,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(Xe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(Xe,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},ir=({children:s,requireAdmin:t=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=Cs(),c=vc();if(a||(t||r)&&i)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!n){const d=c.pathname+c.search+c.hash;return d&&d!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",d),e.jsx(o7,{to:"/auth",replace:!0})}return t&&!l?e.jsx(o7,{to:"/dashboard",replace:!0}):r&&!o&&!l?e.jsx(o7,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var V5e={};(function s(t,r,n,a){var i=!!(t.Worker&&t.Blob&&t.Promise&&t.OffscreenCanvas&&t.OffscreenCanvasRenderingContext2D&&t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.transferControlToOffscreen&&t.URL&&t.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!t.OffscreenCanvas)return!1;try{var de=new OffscreenCanvas(1,1),fe=de.getContext("2d");fe.fillRect(0,0,1,1);var je=de.transferToImageBitmap();fe.createPattern(je,"no-repeat")}catch{return!1}return!0}();function c(){}function d(de){var fe=r.exports.Promise,je=fe!==void 0?fe:t.Promise;return typeof je=="function"?new je(de):(de(c,c),null)}var u=function(de,fe){return{transform:function(je){if(de)return je;if(fe.has(je))return fe.get(je);var xe=new OffscreenCanvas(je.width,je.height),Ee=xe.getContext("2d");return Ee.drawImage(je,0,0),fe.set(je,xe),xe},clear:function(){fe.clear()}}}(o,new Map),m=function(){var de=Math.floor(16.666666666666668),fe,je,xe={},Ee=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(fe=function(Me){var Oe=Math.random();return xe[Oe]=requestAnimationFrame(function Ie(ze){Ee===ze||Ee+de-1{const{data:t,error:r}=await U.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(r)throw r;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function r8t(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function n8t(){const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{const{error:n}=await U.from("celebration_queue").insert({user_id:r.user_id,celebration_type:r.celebration_type,title:r.title,message:r.message||null,points_amount:r.points_amount||null,created_by:t==null?void 0:t.id});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}var Hxe="Dialog",[hrt,mrt]=bu(Hxe),[a8t,$1]=hrt(Hxe),frt=s=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=k.useRef(null),c=k.useRef(null),[d,u]=df({prop:n,defaultProp:a??!1,onChange:i,caller:Hxe});return e.jsx(a8t,{scope:t,triggerRef:o,contentRef:c,contentId:jm(),titleId:jm(),descriptionId:jm(),open:d,onOpenChange:u,onOpenToggle:k.useCallback(()=>u(m=>!m),[u]),modal:l,children:r})};frt.displayName=Hxe;var prt="DialogTrigger",xrt=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=$1(prt,r),i=_i(t,a.triggerRef);return e.jsx(Yn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":W5e(a.open),...n,ref:i,onClick:dn(s.onClick,a.onOpenToggle)})});xrt.displayName=prt;var H5e="DialogPortal",[i8t,grt]=hrt(H5e,{forceMount:void 0}),yrt=s=>{const{__scopeDialog:t,forceMount:r,children:n,container:a}=s,i=$1(H5e,t);return e.jsx(i8t,{scope:t,forceMount:r,children:k.Children.map(n,l=>e.jsx(yh,{present:r||i.open,children:e.jsx(h8,{asChild:!0,container:a,children:l})}))})};yrt.displayName=H5e;var nme="DialogOverlay",vrt=k.forwardRef((s,t)=>{const r=grt(nme,s.__scopeDialog),{forceMount:n=r.forceMount,...a}=s,i=$1(nme,s.__scopeDialog);return i.modal?e.jsx(yh,{present:n||i.open,children:e.jsx(l8t,{...a,ref:t})}):null});vrt.displayName=nme;var o8t=ES("DialogOverlay.RemoveScroll"),l8t=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=$1(nme,r);return e.jsx(uB,{as:o8t,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(Yn.div,{"data-state":W5e(a.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),yA="DialogContent",brt=k.forwardRef((s,t)=>{const r=grt(yA,s.__scopeDialog),{forceMount:n=r.forceMount,...a}=s,i=$1(yA,s.__scopeDialog);return e.jsx(yh,{present:n||i.open,children:i.modal?e.jsx(c8t,{...a,ref:t}):e.jsx(d8t,{...a,ref:t})})});brt.displayName=yA;var c8t=k.forwardRef((s,t)=>{const r=$1(yA,s.__scopeDialog),n=k.useRef(null),a=_i(t,r.contentRef,n);return k.useEffect(()=>{const i=n.current;if(i)return Bxe(i)},[]),e.jsx(_rt,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:dn(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=r.triggerRef.current)==null||l.focus()}),onPointerDownOutside:dn(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:dn(s.onFocusOutside,i=>i.preventDefault())})}),d8t=k.forwardRef((s,t)=>{const r=$1(yA,s.__scopeDialog),n=k.useRef(!1),a=k.useRef(!1);return e.jsx(_rt,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(n.current||(o=r.triggerRef.current)==null||o.focus(),i.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=r.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),_rt=k.forwardRef((s,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=$1(yA,r),c=k.useRef(null),d=_i(t,c);return Oxe(),e.jsxs(e.Fragment,{children:[e.jsx(cB,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(WS,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":W5e(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(h8t,{titleId:o.titleId}),e.jsx(f8t,{contentRef:c,descriptionId:o.descriptionId})]})]})}),G5e="DialogTitle",wrt=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=$1(G5e,r);return e.jsx(Yn.h2,{id:a.titleId,...n,ref:t})});wrt.displayName=G5e;var jrt="DialogDescription",Nrt=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=$1(jrt,r);return e.jsx(Yn.p,{id:a.descriptionId,...n,ref:t})});Nrt.displayName=jrt;var krt="DialogClose",Srt=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=$1(krt,r);return e.jsx(Yn.button,{type:"button",...n,ref:t,onClick:dn(s.onClick,()=>a.onOpenChange(!1))})});Srt.displayName=krt;function W5e(s){return s?"open":"closed"}var Crt="DialogTitleWarning",[u8t,Trt]=pCt(Crt,{contentName:yA,titleName:G5e,docsSlug:"dialog"}),h8t=({titleId:s})=>{const t=Trt(Crt),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return k.useEffect(()=>{s&&(document.getElementById(s)||console.error(r))},[r,s]),null},m8t="DialogDescriptionWarning",f8t=({contentRef:s,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Trt(m8t).contentName}}.`;return k.useEffect(()=>{var i;const a=(i=s.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(n))},[n,s,t]),null},Gxe=frt,K5e=xrt,Wxe=yrt,w8=vrt,j8=brt,fB=wrt,pB=Nrt,xB=Srt;const vs=Gxe,Yi=K5e,p8t=Wxe,Inr=xB,Ert=k.forwardRef(({className:s,...t},r)=>e.jsx(w8,{ref:r,className:zt("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}));Ert.displayName=w8.displayName;const ys=k.forwardRef(({className:s,children:t,overlayClassName:r,...n},a)=>e.jsxs(p8t,{children:[e.jsx(Ert,{className:r}),e.jsxs(j8,{ref:a,className:zt("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...n,children:[t,e.jsxs(xB,{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($r,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ys.displayName=j8.displayName;const _s=({className:s,...t})=>e.jsx("div",{className:zt("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});_s.displayName="DialogHeader";const fn=({className:s,...t})=>e.jsx("div",{className:zt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});fn.displayName="DialogFooter";const bs=k.forwardRef(({className:s,...t},r)=>e.jsx(fB,{ref:r,className:zt("text-lg font-semibold leading-none tracking-tight",s),...t}));bs.displayName=fB.displayName;const an=k.forwardRef(({className:s,...t},r)=>e.jsx(pB,{ref:r,className:zt("text-sm text-muted-foreground",s),...t}));an.displayName=pB.displayName;const x8t={points_earned:wo,listing_created:Pn,deal_closed:Xl,custom:fa},OFe={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"},FFe=()=>{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 g8t(){const{user:s}=Cs(),t=is(),{data:r}=s8t(),n=r8t(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=k.useCallback(()=>{const x=Date.now()+3e3,y={startVelocity:30,spread:360,ticks:60,zIndex:9999},_=(j,N)=>Math.random()*(N-j)+j,b=setInterval(()=>{const j=x-Date.now();if(j<=0){clearInterval(b);return}const N=50*(j/3e3);RFe({...y,particleCount:N,origin:{x:_(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),RFe({...y,particleCount:N,origin:{x:_(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);k.useEffect(()=>{FFe()||r&&r.length>0&&!a&&(i(r[0]),o(!0),setTimeout(c,100))},[r,a,c]);const d=async()=>{if(a){const f=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],x=>(x==null?void 0:x.filter(y=>y.id!==f))??[]),await n.mutateAsync(f)}};if(FFe()||!a)return null;const u=x8t[a.celebration_type]||fa,m=OFe[a.celebration_type]||OFe.custom;return e.jsx(vs,{open:l,onOpenChange:f=>!f&&d(),children:e.jsxs(ys,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${m} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${m} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(Ir,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(Ir,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(Ir,{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(q,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),r&&r.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",r.length-1," more celebration",r.length>2?"s":""," waiting"]})]})]})})}function dr({className:s,...t}){return e.jsx("div",{className:zt("animate-pulse rounded-md bg-muted",s),...t})}const Ne=k.forwardRef(({className:s,type:t,...r},n)=>e.jsx("input",{type:t,className:zt("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",s),ref:n,...r}));Ne.displayName="Input";var y8t="Label",Art=k.forwardRef((s,t)=>e.jsx(Yn.label,{...s,ref:t,onMouseDown:r=>{var a;r.target.closest("button, input, select, textarea")||((a=s.onMouseDown)==null||a.call(s,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));Art.displayName=y8t;var Mrt=Art;const v8t=WA("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ce=k.forwardRef(({className:s,...t},r)=>e.jsx(Mrt,{ref:r,className:zt(v8t(),s),...t}));ce.displayName=Mrt.displayName;const pr=k.forwardRef(({className:s,...t},r)=>e.jsx("textarea",{className:zt("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",s),ref:r,...t}));pr.displayName="Textarea";var Kxe="Tabs",[b8t,Pnr]=bu(Kxe,[XS]),Irt=XS(),[_8t,Y5e]=b8t(Kxe),Prt=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=ZS(o),[m,f]=df({prop:n,onChange:a,defaultProp:i??"",caller:Kxe});return e.jsx(_8t,{scope:r,baseId:jm(),value:m,onValueChange:f,orientation:l,dir:u,activationMode:c,children:e.jsx(Yn.div,{dir:u,"data-orientation":l,...d,ref:t})})});Prt.displayName=Kxe;var Lrt="TabsList",Drt=k.forwardRef((s,t)=>{const{__scopeTabs:r,loop:n=!0,...a}=s,i=Y5e(Lrt,r),l=Irt(r);return e.jsx(Fxe,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:n,children:e.jsx(Yn.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});Drt.displayName=Lrt;var Rrt="TabsTrigger",Ort=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,disabled:a=!1,...i}=s,l=Y5e(Rrt,r),o=Irt(r),c=Brt(l.baseId,n),d=$rt(l.baseId,n),u=n===l.value;return e.jsx(zxe,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(Yn.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:dn(s.onMouseDown,m=>{!a&&m.button===0&&m.ctrlKey===!1?l.onValueChange(n):m.preventDefault()}),onKeyDown:dn(s.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&l.onValueChange(n)}),onFocus:dn(s.onFocus,()=>{const m=l.activationMode!=="manual";!u&&!a&&m&&l.onValueChange(n)})})})});Ort.displayName=Rrt;var Frt="TabsContent",zrt=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,forceMount:a,children:i,...l}=s,o=Y5e(Frt,r),c=Brt(o.baseId,n),d=$rt(o.baseId,n),u=n===o.value,m=k.useRef(u);return k.useEffect(()=>{const f=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(f)},[]),e.jsx(yh,{present:a||u,children:({present:f})=>e.jsx(Yn.div,{"data-state":u?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!f,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:m.current?"0s":void 0},children:f&&i})})});zrt.displayName=Frt;function Brt(s,t){return`${s}-trigger-${t}`}function $rt(s,t){return`${s}-content-${t}`}var w8t=Prt,Urt=Drt,qrt=Ort,Vrt=zrt;const ta=w8t,ea=k.forwardRef(({className:s,...t},r)=>e.jsx(Urt,{ref:r,className:zt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));ea.displayName=Urt.displayName;const rs=k.forwardRef(({className:s,...t},r)=>e.jsx(qrt,{ref:r,className:zt("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}));rs.displayName=qrt.displayName;const fs=k.forwardRef(({className:s,...t},r)=>e.jsx(Vrt,{ref:r,className:zt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));fs.displayName=Vrt.displayName;const C9="#0d0d0d",ame="#1a1a1a",Uf="#c9a84c",gB="#f0d78c",B_={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function Yxe(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:r,error:n}=await U.functions.invoke("public-site-lead",{body:t});if(n)throw n;try{localStorage.setItem(B_.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return r}function Z5e(){try{return!!localStorage.getItem(B_.captured)}catch{return!1}}function j8t(){try{const s=localStorage.getItem(B_.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function X5e({open:s,onClose:t,children:r}){return k.useEffect(()=>{if(!s)return;const n=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=n}},[s]),s?vx.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:n=>n.stopPropagation(),className:"relative w-full max-w-md rounded-2xl overflow-hidden animate-in zoom-in-95",style:{background:`linear-gradient(180deg, ${ame} 0%, ${C9} 100%)`,border:`1px solid ${Uf}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${Uf}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($r,{className:"h-4 w-4"})}),r]})}),document.body):null}function Q5e(){const[s,t]=k.useState({first_name:"",email:"",phone:"",area:""}),[r,n]=k.useState(!1),[a,i]=k.useState("");return{values:s,setValues:t,loading:r,setLoading:n,honeypot:a,setHoneypot:i}}function J5e({values:s,setValues:t,honeypot:r,setHoneypot:n,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(qi,{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(Ks,{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(Mn,{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(Ma,{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:r,onChange:d=>n(d.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function eTe({children:s,disabled:t,onClick:r,type:n="button"}){return e.jsx("button",{type:n,disabled:t,onClick:r,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, ${gB} 0%, ${Uf} 100%)`,color:C9,boxShadow:`0 8px 24px ${Uf}55`},children:s})}function zFe({open:s,onClose:t,initialCriteria:r}){const{values:n,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=Q5e(),[d,u]=k.useState(!1),m=async f=>{if(f.preventDefault(),!!n.email){l(!0);try{await Yxe({lead_type:"new_listing_alerts",email:n.email.trim().toLowerCase(),first_name:n.first_name.trim()||void 0,phone:n.phone.trim()||void 0,criteria:{...r||{},...n.area.trim()?{area:n.area.trim()}:{}}}),u(!0);try{localStorage.setItem(B_.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{he.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(X5e,{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(ym,{className:"h-4 w-4",style:{color:Uf}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:gB},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:`${Uf}22`,border:`1px solid ${Uf}55`},children:e.jsx(Ir,{className:"h-5 w-5",style:{color:Uf}})}),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:m,className:"space-y-4",children:[e.jsx(J5e,{values:n,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(eTe,{type:"submit",disabled:i||!n.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 N8t(){const[s,t]=k.useState(!0),[r,n]=k.useState(!1);k.useEffect(()=>{try{const i=!!localStorage.getItem(B_.stickyDismissed)||Z5e();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(B_.stickyDismissed,"1")}catch{}};return s?e.jsx(zFe,{open:r,onClose:()=>n(!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, ${ame} 0%, ${C9} 100%)`,borderTop:`1px solid ${Uf}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:`${Uf}22`,border:`1px solid ${Uf}55`},children:e.jsx(ym,{className:"h-4 w-4",style:{color:Uf}})}),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:()=>n(!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, ${gB} 0%, ${Uf} 100%)`,color:C9},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx($r,{className:"h-4 w-4"})})]})}),e.jsx(zFe,{open:r,onClose:()=>n(!1)})]})}function k8t(){const[s,t]=k.useState(!1),r=k.useRef(!1);k.useEffect(()=>{try{if(sessionStorage.getItem(B_.exitShown)||Z5e())return}catch{}const f=setTimeout(()=>{r.current=!0},8e3),x=y=>{if(r.current&&!(y.clientY>0)){t(!0);try{sessionStorage.setItem(B_.exitShown,"1")}catch{}window.removeEventListener("mouseleave",x),document.removeEventListener("mouseleave",x)}};return document.addEventListener("mouseleave",x),()=>{clearTimeout(f),document.removeEventListener("mouseleave",x)}},[]);const{values:n,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=Q5e(),[d,u]=k.useState(!1),m=async f=>{if(f.preventDefault(),!!n.email){l(!0);try{await Yxe({lead_type:"exit_intent",email:n.email.trim().toLowerCase(),first_name:n.first_name.trim()||void 0,phone:n.phone.trim()||void 0,criteria:n.area.trim()?{area:n.area.trim()}:void 0}),u(!0),setTimeout(()=>t(!1),2200)}catch{he.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(X5e,{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, ${C9} 0%, ${ame} 60%, ${Uf} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:gB},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:ame,border:`1px solid ${Uf}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(Ir,{className:"h-6 w-6",style:{color:Uf}})}),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:m,className:"space-y-4",children:[e.jsx(J5e,{values:n,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(eTe,{type:"submit",disabled:i||!n.email,children:i?"Sending…":"Send My List"})]})]})]})})}function S8t(){const[s,t]=k.useState([]);k.useEffect(()=>{try{const o=localStorage.getItem(B_.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const r=o=>{t(o);try{localStorage.setItem(B_.savedListings,JSON.stringify(o))}catch{}},n=k.useCallback(o=>s.includes(o),[s]),a=o=>{s.includes(o)||r([...s,o])},i=o=>r(s.filter(c=>c!==o));return{ids:s,has:n,add:a,remove:i,toggle:o=>s.includes(o)?i(o):a(o)}}function C8t({listingId:s,listingAddress:t,className:r}){const{has:n,add:a,remove:i}=S8t(),l=n(s),[o,c]=k.useState(!1),d=()=>{if(l){i(s);return}if(Z5e()){a(s),he.success("Saved to your favorites"),Yxe({lead_type:"saved_listing",email:j8t()||"unknown@local",listing_id:s,listing_address:t}).catch(()=>{});return}c(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:d,className:r,"aria-label":l?"Remove from favorites":"Save to favorites",children:e.jsx(yi,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(T8t,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function T8t({open:s,onClose:t,listingId:r,listingAddress:n,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=Q5e(),m=async f=>{if(f.preventDefault(),!!i.email){c(!0);try{await Yxe({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:r,listing_address:n}),a(),he.success("Saved to your favorites"),t()}catch{he.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(X5e,{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(yi,{className:"h-4 w-4",style:{color:Uf}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:gB},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:m,className:"space-y-4",children:[e.jsx(J5e,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(eTe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}function T9(s,[t,r]){return Math.min(r,Math.max(t,s))}function yB(s){const t=k.useRef({value:s,previous:s});return k.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var Hrt=["PageUp","PageDown"],Grt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Wrt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},N8="Slider",[$Ne,E8t,A8t]=eB(N8),[Krt,Lnr]=bu(N8,[A8t]),[M8t,Zxe]=Krt(N8),Yrt=k.forwardRef((s,t)=>{const{name:r,min:n=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[n],value:u,onValueChange:m=()=>{},onValueCommit:f=()=>{},inverted:x=!1,form:y,..._}=s,b=k.useRef(new Set),j=k.useRef(0),C=l==="horizontal"?I8t:P8t,[A=[],E]=df({prop:u,defaultProp:d,onChange:K=>{var Q;(Q=[...b.current][j.current])==null||Q.focus(),m(K)}}),D=k.useRef(A);function R(K){const Z=F8t(A,K);B(K,Z)}function F(K){B(K,j.current)}function O(){const K=D.current[j.current];A[j.current]!==K&&f(A)}function B(K,Z,{commit:Q}={commit:!1}){const W=U8t(i),te=q8t(Math.round((K-n)/i)*i+n,W),ne=T9(te,[n,a]);E((ae=[])=>{const ue=R8t(ae,ne,Z);if($8t(ue,c*i)){j.current=ue.indexOf(ne);const me=String(ue)!==String(ae);return me&&Q&&f(ue),me?ue:ae}else return ae})}return e.jsx(M8t,{scope:s.__scopeSlider,name:r,disabled:o,min:n,max:a,valueIndexToChangeRef:j,thumbs:b.current,values:A,orientation:l,form:y,children:e.jsx($Ne.Provider,{scope:s.__scopeSlider,children:e.jsx($Ne.Slot,{scope:s.__scopeSlider,children:e.jsx(C,{"aria-disabled":o,"data-disabled":o?"":void 0,..._,ref:t,onPointerDown:dn(_.onPointerDown,()=>{o||(D.current=A)}),min:n,max:a,inverted:x,onSlideStart:o?void 0:R,onSlideMove:o?void 0:F,onSlideEnd:o?void 0:O,onHomeKeyDown:()=>!o&&B(n,0,{commit:!0}),onEndKeyDown:()=>!o&&B(a,A.length-1,{commit:!0}),onStepKeyDown:({event:K,direction:Z})=>{if(!o){const te=Hrt.includes(K.key)||K.shiftKey&&Grt.includes(K.key)?10:1,ne=j.current,ae=A[ne],ue=i*te*Z;B(ae+ue,ne,{commit:!0})}}})})})})});Yrt.displayName=N8;var[Zrt,Xrt]=Krt(N8,{startEdge:"left",endEdge:"right",size:"width",direction:1}),I8t=k.forwardRef((s,t)=>{const{min:r,max:n,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[m,f]=k.useState(null),x=_i(t,C=>f(C)),y=k.useRef(void 0),_=ZS(a),b=_==="ltr",j=b&&!i||!b&&i;function N(C){const A=y.current||m.getBoundingClientRect(),E=[0,A.width],R=tTe(E,j?[r,n]:[n,r]);return y.current=A,R(C-A.left)}return e.jsx(Zrt,{scope:s.__scopeSlider,startEdge:j?"left":"right",endEdge:j?"right":"left",direction:j?1:-1,size:"width",children:e.jsx(Qrt,{dir:_,"data-orientation":"horizontal",...u,ref:x,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const A=N(C.clientX);l==null||l(A)},onSlideMove:C=>{const A=N(C.clientX);o==null||o(A)},onSlideEnd:()=>{y.current=void 0,c==null||c()},onStepKeyDown:C=>{const E=Wrt[j?"from-left":"from-right"].includes(C.key);d==null||d({event:C,direction:E?-1:1})}})})}),P8t=k.forwardRef((s,t)=>{const{min:r,max:n,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=k.useRef(null),m=_i(t,u),f=k.useRef(void 0),x=!a;function y(_){const b=f.current||u.current.getBoundingClientRect(),j=[0,b.height],C=tTe(j,x?[n,r]:[r,n]);return f.current=b,C(_-b.top)}return e.jsx(Zrt,{scope:s.__scopeSlider,startEdge:x?"bottom":"top",endEdge:x?"top":"bottom",size:"height",direction:x?1:-1,children:e.jsx(Qrt,{"data-orientation":"vertical",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const b=y(_.clientY);i==null||i(b)},onSlideMove:_=>{const b=y(_.clientY);l==null||l(b)},onSlideEnd:()=>{f.current=void 0,o==null||o()},onStepKeyDown:_=>{const j=Wrt[x?"from-bottom":"from-top"].includes(_.key);c==null||c({event:_,direction:j?-1:1})}})})}),Qrt=k.forwardRef((s,t)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=Zxe(N8,r);return e.jsx(Yn.span,{...d,ref:t,onKeyDown:dn(s.onKeyDown,m=>{m.key==="Home"?(l(m),m.preventDefault()):m.key==="End"?(o(m),m.preventDefault()):Hrt.concat(Grt).includes(m.key)&&(c(m),m.preventDefault())}),onPointerDown:dn(s.onPointerDown,m=>{const f=m.target;f.setPointerCapture(m.pointerId),m.preventDefault(),u.thumbs.has(f)?f.focus():n(m)}),onPointerMove:dn(s.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&a(m)}),onPointerUp:dn(s.onPointerUp,m=>{const f=m.target;f.hasPointerCapture(m.pointerId)&&(f.releasePointerCapture(m.pointerId),i(m))})})}),Jrt="SliderTrack",ent=k.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=Zxe(Jrt,r);return e.jsx(Yn.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...n,ref:t})});ent.displayName=Jrt;var UNe="SliderRange",tnt=k.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=Zxe(UNe,r),i=Xrt(UNe,r),l=k.useRef(null),o=_i(t,l),c=a.values.length,d=a.values.map(f=>nnt(f,a.min,a.max)),u=c>1?Math.min(...d):0,m=100-Math.max(...d);return e.jsx(Yn.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...n,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:m+"%"}})});tnt.displayName=UNe;var qNe="SliderThumb",snt=k.forwardRef((s,t)=>{const r=E8t(s.__scopeSlider),[n,a]=k.useState(null),i=_i(t,o=>a(o)),l=k.useMemo(()=>n?r().findIndex(o=>o.ref.current===n):-1,[r,n]);return e.jsx(L8t,{...s,ref:i,index:l})}),L8t=k.forwardRef((s,t)=>{const{__scopeSlider:r,index:n,name:a,...i}=s,l=Zxe(qNe,r),o=Xrt(qNe,r),[c,d]=k.useState(null),u=_i(t,N=>d(N)),m=c?l.form||!!c.closest("form"):!0,f=rB(c),x=l.values[n],y=x===void 0?0:nnt(x,l.min,l.max),_=O8t(n,l.values.length),b=f==null?void 0:f[o.size],j=b?z8t(b,y,o.direction):0;return k.useEffect(()=>{if(c)return l.thumbs.add(c),()=>{l.thumbs.delete(c)}},[c,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${y}% + ${j}px)`},children:[e.jsx($Ne.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(Yn.span,{role:"slider","aria-label":s["aria-label"]||_,"aria-valuemin":l.min,"aria-valuenow":x,"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:x===void 0?{display:"none"}:s.style,onFocus:dn(s.onFocus,()=>{l.valueIndexToChangeRef.current=n})})}),m&&e.jsx(rnt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:x},n)]})});snt.displayName=qNe;var D8t="RadioBubbleInput",rnt=k.forwardRef(({__scopeSlider:s,value:t,...r},n)=>{const a=k.useRef(null),i=_i(a,n),l=yB(t);return k.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const m=new Event("input",{bubbles:!0});u.call(o,t),o.dispatchEvent(m)}},[l,t]),e.jsx(Yn.input,{style:{display:"none"},...r,ref:i,defaultValue:t})});rnt.displayName=D8t;function R8t(s=[],t,r){const n=[...s];return n[r]=t,n.sort((a,i)=>a-i)}function nnt(s,t,r){const i=100/(r-t)*(s-t);return T9(i,[0,100])}function O8t(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function F8t(s,t){if(s.length===1)return 0;const r=s.map(a=>Math.abs(a-t)),n=Math.min(...r);return r.indexOf(n)}function z8t(s,t,r){const n=s/2,i=tTe([0,50],[0,n]);return(n-i(t)*r)*r}function B8t(s){return s.slice(0,-1).map((t,r)=>s[r+1]-t)}function $8t(s,t){if(t>0){const r=B8t(s);return Math.min(...r)>=t}return!0}function tTe(s,t){return r=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const n=(t[1]-t[0])/(s[1]-s[0]);return t[0]+n*(r-s[0])}}function U8t(s){return(String(s).split(".")[1]||"").length}function q8t(s,t){const r=Math.pow(10,t);return Math.round(s*r)/r}var ant=Yrt,V8t=ent,H8t=tnt,G8t=snt;const nf=k.forwardRef(({className:s,...t},r)=>e.jsxs(ant,{ref:r,className:zt("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(V8t,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(H8t,{className:"absolute h-full bg-primary"})}),e.jsx(G8t,{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"})]}));nf.displayName=ant.displayName;var W8t=[" ","Enter","ArrowUp","ArrowDown"],K8t=[" ","Enter"],vA="Select",[Xxe,Qxe,Y8t]=eB(vA),[k8,Dnr]=bu(vA,[Y8t,Q_]),Jxe=Q_(),[Z8t,QS]=k8(vA),[X8t,Q8t]=k8(vA),int=s=>{const{__scopeSelect:t,children:r,open:n,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:m,disabled:f,required:x,form:y}=s,_=Jxe(t),[b,j]=k.useState(null),[N,C]=k.useState(null),[A,E]=k.useState(!1),D=ZS(d),[R,F]=df({prop:n,defaultProp:a??!1,onChange:i,caller:vA}),[O,B]=df({prop:l,defaultProp:o,onChange:c,caller:vA}),K=k.useRef(null),Z=b?y||!!b.closest("form"):!0,[Q,W]=k.useState(new Set),te=Array.from(Q).map(ne=>ne.props.value).join(";");return e.jsx(nB,{..._,children:e.jsxs(Z8t,{required:x,scope:t,trigger:b,onTriggerChange:j,valueNode:N,onValueNodeChange:C,valueNodeHasChildren:A,onValueNodeHasChildrenChange:E,contentId:jm(),value:O,onValueChange:B,open:R,onOpenChange:F,dir:D,triggerPointerDownPosRef:K,disabled:f,children:[e.jsx(Xxe.Provider,{scope:t,children:e.jsx(X8t,{scope:s.__scopeSelect,onNativeOptionAdd:k.useCallback(ne=>{W(ae=>new Set(ae).add(ne))},[]),onNativeOptionRemove:k.useCallback(ne=>{W(ae=>{const ue=new Set(ae);return ue.delete(ne),ue})},[]),children:r})}),Z?e.jsxs(Ant,{"aria-hidden":!0,required:x,tabIndex:-1,name:u,autoComplete:m,value:O,onChange:ne=>B(ne.target.value),disabled:f,form:y,children:[O===void 0?e.jsx("option",{value:""}):null,Array.from(Q)]},te):null]})})};int.displayName=vA;var ont="SelectTrigger",lnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,disabled:n=!1,...a}=s,i=Jxe(r),l=QS(ont,r),o=l.disabled||n,c=_i(t,l.onTriggerChange),d=Qxe(r),u=k.useRef("touch"),[m,f,x]=Int(_=>{const b=d().filter(C=>!C.disabled),j=b.find(C=>C.value===l.value),N=Pnt(b,_,j);N!==void 0&&l.onValueChange(N.value)}),y=_=>{o||(l.onOpenChange(!0),x()),_&&(l.triggerPointerDownPosRef.current={x:Math.round(_.pageX),y:Math.round(_.pageY)})};return e.jsx(x8,{asChild:!0,...i,children:e.jsx(Yn.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":Mnt(l.value)?"":void 0,...a,ref:c,onClick:dn(a.onClick,_=>{_.currentTarget.focus(),u.current!=="mouse"&&y(_)}),onPointerDown:dn(a.onPointerDown,_=>{u.current=_.pointerType;const b=_.target;b.hasPointerCapture(_.pointerId)&&b.releasePointerCapture(_.pointerId),_.button===0&&_.ctrlKey===!1&&_.pointerType==="mouse"&&(y(_),_.preventDefault())}),onKeyDown:dn(a.onKeyDown,_=>{const b=m.current!=="";!(_.ctrlKey||_.altKey||_.metaKey)&&_.key.length===1&&f(_.key),!(b&&_.key===" ")&&W8t.includes(_.key)&&(y(),_.preventDefault())})})})});lnt.displayName=ont;var cnt="SelectValue",dnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,className:n,style:a,children:i,placeholder:l="",...o}=s,c=QS(cnt,r),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,m=_i(t,c.onValueNodeChange);return Gu(()=>{d(u)},[d,u]),e.jsx(Yn.span,{...o,ref:m,style:{pointerEvents:"none"},children:Mnt(c.value)?e.jsx(e.Fragment,{children:l}):i})});dnt.displayName=cnt;var J8t="SelectIcon",unt=k.forwardRef((s,t)=>{const{__scopeSelect:r,children:n,...a}=s;return e.jsx(Yn.span,{"aria-hidden":!0,...a,ref:t,children:n||"▼"})});unt.displayName=J8t;var eDt="SelectPortal",hnt=s=>e.jsx(h8,{asChild:!0,...s});hnt.displayName=eDt;var bA="SelectContent",mnt=k.forwardRef((s,t)=>{const r=QS(bA,s.__scopeSelect),[n,a]=k.useState();if(Gu(()=>{a(new DocumentFragment)},[]),!r.open){const i=n;return i?vx.createPortal(e.jsx(fnt,{scope:s.__scopeSelect,children:e.jsx(Xxe.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(pnt,{...s,ref:t})});mnt.displayName=bA;var s1=10,[fnt,JS]=k8(bA),tDt="SelectContentImpl",sDt=ES("SelectContent.RemoveScroll"),pnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:m,collisionBoundary:f,collisionPadding:x,sticky:y,hideWhenDetached:_,avoidCollisions:b,...j}=s,N=QS(bA,r),[C,A]=k.useState(null),[E,D]=k.useState(null),R=_i(t,Ie=>A(Ie)),[F,O]=k.useState(null),[B,K]=k.useState(null),Z=Qxe(r),[Q,W]=k.useState(!1),te=k.useRef(!1);k.useEffect(()=>{if(C)return Bxe(C)},[C]),Oxe();const ne=k.useCallback(Ie=>{const[ze,...Ve]=Z().map(ve=>ve.ref.current),[Le]=Ve.slice(-1),$e=document.activeElement;for(const ve of Ie)if(ve===$e||(ve==null||ve.scrollIntoView({block:"nearest"}),ve===ze&&E&&(E.scrollTop=0),ve===Le&&E&&(E.scrollTop=E.scrollHeight),ve==null||ve.focus(),document.activeElement!==$e))return},[Z,E]),ae=k.useCallback(()=>ne([F,C]),[ne,F,C]);k.useEffect(()=>{Q&&ae()},[Q,ae]);const{onOpenChange:ue,triggerPointerDownPosRef:me}=N;k.useEffect(()=>{if(C){let Ie={x:0,y:0};const ze=Le=>{var $e,ve;Ie={x:Math.abs(Math.round(Le.pageX)-((($e=me.current)==null?void 0:$e.x)??0)),y:Math.abs(Math.round(Le.pageY)-(((ve=me.current)==null?void 0:ve.y)??0))}},Ve=Le=>{Ie.x<=10&&Ie.y<=10?Le.preventDefault():C.contains(Le.target)||ue(!1),document.removeEventListener("pointermove",ze),me.current=null};return me.current!==null&&(document.addEventListener("pointermove",ze),document.addEventListener("pointerup",Ve,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ze),document.removeEventListener("pointerup",Ve,{capture:!0})}}},[C,ue,me]),k.useEffect(()=>{const Ie=()=>ue(!1);return window.addEventListener("blur",Ie),window.addEventListener("resize",Ie),()=>{window.removeEventListener("blur",Ie),window.removeEventListener("resize",Ie)}},[ue]);const[de,fe]=Int(Ie=>{const ze=Z().filter($e=>!$e.disabled),Ve=ze.find($e=>$e.ref.current===document.activeElement),Le=Pnt(ze,Ie,Ve);Le&&setTimeout(()=>Le.ref.current.focus())}),je=k.useCallback((Ie,ze,Ve)=>{const Le=!te.current&&!Ve;(N.value!==void 0&&N.value===ze||Le)&&(O(Ie),Le&&(te.current=!0))},[N.value]),xe=k.useCallback(()=>C==null?void 0:C.focus(),[C]),Ee=k.useCallback((Ie,ze,Ve)=>{const Le=!te.current&&!Ve;(N.value!==void 0&&N.value===ze||Le)&&K(Ie)},[N.value]),Me=n==="popper"?VNe:xnt,Oe=Me===VNe?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:m,collisionBoundary:f,collisionPadding:x,sticky:y,hideWhenDetached:_,avoidCollisions:b}:{};return e.jsx(fnt,{scope:r,content:C,viewport:E,onViewportChange:D,itemRefCallback:je,selectedItem:F,onItemLeave:xe,itemTextRefCallback:Ee,focusSelectedItem:ae,selectedItemText:B,position:n,isPositioned:Q,searchRef:de,children:e.jsx(uB,{as:sDt,allowPinchZoom:!0,children:e.jsx(cB,{asChild:!0,trapped:N.open,onMountAutoFocus:Ie=>{Ie.preventDefault()},onUnmountAutoFocus:dn(a,Ie=>{var ze;(ze=N.trigger)==null||ze.focus({preventScroll:!0}),Ie.preventDefault()}),children:e.jsx(WS,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Ie=>Ie.preventDefault(),onDismiss:()=>N.onOpenChange(!1),children:e.jsx(Me,{role:"listbox",id:N.contentId,"data-state":N.open?"open":"closed",dir:N.dir,onContextMenu:Ie=>Ie.preventDefault(),...j,...Oe,onPlaced:()=>W(!0),ref:R,style:{display:"flex",flexDirection:"column",outline:"none",...j.style},onKeyDown:dn(j.onKeyDown,Ie=>{const ze=Ie.ctrlKey||Ie.altKey||Ie.metaKey;if(Ie.key==="Tab"&&Ie.preventDefault(),!ze&&Ie.key.length===1&&fe(Ie.key),["ArrowUp","ArrowDown","Home","End"].includes(Ie.key)){let Le=Z().filter($e=>!$e.disabled).map($e=>$e.ref.current);if(["ArrowUp","End"].includes(Ie.key)&&(Le=Le.slice().reverse()),["ArrowUp","ArrowDown"].includes(Ie.key)){const $e=Ie.target,ve=Le.indexOf($e);Le=Le.slice(ve+1)}setTimeout(()=>ne(Le)),Ie.preventDefault()}})})})})})})});pnt.displayName=tDt;var rDt="SelectItemAlignedPosition",xnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,onPlaced:n,...a}=s,i=QS(bA,r),l=JS(bA,r),[o,c]=k.useState(null),[d,u]=k.useState(null),m=_i(t,R=>u(R)),f=Qxe(r),x=k.useRef(!1),y=k.useRef(!0),{viewport:_,selectedItem:b,selectedItemText:j,focusSelectedItem:N}=l,C=k.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&_&&b&&j){const R=i.trigger.getBoundingClientRect(),F=d.getBoundingClientRect(),O=i.valueNode.getBoundingClientRect(),B=j.getBoundingClientRect();if(i.dir!=="rtl"){const $e=B.left-F.left,ve=O.left-$e,Qe=R.left-ve,we=R.width+Qe,nt=Math.max(we,F.width),Se=window.innerWidth-s1,Ge=T9(ve,[s1,Math.max(s1,Se-nt)]);o.style.minWidth=we+"px",o.style.left=Ge+"px"}else{const $e=F.right-B.right,ve=window.innerWidth-O.right-$e,Qe=window.innerWidth-R.right-ve,we=R.width+Qe,nt=Math.max(we,F.width),Se=window.innerWidth-s1,Ge=T9(ve,[s1,Math.max(s1,Se-nt)]);o.style.minWidth=we+"px",o.style.right=Ge+"px"}const K=f(),Z=window.innerHeight-s1*2,Q=_.scrollHeight,W=window.getComputedStyle(d),te=parseInt(W.borderTopWidth,10),ne=parseInt(W.paddingTop,10),ae=parseInt(W.borderBottomWidth,10),ue=parseInt(W.paddingBottom,10),me=te+ne+Q+ue+ae,de=Math.min(b.offsetHeight*5,me),fe=window.getComputedStyle(_),je=parseInt(fe.paddingTop,10),xe=parseInt(fe.paddingBottom,10),Ee=R.top+R.height/2-s1,Me=Z-Ee,Oe=b.offsetHeight/2,Ie=b.offsetTop+Oe,ze=te+ne+Ie,Ve=me-ze;if(ze<=Ee){const $e=K.length>0&&b===K[K.length-1].ref.current;o.style.bottom="0px";const ve=d.clientHeight-_.offsetTop-_.offsetHeight,Qe=Math.max(Me,Oe+($e?xe:0)+ve+ae),we=ze+Qe;o.style.height=we+"px"}else{const $e=K.length>0&&b===K[0].ref.current;o.style.top="0px";const Qe=Math.max(Ee,te+_.offsetTop+($e?je:0)+Oe)+Ve;o.style.height=Qe+"px",_.scrollTop=ze-Ee+_.offsetTop}o.style.margin=`${s1}px 0`,o.style.minHeight=de+"px",o.style.maxHeight=Z+"px",n==null||n(),requestAnimationFrame(()=>x.current=!0)}},[f,i.trigger,i.valueNode,o,d,_,b,j,i.dir,n]);Gu(()=>C(),[C]);const[A,E]=k.useState();Gu(()=>{d&&E(window.getComputedStyle(d).zIndex)},[d]);const D=k.useCallback(R=>{R&&y.current===!0&&(C(),N==null||N(),y.current=!1)},[C,N]);return e.jsx(aDt,{scope:r,contentWrapper:o,shouldExpandOnScrollRef:x,onScrollButtonChange:D,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(Yn.div,{...a,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});xnt.displayName=rDt;var nDt="SelectPopperPosition",VNe=k.forwardRef((s,t)=>{const{__scopeSelect:r,align:n="start",collisionPadding:a=s1,...i}=s,l=Jxe(r);return e.jsx(aB,{...l,...i,ref:t,align:n,collisionPadding:a,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});VNe.displayName=nDt;var[aDt,sTe]=k8(bA,{}),HNe="SelectViewport",gnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,nonce:n,...a}=s,i=JS(HNe,r),l=sTe(HNe,r),o=_i(t,i.onViewportChange),c=k.useRef(0);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),e.jsx(Xxe.Slot,{scope:r,children:e.jsx(Yn.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:dn(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:f}=l;if(f!=null&&f.current&&m){const x=Math.abs(c.current-u.scrollTop);if(x>0){const y=window.innerHeight-s1*2,_=parseFloat(m.style.minHeight),b=parseFloat(m.style.height),j=Math.max(_,b);if(j0?A:0,m.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});gnt.displayName=HNe;var ynt="SelectGroup",[iDt,oDt]=k8(ynt),lDt=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=jm();return e.jsx(iDt,{scope:r,id:a,children:e.jsx(Yn.div,{role:"group","aria-labelledby":a,...n,ref:t})})});lDt.displayName=ynt;var vnt="SelectLabel",bnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=oDt(vnt,r);return e.jsx(Yn.div,{id:a.id,...n,ref:t})});bnt.displayName=vnt;var ime="SelectItem",[cDt,_nt]=k8(ime),wnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,value:n,disabled:a=!1,textValue:i,...l}=s,o=QS(ime,r),c=JS(ime,r),d=o.value===n,[u,m]=k.useState(i??""),[f,x]=k.useState(!1),y=_i(t,N=>{var C;return(C=c.itemRefCallback)==null?void 0:C.call(c,N,n,a)}),_=jm(),b=k.useRef("touch"),j=()=>{a||(o.onValueChange(n),o.onOpenChange(!1))};if(n==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return e.jsx(cDt,{scope:r,value:n,disabled:a,textId:_,isSelected:d,onItemTextChange:k.useCallback(N=>{m(C=>C||((N==null?void 0:N.textContent)??"").trim())},[]),children:e.jsx(Xxe.ItemSlot,{scope:r,value:n,disabled:a,textValue:u,children:e.jsx(Yn.div,{role:"option","aria-labelledby":_,"data-highlighted":f?"":void 0,"aria-selected":d&&f,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:y,onFocus:dn(l.onFocus,()=>x(!0)),onBlur:dn(l.onBlur,()=>x(!1)),onClick:dn(l.onClick,()=>{b.current!=="mouse"&&j()}),onPointerUp:dn(l.onPointerUp,()=>{b.current==="mouse"&&j()}),onPointerDown:dn(l.onPointerDown,N=>{b.current=N.pointerType}),onPointerMove:dn(l.onPointerMove,N=>{var C;b.current=N.pointerType,a?(C=c.onItemLeave)==null||C.call(c):b.current==="mouse"&&N.currentTarget.focus({preventScroll:!0})}),onPointerLeave:dn(l.onPointerLeave,N=>{var C;N.currentTarget===document.activeElement&&((C=c.onItemLeave)==null||C.call(c))}),onKeyDown:dn(l.onKeyDown,N=>{var A;((A=c.searchRef)==null?void 0:A.current)!==""&&N.key===" "||(K8t.includes(N.key)&&j(),N.key===" "&&N.preventDefault())})})})})});wnt.displayName=ime;var AO="SelectItemText",jnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,className:n,style:a,...i}=s,l=QS(AO,r),o=JS(AO,r),c=_nt(AO,r),d=Q8t(AO,r),[u,m]=k.useState(null),f=_i(t,j=>m(j),c.onItemTextChange,j=>{var N;return(N=o.itemTextRefCallback)==null?void 0:N.call(o,j,c.value,c.disabled)}),x=u==null?void 0:u.textContent,y=k.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:x},c.value),[c.disabled,c.value,x]),{onNativeOptionAdd:_,onNativeOptionRemove:b}=d;return Gu(()=>(_(y),()=>b(y)),[_,b,y]),e.jsxs(e.Fragment,{children:[e.jsx(Yn.span,{id:c.textId,...i,ref:f}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?vx.createPortal(i.children,l.valueNode):null]})});jnt.displayName=AO;var Nnt="SelectItemIndicator",knt=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s;return _nt(Nnt,r).isSelected?e.jsx(Yn.span,{"aria-hidden":!0,...n,ref:t}):null});knt.displayName=Nnt;var GNe="SelectScrollUpButton",Snt=k.forwardRef((s,t)=>{const r=JS(GNe,s.__scopeSelect),n=sTe(GNe,s.__scopeSelect),[a,i]=k.useState(!1),l=_i(t,n.onScrollButtonChange);return Gu(()=>{if(r.viewport&&r.isPositioned){let o=function(){const d=c.scrollTop>0;i(d)};const c=r.viewport;return o(),c.addEventListener("scroll",o),()=>c.removeEventListener("scroll",o)}},[r.viewport,r.isPositioned]),a?e.jsx(Tnt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=r;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});Snt.displayName=GNe;var WNe="SelectScrollDownButton",Cnt=k.forwardRef((s,t)=>{const r=JS(WNe,s.__scopeSelect),n=sTe(WNe,s.__scopeSelect),[a,i]=k.useState(!1),l=_i(t,n.onScrollButtonChange);return Gu(()=>{if(r.viewport&&r.isPositioned){let o=function(){const d=c.scrollHeight-c.clientHeight,u=Math.ceil(c.scrollTop)c.removeEventListener("scroll",o)}},[r.viewport,r.isPositioned]),a?e.jsx(Tnt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=r;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});Cnt.displayName=WNe;var Tnt=k.forwardRef((s,t)=>{const{__scopeSelect:r,onAutoScroll:n,...a}=s,i=JS("SelectScrollButton",r),l=k.useRef(null),o=Qxe(r),c=k.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return k.useEffect(()=>()=>c(),[c]),Gu(()=>{var u;const d=o().find(m=>m.ref.current===document.activeElement);(u=d==null?void 0:d.ref.current)==null||u.scrollIntoView({block:"nearest"})},[o]),e.jsx(Yn.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:dn(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(n,50))}),onPointerMove:dn(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(n,50))}),onPointerLeave:dn(a.onPointerLeave,()=>{c()})})}),dDt="SelectSeparator",Ent=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s;return e.jsx(Yn.div,{"aria-hidden":!0,...n,ref:t})});Ent.displayName=dDt;var KNe="SelectArrow",uDt=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=Jxe(r),i=QS(KNe,r),l=JS(KNe,r);return i.open&&l.position==="popper"?e.jsx(iB,{...a,...n,ref:t}):null});uDt.displayName=KNe;var hDt="SelectBubbleInput",Ant=k.forwardRef(({__scopeSelect:s,value:t,...r},n)=>{const a=k.useRef(null),i=_i(n,a),l=yB(t);return k.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const m=new Event("change",{bubbles:!0});u.call(o,t),o.dispatchEvent(m)}},[l,t]),e.jsx(Yn.select,{...r,style:{...LJe,...r.style},ref:i,defaultValue:t})});Ant.displayName=hDt;function Mnt(s){return s===""||s===void 0}function Int(s){const t=$u(s),r=k.useRef(""),n=k.useRef(0),a=k.useCallback(l=>{const o=r.current+l;t(o),function c(d){r.current=d,window.clearTimeout(n.current),d!==""&&(n.current=window.setTimeout(()=>c(""),1e3))}(o)},[t]),i=k.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return k.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,a,i]}function Pnt(s,t,r){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=r?s.indexOf(r):-1;let l=mDt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==r));const c=l.find(d=>d.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==r?c:void 0}function mDt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}var fDt=int,Lnt=lnt,pDt=dnt,xDt=unt,gDt=hnt,Dnt=mnt,yDt=gnt,Rnt=bnt,Ont=wnt,vDt=jnt,bDt=knt,Fnt=Snt,znt=Cnt,Bnt=Ent;const Ds=fDt,Fs=pDt,Ps=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(Lnt,{ref:n,className:zt("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...r,children:[t,e.jsx(xDt,{asChild:!0,children:e.jsx(Co,{className:"h-4 w-4 opacity-50"})})]}));Ps.displayName=Lnt.displayName;const $nt=k.forwardRef(({className:s,...t},r)=>e.jsx(Fnt,{ref:r,className:zt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(pg,{className:"h-4 w-4"})}));$nt.displayName=Fnt.displayName;const Unt=k.forwardRef(({className:s,...t},r)=>e.jsx(znt,{ref:r,className:zt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Co,{className:"h-4 w-4"})}));Unt.displayName=znt.displayName;const Ls=k.forwardRef(({className:s,children:t,position:r="popper",...n},a)=>e.jsx(gDt,{children:e.jsxs(Dnt,{ref:a,className:zt("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:r,...n,children:[e.jsx($nt,{}),e.jsx(yDt,{className:zt("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Unt,{})]})}));Ls.displayName=Dnt.displayName;const _Dt=k.forwardRef(({className:s,...t},r)=>e.jsx(Rnt,{ref:r,className:zt("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));_Dt.displayName=Rnt.displayName;const lt=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(Ont,{ref:n,className:zt("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(bDt,{children:e.jsx(la,{className:"h-4 w-4"})})}),e.jsx(vDt,{children:t})]}));lt.displayName=Ont.displayName;const wDt=k.forwardRef(({className:s,...t},r)=>e.jsx(Bnt,{ref:r,className:zt("-mx-1 my-1 h-px bg-muted",s),...t}));wDt.displayName=Bnt.displayName;const jDt=s=>pt({queryKey:["public-listings",s],queryFn:async()=>{let t=U.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city&&(t=t.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:r,error:n}=await t;if(n)throw n;return r}}),NDt=()=>pt({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await U.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const r=new Map,n=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=r.get(l);c?c.count++:r.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=n.get(l);c?c.count++:n.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(r.values()).sort((i,l)=>l.count-i.count),neighborhoods:Array.from(n.values()).sort((i,l)=>l.count-i.count),zips:Array.from(a.values()).sort((i,l)=>l.count-i.count)}}}),kDt=s=>pt({queryKey:["public-listing",s],queryFn:async()=>{const t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);let r=U.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, 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?r=r.eq("id",s):r=r.eq("slug",s);const{data:n,error:a}=await r.single();if(a)throw a;return n},enabled:!!s}),SDt=()=>Mt({mutationFn:async({listingId:s,agentId:t,firstName:r,lastName:n,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:m})=>{let f=null,x=null;if(l){const{data:j}=await U.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();j&&(f=j.id,x=j.sharing_agent_id)}const{data:y,error:_}=await U.from("listing_leads").insert({listing_id:s,agent_id:x||t,first_name:r,last_name:n,email:a,phone:i,share_id:f,referred_by_agent_id:x,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:m||null}).select().single();if(_)throw _;const{error:b}=await U.functions.invoke("process-listing-lead",{body:{leadId:y.id}});return b&&console.error("Error processing lead:",b),y}}),CDt=()=>Mt({mutationFn:async s=>{const{error:t}=await U.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),BFe="/assets/levelup-logo-color-BeKd2k_g.png",TDt={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"},EDt={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"},$Fe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},cq=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),RR=s=>new Intl.NumberFormat("en-US").format(s);function qnt({slugOverride:s}={}){var Yt,es,zs,sr,ms;const t=xo(),r=s||t.slugOrId,[n]=ic(),{data:a,isLoading:i}=kDt(r||""),l=SDt(),o=CDt(),c=n.get("ref"),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState(""),[E,D]=k.useState(""),[R,F]=k.useState("in_person"),[O,B]=k.useState("info"),[K,Z]=k.useState(!1),[Q,W]=k.useState(!1),[te,ne]=k.useState(null),[ae,ue]=k.useState(!1);k.useState(!1);const[me,de]=k.useState(!1),[fe,je]=k.useState(20),[xe,Ee]=k.useState(6.5),[Me,Oe]=k.useState(30),Ie=k.useRef(null),[ze,Ve]=k.useState(!1);k.useEffect(()=>{const gt=()=>Ve(window.scrollY>300);return window.addEventListener("scroll",gt,{passive:!0}),()=>window.removeEventListener("scroll",gt)},[]),k.useEffect(()=>{c&&o.mutate(c)},[c]),k.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[r]);const Le=(a==null?void 0:a.photos)||[],$e=Le.find(gt=>gt.is_primary)||Le[0],ve=k.useMemo(()=>{if(!(a!=null&&a.price))return 0;const gt=a.price*(1-fe/100),Ut=xe/100/12,ht=Me*12;return Ut===0?gt/ht:gt*Ut/(1-Math.pow(1+Ut,-ht))},[a==null?void 0:a.price,fe,xe,Me]),Qe=async()=>{const gt=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:gt})}catch{}else await navigator.clipboard.writeText(gt),he.success("Link copied to clipboard")},we=async gt=>{if(gt.preventDefault(),!d.trim()||!x.trim()||!a)return;const Ut=O==="showing";if(Ut&&!C){he.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:m.trim(),email:x.trim(),phone:_.trim(),shareToken:c,leadType:Ut?"showing_request":"info_request",preferredDate:Ut?C:null,preferredTime:Ut&&E||null,showingMode:Ut?R:null,message:j.trim()||null}),W(!0),he.success(Ut?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(ht){console.error("Lead submission error:",ht),he.error(`Failed to submit: ${ht.message||"Please try again"}`)}finally{Z(!1)}},nt=()=>{te!==null&&ne(te===0?Le.length-1:te-1)},Se=()=>{te!==null&&ne(te===Le.length-1?0:te+1)};if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(dr,{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(Vn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:BFe,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(Pn,{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(q,{asChild:!0,children:e.jsx(Vn,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const Ge=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,We=((es=(Yt=a.agent)==null?void 0:Yt.brokerage)==null?void 0:es.name)||((zs=a.agent)==null?void 0:zs.brokerage_name),Ce=a.latitude&&a.longitude?`https://maps.google.com/maps?q=${a.latitude},${a.longitude}&z=15&output=embed`:a.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${a.property_address}, ${a.city}, ${a.state}`)}&z=15&output=embed`:null,qe=a.description||"",et=qe.length>420,Ze=me||!et?qe:qe.slice(0,420).trimEnd()+"…",rt=a.page_config||{},ct=gt=>{var Ut;return(((Ut=rt.sections)==null?void 0:Ut[gt])??!0)!==!1},vt=Array.isArray(rt.addons)?rt.addons:[],kt=rt.custom_note||"",St=rt.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsxs("title",{children:[Ge," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${cq(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${$Fe[a.property_type]} in ${a.city}, ${a.state}. ${qe.slice(0,140)}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${a.slug||a.id}`}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),e.jsx("meta",{property:"og:title",content:Ge}),e.jsx("meta",{property:"og:description",content:`${cq(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}`}),$e&&e.jsx("meta",{property:"og:image",content:$e.photo_url}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Ge}),e.jsx("meta",{name:"twitter:description",content:`${cq(a.price)} · ${a.city}, ${a.state}`}),$e&&e.jsx("meta",{name:"twitter:image",content:$e.photo_url}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:a.property_address||`${a.city}, ${a.state} Home`,description:qe,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Le.map(gt=>gt.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 ${ze?"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(Vn,{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(Aa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),ze&&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(([gt,Ut])=>e.jsx("a",{href:`#${gt}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:Ut},gt))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C8t,{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:Qe,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(Ec,{className:"h-4 w-4 text-white"})}),e.jsx(q,{size:"sm",onClick:()=>ue(!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:Ie,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[$e?e.jsx("img",{src:$e.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(Xe,{className:`${TDt[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:EDt[a.status]}),Le.length>0&&e.jsxs("button",{onClick:()=>ne(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[e.jsx(Tp,{className:"h-3.5 w-3.5"}),Le.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:cq(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:RR(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(qi,{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}),We&&e.jsx("p",{className:"text-xs text-white/60",children:We})]}),e.jsx(q,{size:"sm",onClick:()=>ue(!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"]})]})})]}),ct("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:k0,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:of,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:C0,label:"Interior",value:`${RR(a.square_footage)} sqft`},a.lot_size&&{icon:m2,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:vn,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:__,label:"Price / sqft",value:`$${RR(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((gt,Ut)=>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(gt.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:gt.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:gt.value})]})]},Ut))})}),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:[ct("story")&&qe&&e.jsxs("section",{id:"story",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),e.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:e.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:Ze})}),et&&e.jsx("button",{onClick:()=>de(!me),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:me?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(Xe,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(Ga,{className:"h-3 w-3 mr-1.5"}),$Fe[a.property_type]]}),a.has_hoa&&e.jsx(Xe,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx(q,{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(un,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(kt||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(Ir,{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:['"',kt||a.agent_notes,'"']})]})]}),ct("gallery")&&Le.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>ne(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Le.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Le.slice(0,7).map((gt,Ut)=>{const ht=["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"],Jt=Ut===6&&Le.length>7;return e.jsxs("button",{onClick:()=>ne(Ut),className:`${ht[Ut]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:gt.photo_url,alt:`Photo ${Ut+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),Jt&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(Tp,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Le.length-7," more"]})]})]},gt.id)})})]}),ct("video")&&((sr=a.video)==null?void 0:sr.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"})})]}),ct("map")&&Ce&&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:Ce,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(Ma,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),ct("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:["$",RR(Math.round(ve))]}),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(ce,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[fe,"%"]})]}),e.jsx(nf,{value:[fe],onValueChange:gt=>je(gt[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",RR(Math.round(a.price*fe/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ce,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[xe.toFixed(2),"%"]})]}),e.jsx(nf,{value:[xe],onValueChange:gt=>Ee(gt[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(ce,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[Me," yr"]})]}),e.jsx(nf,{value:[Me],onValueChange:gt=>Oe(gt[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."})]})]}),vt.map(gt=>{const Ut=gt.type,ht=gt.data||{};if(Ut==="extra_video"&&ht.url){const Jt=String(ht.url).includes("youtu")?`https://www.youtube.com/embed/${String(ht.url).split(/[/=]/).pop()}`:ht.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:ht.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:ht.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Jt,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:ht.title||"Video"})})]},gt.id)}return Ut==="3d_tour"&&ht.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:ht.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:ht.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},gt.id):Ut==="floor_plan"&&ht.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:ht.title||"Layout"}),e.jsx("img",{src:ht.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},gt.id):Ut==="testimonial"&&ht.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:['"',ht.quote,'"']}),ht.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",ht.author]})]},gt.id):Ut==="custom_cta"&&ht.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:St?`${St}22`:"rgba(255,255,255,0.05)",border:`1px solid ${St||"rgba(255,255,255,0.1)"}`},children:[ht.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:ht.title}),e.jsx(q,{asChild:!0,size:"lg",style:St?{background:St}:void 0,children:e.jsx("a",{href:ht.url||"#agent",children:ht.label})})]},gt.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(qi,{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}),We&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:We})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx(q,{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(Mn,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx(q,{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(Ks,{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(UFe,{submitted:Q,activeTab:O,setActiveTab:B,firstName:d,setFirstName:u,lastName:m,setLastName:f,email:x,setEmail:y,phone:_,setPhone:b,message:j,setMessage:N,preferredDate:C,setPreferredDate:A,preferredTime:E,setPreferredTime:D,showingMode:R,setShowingMode:F,isSubmitting:K,onSubmit:we})})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-neutral-950/95 backdrop-blur-xl border-t border-white/10 px-4 py-3 flex items-center gap-2 safe-area-inset-bottom",children:[((ms=a.agent)==null?void 0:ms.phone)&&e.jsx(q,{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(Mn,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(q,{onClick:()=>ue(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(Xy,{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:BFe,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(vs,{open:te!==null,onOpenChange:()=>ne(null),children:e.jsxs(ys,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(_s,{className:"sr-only",children:e.jsx(bs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>ne(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx($r,{className:"h-5 w-5"})}),te!==null&&Le[te]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Le[te].photo_url,alt:`Photo ${te+1}`,className:"w-full max-h-[85vh] object-contain"}),Le.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:nt,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(jl,{className:"h-6 w-6"})}),e.jsx("button",{onClick:Se,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(Ia,{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:[te+1," / ",Le.length]})]})]})]})}),e.jsx(vs,{open:ae,onOpenChange:ue,children:e.jsxs(ys,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(_s,{className:"sr-only",children:e.jsx(bs,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(UFe,{submitted:Q,activeTab:O,setActiveTab:B,firstName:d,setFirstName:u,lastName:m,setLastName:f,email:x,setEmail:y,phone:_,setPhone:b,message:j,setMessage:N,preferredDate:C,setPreferredDate:A,preferredTime:E,setPreferredTime:D,showingMode:R,setShowingMode:F,isSubmitting:K,onSubmit:we})})]})})]})]})}function UFe(s){const{submitted:t,activeTab:r,setActiveTab:n,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:m,message:f,setMessage:x,preferredDate:y,setPreferredDate:_,preferredTime:b,setPreferredTime:j,showingMode:N,setShowingMode:C,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(la,{className:"h-7 w-7 text-emerald-600"})}),e.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:r==="showing"?"Showing request sent!":"Thanks — you're all set!"}),e.jsx("p",{className:"text-sm text-neutral-600",children:r==="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(ta,{value:r,onValueChange:D=>n(D),children:[e.jsxs(ea,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(rs,{value:"info",className:"gap-1.5",children:[e.jsx(Ui,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(rs,{value:"showing",className:"gap-1.5",children:[e.jsx(Xy,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:E,className:"space-y-3",children:[e.jsxs(fs,{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(ce,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(Ne,{id:"preferredDate",type:"date",value:y,onChange:D=>_(D.target.value),min:new Date().toISOString().split("T")[0],required:r==="showing"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(Ds,{value:b,onValueChange:j,children:[e.jsx(Ps,{id:"preferredTime",children:e.jsx(Fs,{placeholder:"Any time"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(lt,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(lt,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(Ds,{value:N,onValueChange:D=>C(D),children:[e.jsx(Ps,{id:"showingMode",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(lt,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(lt,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"firstName",children:"First Name *"}),e.jsx(Ne,{id:"firstName",value:a,onChange:D=>i(D.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"lastName",children:"Last Name"}),e.jsx(Ne,{id:"lastName",value:l,onChange:D=>o(D.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"email",children:"Email *"}),e.jsx(Ne,{id:"email",type:"email",value:c,onChange:D=>d(D.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(ce,{htmlFor:"phone",children:["Phone ",r==="showing"&&"*"]}),e.jsx(Ne,{id:"phone",type:"tel",value:u,onChange:D=>m(D.target.value),required:r==="showing"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"message",children:r==="showing"?"Anything else?":"Message (optional)"}),e.jsx(pr,{id:"message",value:f,onChange:D=>x(D.target.value),rows:2})]}),e.jsx(q,{type:"submit",disabled:A,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:A?"Sending…":r==="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 ome="/assets/levelup-logo-white-C2RAgAoG.png",ADt="/assets/listings-hero-noir-BHCJrhvU.jpg";var Vnt={exports:{}};(function(s,t){(function(r,n){s.exports=n()})(lh,function(){let r,n,a;function i(o,c){if(!r)r=c;else if(!n)n=c;else{const d={};r(d),a=c(d);const 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 = {}; ("+r+")(sharedChunk); ("+n+")(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(v,h){var p=h[0],w=h[1],T=h[2],I=h[3],L=p*I-T*w;return L?(v[0]=I*(L=1/L),v[1]=-w*L,v[2]=-T*L,v[3]=p*L,v):null}function m(){var v=new d(9);return d!=Float32Array&&(v[1]=0,v[2]=0,v[3]=0,v[5]=0,v[6]=0,v[7]=0),v[0]=1,v[4]=1,v[8]=1,v}function f(v,h){var p=h[0],w=h[1],T=h[2],I=h[3],L=h[4],$=h[5],V=h[6],X=h[7],re=h[8];return v[0]=L*re-$*X,v[1]=T*X-w*re,v[2]=w*$-T*L,v[3]=$*V-I*re,v[4]=p*re-T*V,v[5]=T*I-p*$,v[6]=I*X-L*V,v[7]=w*V-p*X,v[8]=p*L-w*I,v}function x(v,h,p){var w=h[0],T=h[1],I=h[2],L=h[3],$=h[4],V=h[5],X=h[6],re=h[7],oe=h[8],le=p[0],ge=p[1],_e=p[2],Te=p[3],Fe=p[4],He=p[5],ot=p[6],st=p[7],mt=p[8];return v[0]=le*w+ge*L+_e*X,v[1]=le*T+ge*$+_e*re,v[2]=le*I+ge*V+_e*oe,v[3]=Te*w+Fe*L+He*X,v[4]=Te*T+Fe*$+He*re,v[5]=Te*I+Fe*V+He*oe,v[6]=ot*w+st*L+mt*X,v[7]=ot*T+st*$+mt*re,v[8]=ot*I+st*V+mt*oe,v}function y(){var v=new d(16);return d!=Float32Array&&(v[1]=0,v[2]=0,v[3]=0,v[4]=0,v[6]=0,v[7]=0,v[8]=0,v[9]=0,v[11]=0,v[12]=0,v[13]=0,v[14]=0),v[0]=1,v[5]=1,v[10]=1,v[15]=1,v}function _(v){var h=new d(16);return h[0]=v[0],h[1]=v[1],h[2]=v[2],h[3]=v[3],h[4]=v[4],h[5]=v[5],h[6]=v[6],h[7]=v[7],h[8]=v[8],h[9]=v[9],h[10]=v[10],h[11]=v[11],h[12]=v[12],h[13]=v[13],h[14]=v[14],h[15]=v[15],h}function b(v){return v[0]=1,v[1]=0,v[2]=0,v[3]=0,v[4]=0,v[5]=1,v[6]=0,v[7]=0,v[8]=0,v[9]=0,v[10]=1,v[11]=0,v[12]=0,v[13]=0,v[14]=0,v[15]=1,v}function j(v,h){var p=h[0],w=h[1],T=h[2],I=h[3],L=h[4],$=h[5],V=h[6],X=h[7],re=h[8],oe=h[9],le=h[10],ge=h[11],_e=h[12],Te=h[13],Fe=h[14],He=h[15],ot=p*$-w*L,st=p*V-T*L,mt=p*X-I*L,bt=w*V-T*$,wt=w*X-I*$,Gt=T*X-I*V,Ot=re*Te-oe*_e,Ht=re*Fe-le*_e,Bt=re*He-ge*_e,$t=oe*Fe-le*Te,Es=oe*He-ge*Te,Os=le*He-ge*Fe,Hs=ot*Os-st*Es+mt*$t+bt*Bt-wt*Ht+Gt*Ot;return Hs?(v[0]=($*Os-V*Es+X*$t)*(Hs=1/Hs),v[1]=(T*Es-w*Os-I*$t)*Hs,v[2]=(Te*Gt-Fe*wt+He*bt)*Hs,v[3]=(le*wt-oe*Gt-ge*bt)*Hs,v[4]=(V*Bt-L*Os-X*Ht)*Hs,v[5]=(p*Os-T*Bt+I*Ht)*Hs,v[6]=(Fe*mt-_e*Gt-He*st)*Hs,v[7]=(re*Gt-le*mt+ge*st)*Hs,v[8]=(L*Es-$*Bt+X*Ot)*Hs,v[9]=(w*Bt-p*Es-I*Ot)*Hs,v[10]=(_e*wt-Te*mt+He*ot)*Hs,v[11]=(oe*mt-re*wt-ge*ot)*Hs,v[12]=($*Ht-L*$t-V*Ot)*Hs,v[13]=(p*$t-w*Ht+T*Ot)*Hs,v[14]=(Te*st-_e*bt-Fe*ot)*Hs,v[15]=(re*bt-oe*st+le*ot)*Hs,v):null}function N(v,h,p){var w=h[0],T=h[1],I=h[2],L=h[3],$=h[4],V=h[5],X=h[6],re=h[7],oe=h[8],le=h[9],ge=h[10],_e=h[11],Te=h[12],Fe=h[13],He=h[14],ot=h[15],st=p[0],mt=p[1],bt=p[2],wt=p[3];return v[0]=st*w+mt*$+bt*oe+wt*Te,v[1]=st*T+mt*V+bt*le+wt*Fe,v[2]=st*I+mt*X+bt*ge+wt*He,v[3]=st*L+mt*re+bt*_e+wt*ot,v[4]=(st=p[4])*w+(mt=p[5])*$+(bt=p[6])*oe+(wt=p[7])*Te,v[5]=st*T+mt*V+bt*le+wt*Fe,v[6]=st*I+mt*X+bt*ge+wt*He,v[7]=st*L+mt*re+bt*_e+wt*ot,v[8]=(st=p[8])*w+(mt=p[9])*$+(bt=p[10])*oe+(wt=p[11])*Te,v[9]=st*T+mt*V+bt*le+wt*Fe,v[10]=st*I+mt*X+bt*ge+wt*He,v[11]=st*L+mt*re+bt*_e+wt*ot,v[12]=(st=p[12])*w+(mt=p[13])*$+(bt=p[14])*oe+(wt=p[15])*Te,v[13]=st*T+mt*V+bt*le+wt*Fe,v[14]=st*I+mt*X+bt*ge+wt*He,v[15]=st*L+mt*re+bt*_e+wt*ot,v}function C(v,h,p){var w,T,I,L,$,V,X,re,oe,le,ge,_e,Te=p[0],Fe=p[1],He=p[2];return h===v?(v[12]=h[0]*Te+h[4]*Fe+h[8]*He+h[12],v[13]=h[1]*Te+h[5]*Fe+h[9]*He+h[13],v[14]=h[2]*Te+h[6]*Fe+h[10]*He+h[14],v[15]=h[3]*Te+h[7]*Fe+h[11]*He+h[15]):(T=h[1],I=h[2],L=h[3],$=h[4],V=h[5],X=h[6],re=h[7],oe=h[8],le=h[9],ge=h[10],_e=h[11],v[0]=w=h[0],v[1]=T,v[2]=I,v[3]=L,v[4]=$,v[5]=V,v[6]=X,v[7]=re,v[8]=oe,v[9]=le,v[10]=ge,v[11]=_e,v[12]=w*Te+$*Fe+oe*He+h[12],v[13]=T*Te+V*Fe+le*He+h[13],v[14]=I*Te+X*Fe+ge*He+h[14],v[15]=L*Te+re*Fe+_e*He+h[15]),v}function A(v,h,p){var w=p[0],T=p[1],I=p[2];return v[0]=h[0]*w,v[1]=h[1]*w,v[2]=h[2]*w,v[3]=h[3]*w,v[4]=h[4]*T,v[5]=h[5]*T,v[6]=h[6]*T,v[7]=h[7]*T,v[8]=h[8]*I,v[9]=h[9]*I,v[10]=h[10]*I,v[11]=h[11]*I,v[12]=h[12],v[13]=h[13],v[14]=h[14],v[15]=h[15],v}function E(v,h,p){var w=Math.sin(p),T=Math.cos(p),I=h[4],L=h[5],$=h[6],V=h[7],X=h[8],re=h[9],oe=h[10],le=h[11];return h!==v&&(v[0]=h[0],v[1]=h[1],v[2]=h[2],v[3]=h[3],v[12]=h[12],v[13]=h[13],v[14]=h[14],v[15]=h[15]),v[4]=I*T+X*w,v[5]=L*T+re*w,v[6]=$*T+oe*w,v[7]=V*T+le*w,v[8]=X*T-I*w,v[9]=re*T-L*w,v[10]=oe*T-$*w,v[11]=le*T-V*w,v}function D(v,h,p){var w=Math.sin(p),T=Math.cos(p),I=h[0],L=h[1],$=h[2],V=h[3],X=h[8],re=h[9],oe=h[10],le=h[11];return h!==v&&(v[4]=h[4],v[5]=h[5],v[6]=h[6],v[7]=h[7],v[12]=h[12],v[13]=h[13],v[14]=h[14],v[15]=h[15]),v[0]=I*T-X*w,v[1]=L*T-re*w,v[2]=$*T-oe*w,v[3]=V*T-le*w,v[8]=I*w+X*T,v[9]=L*w+re*T,v[10]=$*w+oe*T,v[11]=V*w+le*T,v}function R(v,h,p){var w=Math.sin(p),T=Math.cos(p),I=h[0],L=h[1],$=h[2],V=h[3],X=h[4],re=h[5],oe=h[6],le=h[7];return h!==v&&(v[8]=h[8],v[9]=h[9],v[10]=h[10],v[11]=h[11],v[12]=h[12],v[13]=h[13],v[14]=h[14],v[15]=h[15]),v[0]=I*T+X*w,v[1]=L*T+re*w,v[2]=$*T+oe*w,v[3]=V*T+le*w,v[4]=X*T-I*w,v[5]=re*T-L*w,v[6]=oe*T-$*w,v[7]=le*T-V*w,v}function F(v,h){return v[0]=h[0],v[1]=0,v[2]=0,v[3]=0,v[4]=0,v[5]=h[1],v[6]=0,v[7]=0,v[8]=0,v[9]=0,v[10]=h[2],v[11]=0,v[12]=0,v[13]=0,v[14]=0,v[15]=1,v}function O(v,h,p){var w,T,I,L=p[0],$=p[1],V=p[2],X=Math.sqrt(L*L+$*$+V*V);return X0&&(I=1/Math.sqrt(I)),v[0]=h[0]*I,v[1]=h[1]*I,v[2]=h[2]*I,v}function Le(v,h){return v[0]*h[0]+v[1]*h[1]+v[2]*h[2]}function $e(v,h,p){var w=h[0],T=h[1],I=h[2],L=p[0],$=p[1],V=p[2];return v[0]=T*V-I*$,v[1]=I*L-w*V,v[2]=w*$-T*L,v}function ve(v,h,p,w){var T=h[0],I=h[1],L=h[2];return v[0]=T+w*(p[0]-T),v[1]=I+w*(p[1]-I),v[2]=L+w*(p[2]-L),v}function Qe(v,h,p){var w=h[0],T=h[1],I=h[2],L=p[3]*w+p[7]*T+p[11]*I+p[15];return v[0]=(p[0]*w+p[4]*T+p[8]*I+p[12])/(L=L||1),v[1]=(p[1]*w+p[5]*T+p[9]*I+p[13])/L,v[2]=(p[2]*w+p[6]*T+p[10]*I+p[14])/L,v}function we(v,h,p){var w=h[0],T=h[1],I=h[2];return v[0]=w*p[0]+T*p[3]+I*p[6],v[1]=w*p[1]+T*p[4]+I*p[7],v[2]=w*p[2]+T*p[5]+I*p[8],v}function nt(v,h,p){var w=p[0],T=p[1],I=p[2],L=p[3],$=h[0],V=h[1],X=h[2],re=T*X-I*V,oe=I*$-w*X,le=w*V-T*$;return v[0]=$+L*(re+=re)+T*(le+=le)-I*(oe+=oe),v[1]=V+L*oe+I*re-w*le,v[2]=X+L*le+w*oe-T*re,v}function Se(v){return v[0]=0,v[1]=0,v[2]=0,v}function Ge(v,h){return v[0]===h[0]&&v[1]===h[1]&&v[2]===h[2]}var We=me,Ce=de,qe=te;function et(){var v=new d(4);return d!=Float32Array&&(v[0]=0,v[1]=0,v[2]=0,v[3]=0),v}function Ze(v,h,p){return v[0]=h[0]*p,v[1]=h[1]*p,v[2]=h[2]*p,v[3]=h[3]*p,v}function rt(v,h){var p=h[0],w=h[1],T=h[2],I=h[3],L=p*p+w*w+T*T+I*I;return L>0&&(L=1/Math.sqrt(L)),v[0]=p*L,v[1]=w*L,v[2]=T*L,v[3]=I*L,v}function ct(v,h){return v[0]*h[0]+v[1]*h[1]+v[2]*h[2]+v[3]*h[3]}function vt(v,h,p){var w=h[0],T=h[1],I=h[2],L=h[3];return v[0]=p[0]*w+p[4]*T+p[8]*I+p[12]*L,v[1]=p[1]*w+p[5]*T+p[9]*I+p[13]*L,v[2]=p[2]*w+p[6]*T+p[10]*I+p[14]*L,v[3]=p[3]*w+p[7]*T+p[11]*I+p[15]*L,v}function kt(){var v=new d(4);return d!=Float32Array&&(v[0]=0,v[1]=0,v[2]=0),v[3]=1,v}function St(v){return v[0]=0,v[1]=0,v[2]=0,v[3]=1,v}function Yt(v,h,p){p*=.5;var w=h[0],T=h[1],I=h[2],L=h[3],$=Math.sin(p),V=Math.cos(p);return v[0]=w*V+L*$,v[1]=T*V+I*$,v[2]=I*V-T*$,v[3]=L*V-w*$,v}function es(v,h,p){p*=.5;var w=h[0],T=h[1],I=h[2],L=h[3],$=Math.sin(p),V=Math.cos(p);return v[0]=w*V-I*$,v[1]=T*V+L*$,v[2]=I*V+w*$,v[3]=L*V-T*$,v}Q(),et();var zs,sr,ms,gt=rt,Ut=(zs=Q(),sr=ne(1,0,0),ms=ne(0,1,0),function(v,h,p){var w=Le(h,p);return w<-.999999?($e(zs,sr,h),qe(zs)<1e-6&&$e(zs,ms,h),Ve(zs,zs),function(T,I,L){L*=.5;var $=Math.sin(L);T[0]=$*I[0],T[1]=$*I[1],T[2]=$*I[2],T[3]=Math.cos(L)}(v,zs,Math.PI),v):w>.999999?(v[0]=0,v[1]=0,v[2]=0,v[3]=1,v):($e(zs,h,p),v[0]=zs[0],v[1]=zs[1],v[2]=zs[2],v[3]=1+w,gt(v,v))});function ht(){var v=new d(2);return d!=Float32Array&&(v[0]=0,v[1]=0),v}function Jt(v,h){var p=new d(2);return p[0]=v,p[1]=h,p}function Ms(v,h,p){return v[0]=h,v[1]=p,v}function ts(v,h,p){return v[0]=h[0]+p[0],v[1]=h[1]+p[1],v}function Xs(v,h,p){return v[0]=h[0]-p[0],v[1]=h[1]-p[1],v}function js(v,h,p){return v[0]=h[0]*p,v[1]=h[1]*p,v}function $s(v){var h=v[0],p=v[1];return Math.sqrt(h*h+p*p)}function Js(v,h){var p=h[0],w=h[1],T=p*p+w*w;return T>0&&(T=1/Math.sqrt(T)),v[0]=h[0]*T,v[1]=h[1]*T,v}function or(v,h){return v[0]*h[0]+v[1]*h[1]}kt(),kt(),m();var Er,Sr,Gr=Xs;function Yr(v){return v&&v.__esModule&&Object.prototype.hasOwnProperty.call(v,"default")?v.default:v}ht();var Fn=function(){if(Sr)return Er;function v(h,p,w,T){this.cx=3*h,this.bx=3*(w-h)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*p,this.by=3*(T-p)-this.cy,this.ay=1-this.cy-this.by,this.p1x=h,this.p1y=p,this.p2x=w,this.p2y=T}return Sr=1,Er=v,v.prototype={sampleCurveX:function(h){return((this.ax*h+this.bx)*h+this.cx)*h},sampleCurveY:function(h){return((this.ay*h+this.by)*h+this.cy)*h},sampleCurveDerivativeX:function(h){return(3*this.ax*h+2*this.bx)*h+this.cx},solveCurveX:function(h,p){if(p===void 0&&(p=1e-6),h<0)return 0;if(h>1)return 1;for(var w=h,T=0;T<8;T++){var I=this.sampleCurveX(w)-h;if(Math.abs(I)I?$=w:V=w,w=.5*(V-$)+$;return w},solve:function(h,p){return this.sampleCurveY(this.solveCurveX(h,p))}},Er}(),sa=Yr(Fn);function gs(v,h){this.x=v,this.y=h}function mi(v,h){if(Array.isArray(v)){if(!Array.isArray(h)||v.length!==h.length)return!1;for(let p=0;p=1)return 1;const h=v*v,p=h*v;return 4*(v<.5?p:3*(v-h)+p-.75)}function Qt(v,h,p,w){const T=new sa(v,h,p,w);return function(I){return T.solve(I)}}const Re=Qt(.25,.1,.25,1);function Ke(v,h,p){return Math.min(p,Math.max(h,v))}function at(v,h,p){return(p=Ke((p-v)/(h-v),0,1))*p*(3-2*p)}function Nt(v,h,p){const w=p-h,T=((v-h)%w+w)%w+h;return T===h?p:T}function Ft(v,h,p){if(!v.length)return p(null,[]);let w=v.length;const T=new Array(v.length);let I=null;v.forEach((L,$)=>{h(L,(V,X)=>{V&&(I=V),T[$]=X,--w===0&&p(I,T)})})}let qt=1;function cs(){return qt++}function it(v){return v<=1?1:Math.pow(2,Math.ceil(Math.log2(v)))}function Xt(v,h){v.forEach(p=>{h[p]&&(h[p]=h[p].bind(h))})}function Bs(v,h,p){const w={};for(const T in v)w[T]=h.call(this,v[T],T,v);return w}function us(v,h,p){const w={};for(const T in v)h.call(this,v[T],T,v)&&(w[T]=v[T]);return w}function cr(v){return Array.isArray(v)?v.map(cr):typeof v=="object"&&v?Bs(v,cr):v}function Ar(v,h){for(let p=0;p=0)return!0;return!1}const xr={};function Kr(v){xr[v]||(typeof console<"u"&&console.warn(v),xr[v]=!0)}function mn(v,h,p){return(p.y-v.y)*(h.x-v.x)>(h.y-v.y)*(p.x-v.x)}function pn(v){let h=0;for(let p,w,T=0,I=v.length,L=I-1;T@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(p,w,T,I)=>{const L=T||I;return h[w]=!L||L.toLowerCase(),""}),h["max-age"]){const p=parseInt(h["max-age"],10);isNaN(p)?delete h["max-age"]:h["max-age"]=p}return h}let so,Ka=null;function kn(v,h){return[v[4*h],v[4*h+1],v[4*h+2],v[4*h+3]]}function Fi(v,h,p,w){for(;h>1;v[T]>1;v[T]<=w?h=T+1:p=T}return h}function Qa(v){return v>0?1/(1.001-v):1+v}function Hi(v){return v>0?1-1/(1.001-v):-v}function Gi(v,h,p){return(v-h.min)*(p.max-p.min)/(h.max-h.min)+p.min}const Qn={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(!Qn.API_URL)return null;try{const v=new URL(Qn.API_URL);return v.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":v.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 vr(){return new URL(Qn.DRACO_URL,Qn.API_URL).href}function Ca(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(so===void 0){if(typeof WebAssembly!="object")return!1;const v=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]);so=WebAssembly.validate(v)}return so}()?Qn.MESHOPT_SIMD_URL:Qn.MESHOPT_URL,Qn.API_URL).href}function Ji(){return new URL(Qn.BUILDING_GEN_URL,Qn.API_URL).href}function Zo(v){return Qn.API_URL_REGEX.test(v)}function vl(v){return Qn.API_SPRITE_REGEX.test(v)}let vo,hd,ju,sp,Nu,qh;function ku(){return vo==null&&(vo=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),vo}const Cd={now:()=>sp!==void 0?sp:performance.now(),setNow(v){sp=v},restoreNow(){sp=void 0},frame(v){const h=requestAnimationFrame(v);return{cancel:()=>cancelAnimationFrame(h)}},getImageData(v,h=0){const{width:p,height:w}=v;Nu||(Nu=document.createElement("canvas"));const T=Nu.getContext("2d",{willReadFrequently:!0});if(!T)throw new Error("failed to create canvas 2d context");return(p>Nu.width||w>Nu.height)&&(Nu.width=p,Nu.height=w),T.clearRect(-h,-h,p+2*h,w+2*h),T.drawImage(v,0,0,p,w),T.getImageData(-h,-h,p+2*h,w+2*h)},resolveURL:v=>(hd||(hd=document.createElement("a")),hd.href=v,hd.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(ju==null&&(ju=window.matchMedia("(prefers-reduced-motion: reduce)")),ju.matches)},hasCanvasFingerprintNoise(){if(qh!==void 0)return qh;if(!ku())return qh=!1,!1;const v=new OffscreenCanvas(85,1),h=v.getContext("2d",{willReadFrequently:!0});let p=0;for(let T=0;T0?`?${I}`:""}`}const Vh="mapbox-tiles";let K0=500,Y0=50;const rp=["language","worldview","jobid"];let Xu;function Bp(){try{return caches}catch{}}function co(){const v=Bp();v&&Xu==null&&(Xu=v.open(Vh))}let X1=1/0;const Hh={supported:!1,testSupport:function(v){!Su&&$p&&(Xo?Xd(v):vh=v)}};let vh,$p,Su=!1,Xo=!1;const Pg=typeof self<"u"?self:{};function Xd(v){const h=v.createTexture();v.bindTexture(v.TEXTURE_2D,h);try{if(v.texImage2D(v.TEXTURE_2D,0,v.RGBA,v.RGBA,v.UNSIGNED_BYTE,$p),v.isContextLost())return;Hh.supported=!0}catch{}v.deleteTexture(h),Su=!0}Pg.document&&($p=Pg.document.createElement("img"),$p.onload=function(){vh&&Xd(vh),vh=null,Xo=!0},$p.onerror=function(){Su=!0,vh=null},$p.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const Lg={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(Lg);class yw extends Error{constructor(h,p,w){p===401&&Zo(w)&&(h+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(h),this.status=p,this.url=w}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function np(v){return typeof v=="object"&&v!==null&&"status"in v&&v.status===404}const qa=ca()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Z0=function(v,h){return/^file:/.test(p=v.url)||/^file:/.test(qa())&&!/^\w+:/.test(p)?function(w,T){const I=new XMLHttpRequest;I.open(w.method||"GET",w.url,!0),w.type==="arrayBuffer"&&(I.responseType="arraybuffer");for(const L in w.headers)I.setRequestHeader(L,w.headers[L]);return w.type==="json"&&(I.responseType="text",I.setRequestHeader("Accept","application/json")),I.withCredentials=w.credentials==="include",I.onerror=()=>{T(new Error(I.statusText))},I.onload=()=>{if((I.status>=200&&I.status<300||I.status===0)&&I.response!==null){let L=I.response;if(w.type==="json")try{L=JSON.parse(I.response)}catch(V){return T(V)}const $=new Headers;I.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(V=>{const X=V.split(": "),re=X.shift(),oe=X.join(": ");$.append(re,oe)}),T(null,L,$)}else T(new yw(I.statusText,I.status,w.url))},I.send(w.body),{cancel:()=>I.abort()}}(v,h):function(w,T){const I=new AbortController,L=new Request(w.url,{method:w.method||"GET",body:w.body,credentials:w.credentials,headers:w.headers,referrer:qa(),referrerPolicy:w.referrerPolicy,signal:I.signal});let $=!1,V=!1;const X=(re=L.url).indexOf("sku=")>0&&Zo(re);var re;w.type==="json"&&L.headers.set("Accept","application/json");const oe=(ge,_e,Te)=>{if(V)return;if(ge&&ge.message!=="SecurityError"&&Kr(ge.toString()),_e&&Te)return le(_e);const Fe=Date.now();fetch(L).then(He=>{if(He.ok){const ot=X?He.clone():null;return le(He,ot,Fe)}return T(new yw(He.statusText,He.status,w.url))}).catch(He=>{He.name!=="AbortError"&&T(new Error(`${He.message} ${w.url}`))})},le=(ge,_e,Te)=>{(w.type==="arrayBuffer"?ge.arrayBuffer():w.type==="json"?ge.json():ge.text()).then(Fe=>{V||(_e&&Te&&function(He,ot,st){if(co(),Xu==null)return;const mt=Vi(ot.headers.get("cache-control")||"");if(mt["no-store"])return;const bt={status:ot.status,statusText:ot.statusText,headers:new Headers};ot.headers.forEach((Bt,$t)=>bt.headers.set($t,Bt)),mt["max-age"]&&bt.headers.set("Expires",new Date(st+1e3*mt["max-age"]).toUTCString());const wt=bt.headers.get("expires");if(!wt||new Date(wt).getTime()-st<42e4)return;let Gt=gw(He.url,{persistentParams:rp});if(ot.status===206){const Bt=He.headers.get("Range");if(!Bt)return;bt.status=200,Gt=vv(Gt,{range:Bt})}const Ot=new Response((Ht=ot.status)!==200&&Ht!==404&&[101,103,204,205,304].includes(Ht)?null:ot.body,bt);var Ht;co(),Xu!=null&&Xu.then(Bt=>Bt.put(Gt,Ot)).catch(Bt=>Kr(Bt.message))}(L,_e,Te),$=!0,T(null,Fe,ge.headers))}).catch(Fe=>{V||T(new Error(Fe.message))})};return X?function(ge,_e){if(co(),Xu==null)return _e(null);Xu.then(Te=>{let Fe=gw(ge.url,{persistentParams:rp});const He=ge.headers.get("Range");He&&(Fe=vv(Fe,{range:He})),Te.match(Fe).then(ot=>{const st=function(mt){if(!mt)return!1;const bt=new Date(mt.headers.get("expires")||0),wt=Vi(mt.headers.get("cache-control")||"");return Number(bt)>Date.now()&&!wt["no-cache"]}(ot);Te.delete(Fe).catch(_e),st&&Te.put(Fe,ot.clone()).catch(_e),_e(null,ot,st)}).catch(_e)}).catch(_e)}(L,oe):oe(null,null),{cancel:()=>{V=!0,$||I.abort()}}}(v,h);var p},X0=function(v,h){return Z0(Object.assign(v,{type:"arrayBuffer"}),h)};function Mm(v){const h=document.createElement("a");return h.href=v,h.protocol===location.protocol&&h.host===location.host}let Im,ff;Im=[],ff=0;const Up=function(v,h){if(Hh.supported&&(v.headers||(v.headers={}),v.headers.accept="image/webp,*/*"),ff>=Qn.MAX_PARALLEL_IMAGE_REQUESTS){const I={requestParameters:v,callback:h,cancelled:!1,cancel(){this.cancelled=!0}};return Im.push(I),I}ff++;let p=!1;const w=()=>{if(!p)for(p=!0,ff--;Im.length&&ff{w(),I?h(I):L&&function(V,X){const re=new Blob([new Uint8Array(V)],{type:"image/png"});createImageBitmap(re).then(oe=>{X(null,oe)}).catch(oe=>{X(new Error(`Could not load image because of ${oe.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(L,(V,X)=>h(V,X,$))});return{cancel:()=>{T.cancel(),w()}}};var Rx,Q1,pf,Pm={exports:{}},ap={exports:{}},Q0={exports:{}},J1=function(){if(pf)return Pm.exports;pf=1;var v=(Rx||(Rx=1,ap.exports=function(p,w){var T,I,L,$,V,X,re,oe;for(I=p.length-(T=3&p.length),L=w,V=3432918353,X=461845907,oe=0;oe>>16)*V&65535)<<16)&4294967295)<<15|re>>>17))*X+(((re>>>16)*X&65535)<<16)&4294967295)<<13|L>>>19))+((5*(L>>>16)&65535)<<16)&4294967295))+((($>>>16)+58964&65535)<<16);switch(re=0,T){case 3:re^=(255&p.charCodeAt(oe+2))<<16;case 2:re^=(255&p.charCodeAt(oe+1))<<8;case 1:L^=re=(65535&(re=(re=(65535&(re^=255&p.charCodeAt(oe)))*V+(((re>>>16)*V&65535)<<16)&4294967295)<<15|re>>>17))*X+(((re>>>16)*X&65535)<<16)&4294967295}return L^=p.length,L=2246822507*(65535&(L^=L>>>16))+((2246822507*(L>>>16)&65535)<<16)&4294967295,L=3266489909*(65535&(L^=L>>>13))+((3266489909*(L>>>16)&65535)<<16)&4294967295,(L^=L>>>16)>>>0}),ap.exports),h=(Q1||(Q1=1,Q0.exports=function(p,w){for(var T,I=p.length,L=w^I,$=0;I>=4;)T=1540483477*(65535&(T=255&p.charCodeAt($)|(255&p.charCodeAt(++$))<<8|(255&p.charCodeAt(++$))<<16|(255&p.charCodeAt(++$))<<24))+((1540483477*(T>>>16)&65535)<<16),L=1540483477*(65535&L)+((1540483477*(L>>>16)&65535)<<16)^(T=1540483477*(65535&(T^=T>>>24))+((1540483477*(T>>>16)&65535)<<16)),I-=4,++$;switch(I){case 3:L^=(255&p.charCodeAt($+2))<<16;case 2:L^=(255&p.charCodeAt($+1))<<8;case 1:L=1540483477*(65535&(L^=255&p.charCodeAt($)))+((1540483477*(L>>>16)&65535)<<16)}return L=1540483477*(65535&(L^=L>>>13))+((1540483477*(L>>>16)&65535)<<16),(L^=L>>>15)>>>0}),Q0.exports);return Pm.exports=v,Pm.exports.murmur3=v,Pm.exports.murmur2=h,Pm.exports}(),md=Yr(J1);class _c{constructor(h,...p){Object.assign(this,p[0]||{}),this.type=h}}class Lm extends _c{constructor(h,p={}){super("error",Object.assign({error:h},p))}}function Mc(v,h,p){p[v]&&p[v].indexOf(h)!==-1||(p[v]=p[v]||[],p[v].push(h))}function Dm(v,h,p){if(p&&p[v]){const w=p[v].indexOf(h);w!==-1&&p[v].splice(w,1)}}class xf{on(h,p){return this._listeners=this._listeners||{},Mc(h,p,this._listeners),this}off(h,p){return Dm(h,p,this._listeners),Dm(h,p,this._oneTimeListeners),this}once(h,p){return p?(this._oneTimeListeners=this._oneTimeListeners||{},Mc(h,p,this._oneTimeListeners),this):new Promise(w=>{this.once(h,w)})}fire(h,p){const w=typeof h=="string"?new _c(h,p):h,T=w.type;if(this.listens(T)){w.target=this;const I=this._listeners&&this._listeners[T]?this._listeners[T].slice():[];for(const V of I)V.call(this,w);const L=this._oneTimeListeners&&this._oneTimeListeners[T]?this._oneTimeListeners[T].slice():[];for(const V of L)Dm(T,V,this._oneTimeListeners),V.call(this,w);const $=this._eventedParent;if($){const V=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(w,V),$.fire(w)}}else w instanceof Lm&&console.error(w.error);return this}listens(h){return!!(this._listeners&&this._listeners[h]&&this._listeners[h].length>0||this._oneTimeListeners&&this._oneTimeListeners[h]&&this._oneTimeListeners[h].length>0||this._eventedParent&&this._eventedParent.listens(h))}setEventedParent(h,p){return this._eventedParent=h,this._eventedParentData=p,this}}class It{constructor(h){typeof h=="string"?this.name=h:(this.name=h.name,this.iconsetId=h.iconsetId)}static from(h){return new It(h)}static toString(h){return h.iconsetId?`${h.name}${h.iconsetId}`:h.name}static parse(h){const[p,w]=h.split("");return new It({name:p,iconsetId:w})}static isEqual(h,p){return h.name===p.name&&h.iconsetId===p.iconsetId}toString(){return It.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var ar,Pr={},Sn=function(){if(ar)return Pr;ar=1;var v={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 h(I){return(I=Math.round(I))<0?0:I>255?255:I}function p(I){return h(I[I.length-1]==="%"?parseFloat(I)/100*255:parseInt(I))}function w(I){return(L=I[I.length-1]==="%"?parseFloat(I)/100:parseFloat(I))<0?0:L>1?1:L;var L}function T(I,L,$){return $<0?$+=1:$>1&&($-=1),6*$<1?I+(L-I)*$*6:2*$<1?L:3*$<2?I+(L-I)*(2/3-$)*6:I}try{Pr.parseCSSColor=function(I){var L,$=I.replace(/ /g,"").toLowerCase();if($ in v)return v[$].slice();if($[0]==="#")return $.length===4?(L=parseInt($.substr(1),16))>=0&&L<=4095?[(3840&L)>>4|(3840&L)>>8,240&L|(240&L)>>4,15&L|(15&L)<<4,1]:null:$.length===7&&(L=parseInt($.substr(1),16))>=0&&L<=16777215?[(16711680&L)>>16,(65280&L)>>8,255&L,1]:null;var V=$.indexOf("("),X=$.indexOf(")");if(V!==-1&&X+1===$.length){var re=$.substr(0,V),oe=$.substr(V+1,X-(V+1)).split(","),le=1;switch(re){case"rgba":if(oe.length!==4)return null;le=w(oe.pop());case"rgb":return oe.length!==3?null:[p(oe[0]),p(oe[1]),p(oe[2]),le];case"hsla":if(oe.length!==4)return null;le=w(oe.pop());case"hsl":if(oe.length!==3)return null;var ge=(parseFloat(oe[0])%360+360)%360/360,_e=w(oe[1]),Te=w(oe[2]),Fe=Te<=.5?Te*(_e+1):Te+_e-Te*_e,He=2*Te-Fe;return[h(255*T(He,Fe,ge+1/3)),h(255*T(He,Fe,ge)),h(255*T(He,Fe,ge-1/3)),le];default:return null}}return null}}catch{}return Pr}();class Vr{constructor(h,p,w,T=1){this.r=h,this.g=p,this.b=w,this.a=T}static parse(h){if(!h)return;if(h instanceof Vr)return h;if(typeof h!="string")return;const p=Sn.parseCSSColor(h);return p?new Vr(p[0]/255,p[1]/255,p[2]/255,p[3]):void 0}toString(){const[h,p,w,T]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*h)},${Math.round(255*p)},${Math.round(255*w)},${T})`}toNonPremultipliedRenderColor(h){const{r:p,g:w,b:T,a:I}=this;return new Va(h,p,w,T,I)}toPremultipliedRenderColor(h){const{r:p,g:w,b:T,a:I}=this;return new ri(h,p*I,w*I,T*I,I)}clone(){return new Vr(this.r,this.g,this.b,this.a)}}class na{constructor(h,p,w,T,I,L=!1){if(this.premultiplied=!1,this.premultiplied=L,h){const $=h.image.height,V=$*$;this.premultiplied?(p=I===0?0:p/I*($-1),w=I===0?0:w/I*($-1),T=I===0?0:T/I*($-1)):(p*=$-1,w*=$-1,T*=$-1),p=Math.max(0,Math.min($-1,p)),w=Math.max(0,Math.min($-1,w)),T=Math.max(0,Math.min($-1,T));const X=Math.floor(p),re=Math.floor(w),oe=Math.floor(T),le=Math.ceil(p),ge=Math.ceil(w),_e=Math.ceil(T),Te=p-X,Fe=w-re,He=T-oe,ot=h.image.data,st=4*(X+re*V+oe*$),mt=4*(X+re*V+_e*$),bt=4*(X+ge*V+oe*$),wt=4*(X+ge*V+_e*$),Gt=4*(le+re*V+oe*$),Ot=4*(le+re*V+_e*$),Ht=4*(le+ge*V+oe*$),Bt=4*(le+ge*V+_e*$);this.r=An(An(An(ot[st],ot[mt],He),An(ot[bt],ot[wt],He),Fe),An(An(ot[Gt],ot[Ot],He),An(ot[Ht],ot[Bt],He),Fe),Te)/255*(this.premultiplied?I:1),this.g=An(An(An(ot[st+1],ot[mt+1],He),An(ot[bt+1],ot[wt+1],He),Fe),An(An(ot[Gt+1],ot[Ot+1],He),An(ot[Ht+1],ot[Bt+1],He),Fe),Te)/255*(this.premultiplied?I:1),this.b=An(An(An(ot[st+2],ot[mt+2],He),An(ot[bt+2],ot[wt+2],He),Fe),An(An(ot[Gt+2],ot[Ot+2],He),An(ot[Ht+2],ot[Bt+2],He),Fe),Te)/255*(this.premultiplied?I:1),this.a=I}else this.r=p,this.g=w,this.b=T,this.a=I}toArray(){const{r:h,g:p,b:w,a:T}=this;return[255*h,255*p,255*w,T]}toHslaArray(){let{r:h,g:p,b:w,a:T}=this;if(this.premultiplied){if(T===0)return[0,0,0,0];const _e=1/T;h*=_e,p*=_e,w*=_e}const I=Math.min(Math.max(h,0),1),L=Math.min(Math.max(p,0),1),$=Math.min(Math.max(w,0),1),V=Math.min(I,L,$),X=Math.max(I,L,$),re=X-V,oe=.5*(V+X);if(re===0)return[0,0,100*oe,T];const le=oe>.5?re/(2-X-V):re/(X+V);let ge;switch(X){case I:ge=60*((L-$)/re+(L<$?6:0));break;case L:ge=60*(($-I)/re+2);break;default:ge=60*((I-L)/re+4)}return[ge,100*le,100*oe,T]}toArray01(){const{r:h,g:p,b:w,a:T}=this;return[h,p,w,T]}toArray01Scaled(h){const{r:p,g:w,b:T}=this;return[p*h,w*h,T*h]}toArray01Linear(){const{r:h,g:p,b:w,a:T}=this;return[Math.pow(h,2.2),Math.pow(p,2.2),Math.pow(w,2.2),T]}}class Va extends na{constructor(h,p,w,T,I){super(h,p,w,T,I,!1)}}class ri extends na{constructor(h,p,w,T,I){super(h,p,w,T,I,!0)}}function An(v,h,p){return v*(1-p)+h*p}function fd(v,h,p){return v.map((w,T)=>An(w,h[T],p))}Vr.black=new Vr(0,0,0,1),Vr.white=new Vr(1,1,1,1),Vr.transparent=new Vr(0,0,0,0),Vr.red=new Vr(1,0,0,1),Vr.blue=new Vr(0,0,1,1);var Gh=Object.freeze({__proto__:null,array:fd,color:function(v,h,p){return new Vr(An(v.r,h.r,p),An(v.g,h.g,p),An(v.b,h.b,p),An(v.a,h.a,p))},number:An});class Cu extends Error{constructor(h,p){super(p),this.message=p,this.key=h}}class Ox{constructor(h,p=[]){this.parent=h,this.bindings={};for(const[w,T]of p)this.bindings[w]=T}concat(h){return new Ox(this,h)}get(h){if(this.bindings[h])return this.bindings[h];if(this.parent)return this.parent.get(h);throw new Error(`${h} not found in scope.`)}has(h){return!!this.bindings[h]||!!this.parent&&this.parent.has(h)}}const ip={kind:"null"},yn={kind:"number"},wi={kind:"string"},Bi={kind:"boolean"},bh={kind:"color"},qp={kind:"object"},Zi={kind:"value"},Vp={kind:"collator"},J0={kind:"formatted"},eb={kind:"resolvedImage"};function Tu(v,h){return{kind:"array",itemType:v,N:h}}function Il(v){if(v.kind==="array"){const h=Il(v.itemType);return typeof v.N=="number"?`array<${h}, ${v.N}>`:v.itemType.kind==="value"?"array":`array<${h}>`}return v.kind}const xM=[ip,yn,wi,Bi,bh,J0,qp,Tu(Zi),eb];function ey(v,h){if(h.kind==="error")return null;if(v.kind==="array"){if(h.kind==="array"&&(h.N===0&&h.itemType.kind==="value"||!ey(v.itemType,h.itemType))&&(typeof v.N!="number"||v.N===h.N))return null}else{if(v.kind===h.kind)return null;if(v.kind==="value"){for(const p of xM)if(!ey(p,h))return null}}return`Expected ${Il(v)} but found ${Il(h)} instead.`}function tb(v,h){return h.some(p=>p.kind===v.kind)}function Hp(v,h){return h.some(p=>p==="null"?v===null:p==="array"?Array.isArray(v):p==="object"?v&&!Array.isArray(v)&&typeof v=="object":p===typeof v)}function Gp(v,h){return v.kind==="array"&&h.kind==="array"?v.N===h.N&&Gp(v.itemType,h.itemType):v.kind===h.kind}class vw{constructor(h,p,w){this.sensitivity=h?p?"variant":"case":p?"accent":"base",this.locale=w,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(h,p){return this.collator.compare(h,p)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class sb{constructor(h,p,w,T,I){this.text=h.normalize?h.normalize():h,this.image=p,this.scale=w,this.fontStack=T,this.textColor=I}}class Td{constructor(h){this.sections=h}static fromString(h){return new Td([new sb(h,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(h=>h.text.length!==0||!!h.image&&h.image.hasPrimary())}static factory(h){return h instanceof Td?h:Td.fromString(h)}toString(){return this.sections.length===0?"":this.sections.map(h=>h.text).join("")}serialize(){const h=["format"];for(const p of this.sections){if(p.image){const T=p.image.getPrimary().id.toString();h.push(["image",T]);continue}h.push(p.text);const w={};p.fontStack&&(w["text-font"]=["literal",p.fontStack.split(",")]),p.scale&&(w["font-scale"]=p.scale),p.textColor&&(w["text-color"]=["rgba"].concat(p.textColor.toNonPremultipliedRenderColor(null).toArray())),h.push(w)}return h}}class Rm{constructor(h,p={}){this.id=It.from(h),this.params=p.params,this.sx=p.sx||1,this.sy=p.sy||1}toString(){return JSON.stringify(this)}static parse(h){let p,w,T,I;try{({id:p,params:w,sx:T,sy:I}=JSON.parse(h)||{})}catch{return null}return p?new Rm(p,{params:w,sx:T,sy:I}):null}scaleSelf(h,p=h){return this.sx*=h,this.sy*=p,this}}class Ed{constructor(h,p,w,T,I=!1){this.primaryId=It.from(h),this.primaryOptions=p,w&&(this.secondaryId=It.from(w)),this.secondaryOptions=T,this.available=I}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Rm(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Rm(this.secondaryId,this.secondaryOptions):null}static from(h){return typeof h=="string"?Ed.build({name:h}):h}static build(h,p,w,T){return!h||typeof h=="object"&&!("name"in h)?null:new Ed(h,w,p,T)}}function gf(v,h,p,w){return typeof v=="number"&&v>=0&&v<=255&&typeof h=="number"&&h>=0&&h<=255&&typeof p=="number"&&p>=0&&p<=255?w===void 0||typeof w=="number"&&w>=0&&w<=1?null:`Invalid rgba value [${[v,h,p,w].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof w=="number"?[v,h,p,w]:[v,h,p]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function op(v){if(v===null||typeof v=="string"||typeof v=="boolean"||typeof v=="number"||v instanceof Vr||v instanceof vw||v instanceof Td||v instanceof Ed)return!0;if(Array.isArray(v)){for(const h of v)if(!op(h))return!1;return!0}if(typeof v=="object"){for(const h in v)if(!op(v[h]))return!1;return!0}return!1}function kl(v){if(v===null)return ip;if(typeof v=="string")return wi;if(typeof v=="boolean")return Bi;if(typeof v=="number")return yn;if(v instanceof Vr)return bh;if(v instanceof vw)return Vp;if(v instanceof Td)return J0;if(v instanceof Ed)return eb;if(Array.isArray(v)){const h=v.length;let p;for(const w of v){const T=kl(w);if(p){if(p===T)continue;p=Zi;break}p=T}return Tu(p||Zi,h)}return qp}function Hn(v){const h=typeof v;return v===null?"":h==="string"||h==="number"||h==="boolean"?String(v):v instanceof Td||v instanceof Ed||v instanceof Vr?v.toString():JSON.stringify(v)}class Jr{constructor(h,p){this.type=h,this.value=p}static parse(h,p){if(h.length!==2)return p.error(`'literal' expression requires exactly one argument, but found ${h.length-1} instead.`);if(!op(h[1]))return p.error("invalid value");const w=h[1];let T=kl(w);const I=p.expectedType;return T.kind!=="array"||T.N!==0||!I||I.kind!=="array"||typeof I.N=="number"&&I.N!==0||(T=I),new Jr(T,w)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Vr?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Td?this.value.serialize():this.value}}class hl{constructor(h){this.name="ExpressionEvaluationError",this.message=h}toJSON(){return this.message}}const Xn={string:wi,number:yn,boolean:Bi,object:qp};class Om{constructor(h,p){this.type=h,this.args=p}static parse(h,p){if(h.length<2)return p.error("Expected at least one argument.");let w,T=1;const I=h[0];if(I==="array"){let $,V;if(h.length>2){const X=h[1];if(typeof X!="string"||!(X in Xn)||X==="object")return p.error('The item type argument of "array" must be one of string, number, boolean',1);$=Xn[X],T++}else $=Zi;if(h.length>3){if(h[2]!==null&&(typeof h[2]!="number"||h[2]<0||h[2]!==Math.floor(h[2])))return p.error('The length argument to "array" must be a positive integer literal',2);V=h[2],T++}w=Tu($,V)}else w=Xn[I];const L=[];for(;Th.outputDefined())}serialize(){const h=this.type,p=[h.kind];if(h.kind==="array"){const w=h.itemType;if(w.kind==="string"||w.kind==="number"||w.kind==="boolean"){p.push(w.kind);const T=h.N;(typeof T=="number"||this.args.length>1)&&p.push(T)}}return p.concat(this.args.map(w=>w.serialize()))}}class Wh{constructor(h){this.type=J0,this.sections=h}static parse(h,p){if(h.length<2)return p.error("Expected at least one argument.");const w=h[1];if(!Array.isArray(w)&&typeof w=="object")return p.error("First argument must be an image or text section.");const T=[];let I=!1;for(let L=1;L<=h.length-1;++L){const $=h[L];if(I&&typeof $=="object"&&!Array.isArray($)){I=!1;let V=null;if($["font-scale"]&&(V=p.parseObjectValue($["font-scale"],L,"font-scale",yn),!V))return null;let X=null;if($["text-font"]&&(X=p.parseObjectValue($["text-font"],L,"text-font",Tu(wi)),!X))return null;let re=null;if($["text-color"]&&(re=p.parseObjectValue($["text-color"],L,"text-color",bh),!re))return null;const oe=T[T.length-1];oe.scale=V,oe.font=X,oe.textColor=re}else{const V=p.parse(h[L],L,Zi);if(!V)return null;const X=V.type.kind;if(X!=="string"&&X!=="value"&&X!=="null"&&X!=="resolvedImage")return p.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");I=!0,T.push({content:V,scale:null,font:null,textColor:null})}}return new Wh(T)}evaluate(h){return new Td(this.sections.map(p=>{const w=p.content.evaluate(h);return Gp(kl(w),eb)?new sb("",w,null,null,null):new sb(Hn(w),null,p.scale?p.scale.evaluate(h):null,p.font?p.font.evaluate(h).join(","):null,p.textColor?p.textColor.evaluate(h):null)}))}eachChild(h){for(const p of this.sections)h(p.content),p.scale&&h(p.scale),p.font&&h(p.font),p.textColor&&h(p.textColor)}outputDefined(){return!1}serialize(){const h=["format"];for(const p of this.sections){h.push(p.content.serialize());const w={};p.scale&&(w["font-scale"]=p.scale.serialize()),p.font&&(w["text-font"]=p.font.serialize()),p.textColor&&(w["text-color"]=p.textColor.serialize()),h.push(w)}return h}}class Cn{constructor(h,p,w,T){this._imageWarnHistory={},this.type=eb,this.namePrimary=h,this.nameSecondary=p,w&&(this.paramsPrimary=w.params,this.iconsetIdPrimary=w.iconset?w.iconset.id:void 0),T&&(this.paramsSecondary=T.params,this.iconsetIdSecondary=T.iconset?T.iconset.id:void 0)}static parse(h,p){if(h.length<2)return p.error("Expected two or more arguments.");let w=1;const T=[];function I(){if(wIt.isEqual(L,I)),T.available){const L=T.getSecondary()?T.getSecondary().id:null;L&&(T.available=h.availableImages.some($=>It.isEqual($,L)))}}return T}eachChild(h){if(h(this.namePrimary),this.paramsPrimary)for(const p in this.paramsPrimary)this.paramsPrimary[p]&&h(this.paramsPrimary[p]);if(this.nameSecondary&&(h(this.nameSecondary),this.paramsSecondary))for(const p in this.paramsSecondary)this.paramsSecondary[p]&&h(this.paramsSecondary[p])}outputDefined(){return!1}serializeOptions(h,p){const w={};if(p&&(w.iconset={id:p}),h){w.params={};for(const T in h)h[T]&&(w.params[T]=h[T].serialize())}return Object.keys(w).length>0?w:void 0}serialize(){const h=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const p=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);p&&h.push(p)}if(this.nameSecondary&&(h.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const p=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);p&&h.push(p)}return h}}function ty(v){return bv(v)?"string":rb(v)?"number":Dg(v)?"boolean":Array.isArray(v)?"array":v===null?"null":bw(v)?"object":typeof v}function bw(v){return v!=null&&!Array.isArray(v)&&typeof v!="function"&&!(v instanceof String||v instanceof Number||v instanceof Boolean)&&typeof v=="object"}function bv(v){return typeof v=="string"||v instanceof String}function rb(v){return typeof v=="number"||v instanceof Number}function Dg(v){return typeof v=="boolean"||v instanceof Boolean}const lp={"to-boolean":Bi,"to-color":bh,"to-number":yn,"to-string":wi};class Kh{constructor(h,p){this.type=h,this.args=p}static parse(h,p){if(h.length<2)return p.error("Expected at least one argument.");const w=h[0],T=[];let I=ip;if(w==="to-array"){if(!Array.isArray(h[1]))return null;const L=h[1].length;if(p.expectedType){if(p.expectedType.kind!=="array")return p.error(`Expected ${p.expectedType.kind} but found array.`);I=Tu(p.expectedType.itemType,L)}else{if(!(L>0&&op(h[1][0])))return null;I=Tu(kl(h[1][0]),L)}for(let $=0;$4?`Invalid rbga value ${JSON.stringify(p)}: expected an array containing either three or four numeric values.`:gf(p[0],p[1],p[2],p[3]),!w))return new Vr(p[0]/255,p[1]/255,p[2]/255,p[3])}throw new hl(w||`Could not parse color from value '${typeof p=="string"?p:String(JSON.stringify(p))}'`)}if(this.type.kind==="number"){let p=null;for(const w of this.args){if(p=w.evaluate(h),p===null)return 0;const T=Number(p);if(!isNaN(T))return T}throw new hl(`Could not convert ${JSON.stringify(p)} to number.`)}return this.type.kind==="formatted"?Td.fromString(Hn(this.args[0].evaluate(h))):this.type.kind==="resolvedImage"?Ed.build(Hn(this.args[0].evaluate(h))):this.type.kind==="array"?this.args.map(p=>p.evaluate(h)):Hn(this.args[0].evaluate(h))}eachChild(h){this.args.forEach(h)}outputDefined(){return this.args.every(h=>h.outputDefined())}serialize(){if(this.type.kind==="formatted")return new Wh([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new Cn(this.args[0]).serialize();const h=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(p=>{h.push(p.serialize())}),h}}const cp=["Unknown","Point","LineString","Polygon"];class Fm{constructor(h,p,w){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=h,this.options=p,this.iconImageUseTheme=w}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?cp[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(h){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const h=this.featureDistanceData.center,p=this.featureDistanceData.scale,{x:w,y:T}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(w*p-h[0])+this.featureDistanceData.bearing[1]*(T*p-h[1])}return 0}parseColor(h){let p=this._parseColorCache[h];return p||(p=this._parseColorCache[h]=Vr.parse(h)),p}getConfig(h){return this.options?this.options.get(h):null}}class wc{constructor(h,p,w,T,I){this.name=h,this.type=p,this._evaluate=w,this.args=T,this._overloadIndex=I}evaluate(h){if(!this._evaluate){const p=wc.definitions[this.name];this._evaluate=Array.isArray(p)?p[2]:p.overloads[this._overloadIndex][1]}return this._evaluate(h,this.args)}eachChild(h){this.args.forEach(h)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(h=>h.serialize()))}static parse(h,p){const w=h[0],T=wc.definitions[w];if(!T)return p.error(`Unknown expression "${w}". If you wanted a literal array, use ["literal", [...]].`,0);const I=Array.isArray(T)?T[0]:T.type,L=Array.isArray(T)?[[T[1],T[2]]]:T.overloads,$=[];let V=null,X=-1;for(const[re,oe]of L){if(Array.isArray(re)&&re.length!==h.length-1)continue;$.push(re),X++,V=new Iw(p.registry,p.path,null,p.scope,void 0,p._scope,p.options,p.iconImageUseTheme);const le=[];let ge=!1;for(let _e=1;_ele)).map(yf).join(" | "),oe=[];for(let le=1;lep;){if(w-p>600){const V=w-p+1,X=h-p+1,re=Math.log(V),oe=.5*Math.exp(2*re/3),le=.5*Math.sqrt(re*oe*(V-oe)/V)*(X-V/2<0?-1:1);H2(v,h,Math.max(p,Math.floor(h-X*oe/V+le)),Math.min(w,Math.floor(h+(V-X)*oe/V+le)),T)}const I=v[h];let L=p,$=w;for(Vl(v,p,h),T(v[w],I)>0&&Vl(v,p,w);L<$;){for(Vl(v,L,$),L++,$--;T(v[L],I)<0;)L++;for(;T(v[$],I)>0;)$--}T(v[p],I)===0?Vl(v,p,$):($++,Vl(v,$,w)),$<=h&&(p=$+1),h<=$&&(w=$-1)}}function Vl(v,h,p){const w=v[h];v[h]=v[p],v[p]=w}function _v(v,h){return vh?1:0}function G2(v){let h=0;for(let p,w,T=0,I=v.length,L=I-1;T=h[2]||v[1]<=h[1]||v[3]>=h[3])}function v4(v,h,p){const w=v[0]-h[0],T=v[1]-h[1],I=v[0]-p[0],L=v[1]-p[1];return w*L-I*T===0&&w*I<=0&&T*L<=0}function Rg(v,h,p){return h[1]>v[1]!=p[1]>v[1]&&v[0]<(p[0]-h[0])*(v[1]-h[1])/(p[1]-h[1])+h[0]}function zl(v,h,p=!1){let w=!1;for(let T=0,I=h.length;T0&&$<0||L<0&&$>0}function Kc(v,h,p,w){return(T=[w[0]-p[0],w[1]-p[1]])[0]*(I=[h[0]-v[0],h[1]-v[1]])[1]-T[1]*I[0]!==0&&!(!Ad(v,h,p,w)||!Ad(p,w,v,h));var T,I}function nb(v){const h=new gs(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),p=new gs(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const w of v[0])h.x>w.x&&(h.x=w.x),h.y>w.y&&(h.y=w.y),p.xp[2]){const T=.5*w;let I=v[0]-p[0]>T?-w:p[0]-v[0]>T?w:0;I===0&&(I=v[0]-p[2]>T?-w:p[2]-v[0]>T?w:0),v[0]+=I}vf(h,v)}function jv(v,h,p,w){const T=Math.pow(2,w.z)*dp,I=[w.x*dp,w.y*dp],L=[];if(!v)return L;for(const $ of v)for(const V of $){const X=[V.x+I[0],V.y+I[1]];Ic(X,h,p,T),L.push(X)}return L}function Nw(v,h,p,w){const T=Math.pow(2,w.z)*dp,I=[w.x*dp,w.y*dp],L=[];if(!v)return L;for(const V of v){const X=[];for(const re of V){const oe=[re.x+I[0],re.y+I[1]];vf(h,oe),X.push(oe)}L.push(X)}if(h[2]-h[0]<=T/2){($=h)[0]=$[1]=1/0,$[2]=$[3]=-1/0;for(const V of L)for(const X of V)Ic(X,h,p,T)}var $;return L}class Fx{constructor(h,p){this.type=Bi,this.geojson=h,this.geometries=p}static parse(h,p){if(h.length!==2)return p.error(`'within' expression requires exactly one argument, but found ${h.length-1} instead.`);if(op(h[1])){const w=h[1];if(w.type==="FeatureCollection")for(let T=0;Tp)return kw(I,L,(p-(w-$))/$)}return h[h.length-1]}pointToSegmentDistance(h,p,w){let[T,I]=p,L=zm(w[0]-T)*this.kx,$=(w[1]-I)*this.ky;if(L!==0||$!==0){const V=(zm(h[0]-T)*this.kx*L+(h[1]-I)*this.ky*$)/(L*L+$*$);V>1?(T=w[0],I=w[1]):V>0&&(T+=L/this.kx*V,I+=$/this.ky*V)}return L=zm(h[0]-T)*this.kx,$=(h[1]-I)*this.ky,Math.sqrt(L*L+$*$)}pointOnLine(h,p){let w=1/0,T=h[0][0],I=h[0][1],L=0,$=0;for(let V=0;V1?(X=h[V+1][0],re=h[V+1][1]):ge>0&&(X+=oe/this.kx*ge,re+=le/this.ky*ge)),oe=zm(p[0]-X)*this.kx,le=(p[1]-re)*this.ky;const _e=oe*oe+le*le;_eI.index||T.index===I.index&&T.t>I.t){const X=T;T=I,I=X}const L=[T.point],$=T.index+1,V=I.index;!Z2(w[$],L[0])&&$<=V&&L.push(w[$]);for(let X=$+1;X<=V;X++)L.push(w[X]);return Z2(w[V],I.point)||L.push(I.point),L}lineSliceAlong(h,p,w){let T=0;const I=[];for(let L=0;Lh&&I.length===0&&I.push(kw($,V,(h-(T-X))/X)),T>=p)return I.push(kw($,V,(p-(T-X))/X)),I;T>h&&I.push(V)}return I}bufferPoint(h,p){const w=p/this.ky,T=p/this.kx;return[h[0]-T,h[1]-w,h[0]+T,h[1]+w]}bufferBBox(h,p){const w=p/this.ky,T=p/this.kx;return[h[0]-T,h[1]-w,h[2]+T,h[3]+w]}insideBBox(h,p){return zm(h[0]-p[0])>=0&&zm(h[0]-p[2])<=0&&h[1]>=p[1]&&h[1]<=p[3]}}function Z2(v,h){return v[0]===h[0]&&v[1]===h[1]}function kw(v,h,p){const w=zm(h[0]-v[0]);return[v[0]+w*p,v[1]+(h[1]-v[1])*p]}function zm(v){for(;v<-180;)v+=360;for(;v>180;)v-=360;return v}class Og{constructor(h=[],p=(w,T)=>wT?1:0){if(this.data=h,this.length=this.data.length,this.compare=p,this.length>0)for(let w=(this.length>>1)-1;w>=0;w--)this._down(w)}push(h){this.data.push(h),this._up(this.length++)}pop(){if(this.length===0)return;const h=this.data[0],p=this.data.pop();return--this.length>0&&(this.data[0]=p,this._down(0)),h}peek(){return this.data[0]}_up(h){const{data:p,compare:w}=this,T=p[h];for(;h>0;){const I=h-1>>1,L=p[I];if(w(T,L)>=0)break;p[h]=L,h=I}p[h]=T}_down(h){const{data:p,compare:w}=this,T=this.length>>1,I=p[h];for(;h=0)break;p[h]=p[L],h=L}p[h]=I}}var Lr=8192;function Sw(v,h){return h.dist-v.dist}function Cw(v){const h=[1/0,1/0,-1/0,-1/0];if(h.length!==v.length)return!1;for(let p=0;p=v[0]&&v[1]v[1])return[null,null];const p=ry(v);if(h){if(p===2)return[v,null];const w=Math.floor(p/2);return[[v[0],v[0]+w],[v[0]+w,v[1]]]}{if(p===1)return[v,null];const w=Math.floor(p/2)-1;return[[v[0],v[0]+w],[v[0]+w+1,v[1]]]}}function Fg(v,h){const p=[1/0,1/0,-1/0,-1/0];if(!bf(h,v.length))return p;for(let w=h[0];w<=h[1];++w)vf(p,v[w]);return p}function ob(v){const h=[1/0,1/0,-1/0,-1/0];for(let p=0;ph[2]&&(w=v[0]-h[2]),v[1]>h[3]&&(T=v[1]-h[3]),v[3]=w)return w;if(sy(T,I)){if(Tw(v,h))return 0}else if(Tw(h,v))return 0;let L=w;for(const $ of v)for(let V=0,X=$.length,re=X-1;V=I)continue;const re=X.range1;if(ry(re)<=$){if(!bf(re,v.length))return NaN;if(h){const oe=nl(v,re,p,w);if((I=Math.min(I,oe))===0)return I}else for(let oe=re[0];oe<=re[1];++oe){const le=gM(v[oe],p,w);if((I=Math.min(I,le))===0)return I}}else{const oe=Sv(re,h);if(oe[0]!==null){const le=Cv(Fg(v,oe[0]),V,w);le=L)continue;const oe=re.range1,le=re.range2;if(ry(oe)<=V&&ry(le)<=X){if(!bf(oe,v.length)||!bf(le,p.length))return NaN;if(h&&w?L=Math.min(L,yD(v,oe,p,le,T)):h||w?h&&!w?L=Math.min(L,j4(p,le,v,oe,T)):!h&&w&&(L=Math.min(L,j4(v,oe,p,le,T))):L=Math.min(L,k4(v,oe,p,le,T)),L===0)return L}else{const ge=Sv(oe,h),_e=Sv(le,w);X2($,L,T,v,p,ge[0],_e[0]),X2($,L,T,v,p,ge[0],_e[1]),X2($,L,T,v,p,ge[1],_e[0]),X2($,L,T,v,p,ge[1],_e[1])}}return L}function Ew(v,h,p,w,T=1/0){let I=T;const L=Fg(v,[0,v.length-1]);for(const $ of p)if(!(I!==1/0&&Cv(L,Fg($,[0,$.length-1]),w)>=I)&&(I=Math.min(I,hp(v,h,$,!0,w,I)),I===0))return I;return I}function Tv(v,h,p,w,T=1/0){let I=T;const L=Fg(v,[0,v.length-1]);for(const $ of p){if(I!==1/0&&Cv(L,ob($),w)>=I)continue;const V=bD(v,h,$,w,I);if(isNaN(V))return V;if((I=Math.min(I,V))===0)return I}return I}function Q2(v){return v==="Point"||v==="MultiPoint"||v==="LineString"||v==="MultiLineString"||v==="Polygon"||v==="MultiPolygon"}class ny{constructor(h,p){this.type=yn,this.geojson=h,this.geometries=p}static parse(h,p){if(h.length!==2)return p.error(`'distance' expression requires either one argument, but found ' ${h.length-1} instead.`);if(op(h[1])){const w=h[1];if(w.type==="FeatureCollection"){for(let T=0;T{h&&!ay(p)&&(h=!1)}),h}function iy(v){if(v instanceof wc&&v.name==="feature-state")return!1;let h=!0;return v.eachChild(p=>{h&&!iy(p)&&(h=!1)}),h}function Yh(v,h){if(v instanceof wc&&h.indexOf(v.name)>=0)return!1;let p=!0;return v.eachChild(w=>{p&&!Yh(w,h)&&(p=!1)}),p}function J2(v,h,p){return[v,h,p].filter(Boolean).join("")}function Aw(v,h){switch(v){case"string":return Hn(h);case"number":return+h;case"boolean":return!!h;case"color":return Vr.parse(h);case"formatted":return Td.fromString(Hn(h));case"resolvedImage":return Ed.build(Hn(h))}return h}function yM(v,h,p,w){return w!==void 0&&(v=w*Math.round(v/w)),h!==void 0&&vp&&(v=p),v}class Ev{constructor(h,p,w,T=!1){this.type=h,this.key=p,this.scope=w,this.featureConstant=T}static parse(h,p){let w=p.expectedType;if(w==null&&(w=Zi),h.length<2||h.length>3)return p.error("Invalid number of arguments for 'config' expression.");const T=p.parse(h[1],1);if(!(T instanceof Jr))return p.error("Key name of 'config' expression must be a string literal.");let I,L=!0;const $=Hn(T.value);if(h.length>=3){const V=p.parse(h[2],2);if(!(V instanceof Jr))return p.error("Scope of 'config' expression must be a string literal.");I=Hn(V.value)}if(p.options){const V=J2($,I,p._scope),X=p.options.get(V);X&&(L=ay(X.value||X.default))}return new Ev(w,$,I,L)}evaluate(h){const p=J2(this.key,this.scope,h.scope),w=h.getConfig(p);if(!w)return null;const{type:T,value:I,values:L,minValue:$,maxValue:V,stepValue:X}=w,re=w.default.evaluate(h);let oe=re;if(I){const le=h.scope;h.scope=(le||"").split("").slice(1).join(""),oe=I.evaluate(h),h.scope=le}return T&&(oe=Aw(T,oe)),oe===void 0||$===void 0&&V===void 0&&X===void 0||(typeof oe=="number"?oe=yM(oe,$,V,X):Array.isArray(oe)&&(oe=oe.map(le=>typeof le=="number"?yM(le,$,V,X):le))),I!==void 0&&oe!==void 0&&L&&!L.includes(oe)&&(oe=re,T&&(oe=Aw(T,oe))),(T&&T!==this.type||oe!==void 0&&!Gp(kl(oe),this.type))&&(oe=Aw(this.type.kind,oe)),oe}eachChild(){}outputDefined(){return!1}serialize(){const h=["config",this.key];return this.scope&&h.concat(this.scope),h}}class Mw{constructor(h,p){this.type=p.type,this.name=h,this.boundExpression=p}static parse(h,p){if(h.length!==2||typeof h[1]!="string")return p.error("'var' expression requires exactly one string literal argument.");const w=h[1];return p.scope.has(w)?new Mw(w,p.scope.get(w)):p.error(`Unknown variable "${w}". Make sure "${w}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(h){return this.boundExpression.evaluate(h)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class Iw{constructor(h,p=[],w,T=new Ox,I=[],L,$,V){this.registry=h,this.path=p,this.key=p.map(X=>typeof X=="string"?`['${X}']`:`[${X}]`).join(""),this.scope=T,this.errors=I,this.expectedType=w,this._scope=L,this.options=$,this.iconImageUseTheme=V}parse(h,p,w,T,I={}){return p||w?this.concat(p,null,w,T)._parse(h,I):this._parse(h,I)}parseObjectValue(h,p,w,T,I,L={}){return this.concat(p,w,T,I)._parse(h,L)}_parse(h,p){function w(T,I,L){return L==="assert"?new Om(I,[T]):L==="coerce"?new Kh(I,[T]):T}if(h!==null&&typeof h!="string"&&typeof h!="boolean"&&typeof h!="number"||(h=["literal",h]),Array.isArray(h)){if(h.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const T=typeof h[0]=="string"?this.registry[h[0]]:void 0;if(T){let I=T.parse(h,this);if(!I)return null;if(this.expectedType){const L=this.expectedType,$=I.type;if(L.kind!=="string"&&L.kind!=="number"&&L.kind!=="boolean"&&L.kind!=="object"&&L.kind!=="array"||$.kind!=="value")if(L.kind!=="color"&&L.kind!=="formatted"&&L.kind!=="resolvedImage"||$.kind!=="value"&&$.kind!=="string"){if(this.checkSubtype(L,$))return null}else I=w(I,L,p.typeAnnotation||"coerce");else I=w(I,L,p.typeAnnotation||"assert")}if(!(I instanceof Jr)&&I.type.kind!=="resolvedImage"&&eN(I)){const L=new Fm(this._scope,this.options,this.iconImageUseTheme);try{I=new Jr(I.type,I.evaluate(L))}catch($){return this.error($.message),null}}return I}return Kh.parse(["to-array",h],this)}return this.error(h===void 0?"'undefined' value invalid. Use null instead.":typeof h=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof h} instead.`)}concat(h,p,w,T){let I=typeof h=="number"?this.path.concat(h):this.path;I=typeof p=="string"?I.concat(p):I;const L=T?this.scope.concat(T):this.scope;return new Iw(this.registry,I,w||null,L,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(h,...p){const w=`${this.key}${p.map(T=>`[${T}]`).join("")}`;this.errors.push(new Cu(w,h))}checkSubtype(h,p){const w=ey(h,p);return w&&this.error(w),w}}function eN(v){if(v instanceof Mw)return eN(v.boundExpression);if(v instanceof wc&&v.name==="error"||v instanceof _w||v instanceof Fx||v instanceof ny||v instanceof Ev)return!1;const h=v instanceof Kh||v instanceof Om;let p=!0;return v.eachChild(w=>{p=h?p&&eN(w):p&&w instanceof Jr}),!!p&&ay(v)&&Yh(v,["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 Pw(v,h){const p=v.length-1;let w,T,I=0,L=p,$=0;for(;I<=L;)if($=Math.floor((I+L)/2),w=v[$],T=v[$+1],w<=h){if($===p||hh))throw new hl("Input is not a number.");L=$-1}return 0}class Lw{constructor(h,p,w){this.type=h,this.input=p,this.labels=[],this.outputs=[];for(const[T,I]of w)this.labels.push(T),this.outputs.push(I)}static parse(h,p){if(h.length-1<4)return p.error(`Expected at least 4 arguments, but found only ${h.length-1}.`);if((h.length-1)%2!=0)return p.error("Expected an even number of arguments.");const w=p.parse(h[1],1,yn);if(!w)return null;const T=[];let I=null;p.expectedType&&p.expectedType.kind!=="value"&&(I=p.expectedType);for(let L=1;L=$)return p.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',X);const oe=p.parse(V,re,I);if(!oe)return null;I=I||oe.type,T.push([$,oe])}return new Lw(I,w,T)}evaluate(h){const p=this.labels,w=this.outputs;if(p.length===1)return w[0].evaluate(h);const T=this.input.evaluate(h);if(T<=p[0])return w[0].evaluate(h);const I=p.length;return T>=p[I-1]?w[I-1].evaluate(h):w[Pw(p,T)].evaluate(h)}eachChild(h){h(this.input);for(const p of this.outputs)h(p)}outputDefined(){return this.outputs.every(h=>h.outputDefined())}serialize(){const h=["step",this.input.serialize()];for(let p=0;p0&&h.push(this.labels[p]),h.push(this.outputs[p].serialize());return h}}const Zh=.95047,wh=1.08883,S4=4/29,Av=6/29,C4=3*Av*Av,vM=Av*Av*Av,bM=Math.PI/180,T4=180/Math.PI;function tN(v){return v>vM?Math.pow(v,1/3):v/C4+S4}function Dw(v){return v>Av?v*v*v:C4*(v-S4)}function lb(v){return 255*(v<=.0031308?12.92*v:1.055*Math.pow(v,1/2.4)-.055)}function Mv(v){return(v/=255)<=.04045?v/12.92:Math.pow((v+.055)/1.055,2.4)}function Rw(v){const h=Mv(v.r),p=Mv(v.g),w=Mv(v.b),T=tN((.4124564*h+.3575761*p+.1804375*w)/Zh),I=tN((.2126729*h+.7151522*p+.072175*w)/1);return{l:116*I-16,a:500*(T-I),b:200*(I-tN((.0193339*h+.119192*p+.9503041*w)/wh)),alpha:v.a}}function sN(v){let h=(v.l+16)/116,p=isNaN(v.a)?h:h+v.a/500,w=isNaN(v.b)?h:h-v.b/200;return h=1*Dw(h),p=Zh*Dw(p),w=wh*Dw(w),new Vr(lb(3.2404542*p-1.5371385*h-.4985314*w),lb(-.969266*p+1.8760108*h+.041556*w),lb(.0556434*p-.2040259*h+1.0572252*w),v.alpha)}function _M(v,h,p){const w=h-v;return v+p*(w>180||w<-180?w-360*Math.round(w/360):w)}const Iv={forward:Rw,reverse:sN,interpolate:function(v,h,p){return{l:An(v.l,h.l,p),a:An(v.a,h.a,p),b:An(v.b,h.b,p),alpha:An(v.alpha,h.alpha,p)}}},zg={forward:function(v){const{l:h,a:p,b:w}=Rw(v),T=Math.atan2(w,p)*T4;return{h:T<0?T+360:T,c:Math.sqrt(p*p+w*w),l:h,alpha:v.a}},reverse:function(v){const h=v.h*bM,p=v.c;return sN({l:v.l,a:Math.cos(h)*p,b:Math.sin(h)*p,alpha:v.alpha})},interpolate:function(v,h,p){return{h:_M(v.h,h.h,p),c:An(v.c,h.c,p),l:An(v.l,h.l,p),alpha:An(v.alpha,h.alpha,p)}}};var E4=Object.freeze({__proto__:null,hcl:zg,lab:Iv});class Qd{constructor(h,p,w,T,I){this.type=h,this.operator=p,this.interpolation=w,this.input=T,this.labels=[],this.outputs=[];for(const[L,$]of I)this.labels.push(L),this.outputs.push($)}static interpolationFactor(h,p,w,T){let I=0;if(h.name==="exponential")I=cb(p,h.base,w,T);else if(h.name==="linear")I=cb(p,1,w,T);else if(h.name==="cubic-bezier"){const L=h.controlPoints;I=new sa(L[0],L[1],L[2],L[3]).solve(cb(p,1,w,T))}return I}static parse(h,p){let[w,T,I,...L]=h;if(!Array.isArray(T)||T.length===0)return p.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 p.error("Exponential interpolation requires a numeric base.",1,1);T={name:"exponential",base:X}}else{if(T[0]!=="cubic-bezier")return p.error(`Unknown interpolation type ${String(T[0])}`,1,0);{const X=T.slice(1);if(X.length!==4||X.some(re=>typeof re!="number"||re<0||re>1))return p.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);T={name:"cubic-bezier",controlPoints:X}}}if(h.length-1<4)return p.error(`Expected at least 4 arguments, but found only ${h.length-1}.`);if(h.length-1>3&&(h.length-1)%2!=0)return p.error("Expected an even number of arguments.");if(I=p.parse(I,2,yn),!I)return null;const $=[];let V=null;w==="interpolate-hcl"||w==="interpolate-lab"?V=bh:p.expectedType&&p.expectedType.kind!=="value"&&(V=p.expectedType);for(let X=0;X=re)return p.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',le);const _e=p.parse(oe,ge,V);if(!_e)return null;V=V||_e.type,$.push([re,_e])}return V.kind==="number"||V.kind==="color"||V.kind==="array"&&V.itemType.kind==="number"&&typeof V.N=="number"?new Qd(V,w,T,I,$):p.error(`Type ${Il(V)} is not interpolatable.`)}evaluate(h){const p=this.labels,w=this.outputs;if(p.length===1)return w[0].evaluate(h);const T=this.input.evaluate(h);if(T<=p[0])return w[0].evaluate(h);const I=p.length;if(T>=p[I-1])return w[I-1].evaluate(h);const L=Pw(p,T),$=Qd.interpolationFactor(this.interpolation,T,p[L],p[L+1]),V=w[L].evaluate(h),X=w[L+1].evaluate(h);return this.operator==="interpolate"?Gh[this.type.kind.toLowerCase()](V,X,$):this.operator==="interpolate-hcl"?zg.reverse(zg.interpolate(zg.forward(V),zg.forward(X),$)):Iv.reverse(Iv.interpolate(Iv.forward(V),Iv.forward(X),$))}eachChild(h){h(this.input);for(const p of this.outputs)h(p)}outputDefined(){return this.outputs.every(h=>h.outputDefined())}serialize(){let h;h=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const p=[this.operator,h,this.input.serialize()];for(let w=0;wey(T,$.type));return new db(L?Zi:w,I)}evaluate(h){let p,w=null,T=0;for(const I of this.args){if(T++,w=I.evaluate(h),w&&w instanceof Ed&&!w.available&&(p||(p=w),w=null,T===this.args.length))return p;if(w!==null)break}return w}eachChild(h){this.args.forEach(h)}outputDefined(){return this.args.every(h=>h.outputDefined())}serialize(){const h=["coalesce"];return this.eachChild(p=>{h.push(p.serialize())}),h}}class Pv{constructor(h,p){this.type=p.type,this.bindings=[].concat(h),this.result=p}evaluate(h){return this.result.evaluate(h)}eachChild(h){for(const p of this.bindings)h(p[1]);h(this.result)}static parse(h,p){if(h.length<4)return p.error(`Expected at least 3 arguments, but found ${h.length-1} instead.`);const w=[];for(let I=1;I=w.length)throw new hl("Array index out of bounds: index exceeds array size");if(p!==Math.floor(p))throw new hl("Array index must be an integer. Use at-interpolated for fractional indices");return w[p]}eachChild(h){h(this.index),h(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class Ow{constructor(h,p,w){this.type=h,this.index=p,this.input=w}static parse(h,p){if(h.length!==3)return p.error(`Expected 2 arguments, but found ${h.length-1} instead.`);const w=p.parse(h[1],1,yn),T=p.parse(h[2],2,Tu(p.expectedType||Zi));return w&&T?new Ow(T.type.itemType,w,T):null}evaluate(h){const p=this.index.evaluate(h),w=this.input.evaluate(h);if(p<0)throw new hl(`Array index out of bounds: ${p} < 0.`);if(p>w.length-1)throw new hl(`Array index out of bounds: ${p} > ${w.length-1}.`);if(p===Math.floor(p))return w[p];const T=Math.floor(p),I=Math.ceil(p),L=w[T],$=w[I];if(typeof L!="number"||typeof $!="number")throw new hl(`Cannot interpolate between non-number values at index ${p}.`);const V=p-T;return L*(1-V)+$*V}eachChild(h){h(this.index),h(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class Bm{constructor(h,p){this.type=Bi,this.needle=h,this.haystack=p}static parse(h,p){if(h.length!==3)return p.error(`Expected 2 arguments, but found ${h.length-1} instead.`),null;const w=p.parse(h[1],1,Zi),T=p.parse(h[2],2,Zi);return w&&T?tb(w.type,[Bi,wi,yn,ip,Zi])?new Bm(w,T):(p.error(`Expected first argument to be of type boolean, string, number or null, but found ${Il(w.type)} instead`),null):null}evaluate(h){const p=this.needle.evaluate(h),w=this.haystack.evaluate(h);if(w==null)return!1;if(!Hp(p,["boolean","string","number","null"]))throw new hl(`Expected first argument to be of type boolean, string, number or null, but found ${Il(kl(p))} instead.`);if(!Hp(w,["string","array"]))throw new hl(`Expected second argument to be of type array or string, but found ${Il(kl(w))} instead.`);return w.indexOf(p)>=0}eachChild(h){h(this.needle),h(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Fw{constructor(h,p,w){this.type=yn,this.needle=h,this.haystack=p,this.fromIndex=w}static parse(h,p){if(h.length<=2||h.length>=5)return p.error(`Expected 3 or 4 arguments, but found ${h.length-1} instead.`),null;const w=p.parse(h[1],1,Zi),T=p.parse(h[2],2,Zi);if(!w||!T)return null;if(!tb(w.type,[Bi,wi,yn,ip,Zi]))return p.error(`Expected first argument to be of type boolean, string, number or null, but found ${Il(w.type)} instead`),null;if(h.length===4){const I=p.parse(h[3],3,yn);return I?new Fw(w,T,I):null}return new Fw(w,T)}evaluate(h){const p=this.needle.evaluate(h),w=this.haystack.evaluate(h);if(!Hp(p,["boolean","string","number","null"]))throw new hl(`Expected first argument to be of type boolean, string, number or null, but found ${Il(kl(p))} instead.`);if(!Hp(w,["string","array"]))throw new hl(`Expected second argument to be of type array or string, but found ${Il(kl(w))} instead.`);if(this.fromIndex){const T=this.fromIndex.evaluate(h);return w.indexOf(p,T)}return w.indexOf(p)}eachChild(h){h(this.needle),h(this.haystack),this.fromIndex&&h(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const h=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),h]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class Lv{constructor(h,p,w,T,I,L){this.inputType=h,this.type=p,this.input=w,this.cases=T,this.outputs=I,this.otherwise=L}static parse(h,p){if(h.length<5)return p.error(`Expected at least 4 arguments, but found only ${h.length-1}.`);if(h.length%2!=1)return p.error("Expected an even number of arguments.");let w,T;p.expectedType&&p.expectedType.kind!=="value"&&(T=p.expectedType);const I={},L=[];for(let X=2;XNumber.MAX_SAFE_INTEGER)return le.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof _e=="number"&&Math.floor(_e)!==_e)return le.error("Numeric branch labels must be integer values.");if(w){if(le.checkSubtype(w,kl(_e)))return null}else w=kl(_e);if(I[String(_e)]!==void 0)return le.error("Branch labels must be unique.");I[String(_e)]=L.length}const ge=p.parse(oe,X,T);if(!ge)return null;T=T||ge.type,L.push(ge)}const $=p.parse(h[1],1,Zi);if(!$)return null;const V=p.parse(h[h.length-1],h.length-1,T);return V?$.type.kind!=="value"&&p.concat(1).checkSubtype(w,$.type)?null:new Lv(w,T,$,I,L,V):null}evaluate(h){const p=this.input.evaluate(h);return(Gp(kl(p),this.inputType)&&this.outputs[this.cases[p]]||this.otherwise).evaluate(h)}eachChild(h){h(this.input),this.outputs.forEach(h),h(this.otherwise)}outputDefined(){return this.outputs.every(h=>h.outputDefined())&&this.otherwise.outputDefined()}serialize(){const h=["match",this.input.serialize()],p=Object.keys(this.cases).sort(),w=[],T={};for(const L of p){const $=T[this.cases[L]];$===void 0?(T[this.cases[L]]=w.length,w.push([this.cases[L],[L]])):w[$][1].push(L)}const I=L=>this.inputType.kind==="number"?Number(L):L;for(const[L,$]of w)h.push($.length===1?I($[0]):$.map(I)),h.push(this.outputs[L].serialize());return h.push(this.otherwise.serialize()),h}}class oy{constructor(h,p,w){this.type=h,this.branches=p,this.otherwise=w}static parse(h,p){if(h.length<4)return p.error(`Expected at least 3 arguments, but found only ${h.length-1}.`),null;if(h.length%2!=0)return p.error("Expected an odd number of arguments."),null;let w;p.expectedType&&p.expectedType.kind!=="value"&&(w=p.expectedType);const T=[];for(let L=1;Lp.outputDefined())&&this.otherwise.outputDefined()}serialize(){const h=["case"];return this.eachChild(p=>{h.push(p.serialize())}),h}}class ly{constructor(h,p,w,T){this.type=h,this.input=p,this.beginIndex=w,this.endIndex=T}static parse(h,p){if(h.length<=2||h.length>=5)return p.error(`Expected 3 or 4 arguments, but found ${h.length-1} instead.`),null;const w=p.parse(h[1],1,Zi),T=p.parse(h[2],2,yn);if(!w||!T)return null;if(!tb(w.type,[Tu(Zi),wi,Zi]))return p.error(`Expected first argument to be of type array or string, but found ${Il(w.type)} instead`),null;if(h.length===4){const I=p.parse(h[3],3,yn);return I?new ly(w.type,w,T,I):null}return new ly(w.type,w,T)}evaluate(h){const p=this.input.evaluate(h),w=this.beginIndex.evaluate(h);if(!Hp(p,["string","array"]))throw new hl(`Expected first argument to be of type array or string, but found ${Il(kl(p))} instead.`);if(this.endIndex){const T=this.endIndex.evaluate(h);return p.slice(w,T)}return p.slice(w)}eachChild(h){h(this.input),h(this.beginIndex),this.endIndex&&h(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const h=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),h]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class ub{constructor(h,p){this.type=Tu(wi),this.str=h,this.delimiter=p}static parse(h,p){if(h.length!==3)return p.error(`Expected 2 arguments, but found ${h.length-1} instead.`);const w=p.parse(h[1],1,wi),T=p.parse(h[2],2,wi);return w&&T?new ub(w,T):void 0}evaluate(h){const p=this.str.evaluate(h),w=this.delimiter.evaluate(h);return p.split(w)}eachChild(h){h(this.str),h(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function A4(v,h){return v==="=="||v==="!="?h.kind==="boolean"||h.kind==="string"||h.kind==="number"||h.kind==="null"||h.kind==="value":h.kind==="string"||h.kind==="number"||h.kind==="value"}function hb(v,h,p,w){return w.compare(h,p)===0}function Yc(v,h,p){const w=v!=="=="&&v!=="!=";return class Hnt{constructor(I,L,$){this.type=Bi,this.lhs=I,this.rhs=L,this.collator=$,this.hasUntypedArgument=I.type.kind==="value"||L.type.kind==="value"}static parse(I,L){if(I.length!==3&&I.length!==4)return L.error("Expected two or three arguments.");const $=I[0];let V=L.parse(I[1],1,Zi);if(!V)return null;if(!A4($,V.type))return L.concat(1).error(`"${$}" comparisons are not supported for type '${Il(V.type)}'.`);let X=L.parse(I[2],2,Zi);if(!X)return null;if(!A4($,X.type))return L.concat(2).error(`"${$}" comparisons are not supported for type '${Il(X.type)}'.`);if(V.type.kind!==X.type.kind&&V.type.kind!=="value"&&X.type.kind!=="value")return L.error(`Cannot compare types '${Il(V.type)}' and '${Il(X.type)}'.`);w&&(V.type.kind==="value"&&X.type.kind!=="value"?V=new Om(X.type,[V]):V.type.kind!=="value"&&X.type.kind==="value"&&(X=new Om(V.type,[X])));let re=null;if(I.length===4){if(V.type.kind!=="string"&&X.type.kind!=="string"&&V.type.kind!=="value"&&X.type.kind!=="value")return L.error("Cannot use collator to compare non-string types.");if(re=L.parse(I[3],3,Vp),!re)return null}return new Hnt(V,X,re)}evaluate(I){const L=this.lhs.evaluate(I),$=this.rhs.evaluate(I);if(w&&this.hasUntypedArgument){const V=kl(L),X=kl($);if(V.kind!==X.kind||V.kind!=="string"&&V.kind!=="number")throw new hl(`Expected arguments for "${v}" to be (string, string) or (number, number), but found (${V.kind}, ${X.kind}) instead.`)}if(this.collator&&!w&&this.hasUntypedArgument){const V=kl(L),X=kl($);if(V.kind!=="string"||X.kind!=="string")return h(I,L,$)}return this.collator?p(I,L,$,this.collator.evaluate(I)):h(I,L,$)}eachChild(I){I(this.lhs),I(this.rhs),this.collator&&I(this.collator)}outputDefined(){return!0}serialize(){const I=[v];return this.eachChild(L=>{I.push(L.serialize())}),I}}}const wM=Yc("==",function(v,h,p){return h===p},hb),rN=Yc("!=",function(v,h,p){return h!==p},function(v,h,p,w){return!hb(0,h,p,w)}),nN=Yc("<",function(v,h,p){return h",function(v,h,p){return h>p},function(v,h,p,w){return w.compare(h,p)>0}),_D=Yc("<=",function(v,h,p){return h<=p},function(v,h,p,w){return w.compare(h,p)<=0}),Pa=Yc(">=",function(v,h,p){return h>=p},function(v,h,p,w){return w.compare(h,p)>=0});class Bg{constructor(h,p,w,T,I,L){this.type=wi,this.number=h,this.locale=p,this.currency=w,this.unit=T,this.minFractionDigits=I,this.maxFractionDigits=L}static parse(h,p){if(h.length!==3)return p.error("Expected two arguments.");const w=p.parse(h[1],1,yn);if(!w)return null;const T=h[2];if(typeof T!="object"||Array.isArray(T))return p.error("NumberFormat options argument must be an object.");let I=null;if(T.locale&&(I=p.parseObjectValue(T.locale,2,"locale",wi),!I))return null;let L=null;if(T.currency&&(L=p.parseObjectValue(T.currency,2,"currency",wi),!L))return null;let $=null;if(T.unit&&($=p.parseObjectValue(T.unit,2,"unit",wi),!$))return null;let V=null;if(T["min-fraction-digits"]&&(V=p.parseObjectValue(T["min-fraction-digits"],2,"min-fraction-digits",yn),!V))return null;let X=null;return T["max-fraction-digits"]&&(X=p.parseObjectValue(T["max-fraction-digits"],2,"max-fraction-digits",yn),!X)?null:new Bg(w,I,L,$,V,X)}evaluate(h){return new Intl.NumberFormat(this.locale?this.locale.evaluate(h):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(h):void 0,unit:this.unit?this.unit.evaluate(h):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(h):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(h):void 0}).format(this.number.evaluate(h))}eachChild(h){h(this.number),this.locale&&h(this.locale),this.currency&&h(this.currency),this.unit&&h(this.unit),this.minFractionDigits&&h(this.minFractionDigits),this.maxFractionDigits&&h(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const h={};return this.locale&&(h.locale=this.locale.serialize()),this.currency&&(h.currency=this.currency.serialize()),this.unit&&(h.unit=this.unit.serialize()),this.minFractionDigits&&(h["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(h["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),h]}}class mb{constructor(h){this.type=yn,this.input=h}static parse(h,p){if(h.length!==2)return p.error(`Expected 1 argument, but found ${h.length-1} instead.`),null;const w=p.parse(h[1],1);return w?w.type.kind!=="array"&&w.type.kind!=="string"&&w.type.kind!=="value"?(p.error(`Expected argument of type string or array, but found ${Il(w.type)} instead.`),null):new mb(w):null}evaluate(h){const p=this.input.evaluate(h);if(typeof p=="string"||Array.isArray(p))return p.length;throw new hl(`Expected value to be of type string or array, but found ${Il(kl(p))} instead.`)}eachChild(h){h(this.input)}outputDefined(){return!1}serialize(){const h=["length"];return this.eachChild(p=>{h.push(p.serialize())}),h}}function M4(v){return function(){v=1831565813+(v|=0)|0;let h=Math.imul(v^v>>>15,1|v);return h=h+Math.imul(h^h>>>7,61|h)^h,((h^h>>>14)>>>0)/4294967296}}const fb={"==":wM,"!=":rN,">":Qu,"<":nN,">=":Pa,"<=":_D,array:Om,at:_f,"at-interpolated":Ow,boolean:Om,case:oy,coalesce:db,collator:_w,format:Wh,image:Cn,in:Bm,"index-of":Fw,interpolate:Qd,"interpolate-hcl":Qd,"interpolate-lab":Qd,length:mb,let:Pv,literal:Jr,match:Lv,number:Om,"number-format":Bg,object:Om,slice:ly,step:Lw,string:Om,"to-boolean":Kh,"to-color":Kh,"to-number":Kh,"to-string":Kh,var:Mw,within:Fx,distance:ny,config:Ev,split:ub};function pb(v,[h,p,w,T]){h=h.evaluate(v),p=p.evaluate(v),w=w.evaluate(v);const I=T?T.evaluate(v):1,L=gf(h,p,w,I);if(L)throw new hl(L);return new Vr(h/255,p/255,w/255,I)}function zw(v,[h,p,w,T]){h=h.evaluate(v),p=p.evaluate(v),w=w.evaluate(v);const I=T?T.evaluate(v):1,L=function(X,re,oe,le){return typeof X=="number"&&X>=0&&X<=360?typeof re=="number"&&re>=0&&re<=100&&typeof oe=="number"&&oe>=0&&oe<=100?le===void 0||typeof le=="number"&&le>=0&&le<=1?null:`Invalid hsla value [${[X,re,oe,le].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof le=="number"?[X,re,oe,le]:[X,re,oe]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof le=="number"?[X,re,oe,le]:[X,re,oe]).join(", ")}]: 'h' must be between 0 and 360.`}(h,p,w,I);if(L)throw new hl(L);const $=`hsla(${h}, ${p}%, ${w}%, ${I})`,V=Vr.parse($);if(!V)throw new hl(`Failed to parse HSLA color: ${$}`);return V}function Dv(v,h){return v in h}function Bw(v,h){const p=h[v];return p===void 0?null:p}function $g(v){return{type:v}}function $w(v){if(v instanceof Ev)return new Set([v.key]);let h=new Set;return v.eachChild(p=>{h=new Set([...h,...$w(p)])}),h}function xb(v){if(v instanceof wc&&v.name==="is-active-floor")return!0;let h=!1;return v.eachChild(p=>{!h&&xb(p)&&(h=!0)}),h}function aN(v){return{result:"success",value:v}}function jc(v){return{result:"error",value:v}}function Xh(v,h){return!!v&&!!v.parameters&&v.parameters.indexOf(h)>-1}function wf(v){return v["property-type"]==="data-driven"}function iN(v){return Xh(v.expression,"measure-light")}function oN(v){return Xh(v.expression,"zoom")}function $m(v){return!!v.expression&&v.expression.interpolated}function lN(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function Wp(v){return v}function jM(v,h){const p=h.type==="color",w=v.stops&&typeof v.stops[0][0]=="object",T=w||!(w||v.property!==void 0),I=v.type||($m(h)?"exponential":"interval");if(p&&((v=Object.assign({},v)).stops&&(v.stops=v.stops.map(X=>[X[0],Vr.parse(X[1])])),v.default=Vr.parse(v.default?v.default:h.default)),v.colorSpace&&v.colorSpace!=="rgb"&&!E4[v.colorSpace])throw new Error(`Unknown color space: ${v.colorSpace}`);let L,$,V;if(I==="exponential")L=I4;else if(I==="interval")L=kM;else if(I==="categorical"){L=NM,$=Object.create(null);for(const X of v.stops)$[X[0]]=X[1];V=typeof v.stops[0][0]}else{if(I!=="identity")throw new Error(`Unknown function type "${I}"`);L=Uw}if(w){const X={},re=[];for(let ge=0;gege[0]),evaluate:({zoom:ge},_e)=>I4({stops:oe,base:v.base},h,ge).evaluate(ge,_e)}}if(T){const X=I==="exponential"?{name:"exponential",base:v.base!==void 0?v.base:1}:null;return{kind:"camera",interpolationType:X,interpolationFactor:Qd.interpolationFactor.bind(void 0,X),zoomStops:v.stops.map(re=>re[0]),evaluate:({zoom:re})=>L(v,h,re,$,V)}}return{kind:"source",evaluate(X,re){const oe=re&&re.properties?re.properties[v.property]:void 0;return oe===void 0?Kp(v.default,h.default):L(v,h,oe,$,V)}}}function Kp(v,h,p){return v!==void 0?v:h!==void 0?h:p!==void 0?p:void 0}function NM(v,h,p,w,T){return Kp(typeof p===T?w[p]:void 0,v.default,h.default)}function kM(v,h,p){if(!rb(p))return Kp(v.default,h.default);const w=v.stops.length;if(w===1||p<=v.stops[0][0])return v.stops[0][1];if(p>=v.stops[w-1][0])return v.stops[w-1][1];const T=Pw(v.stops.map(I=>I[0]),p);return v.stops[T][1]}function I4(v,h,p){const w=v.base!==void 0?v.base:1;if(!rb(p))return Kp(v.default,h.default);const T=v.stops.length;if(T===1||p<=v.stops[0][0])return v.stops[0][1];if(p>=v.stops[T-1][0])return v.stops[T-1][1];const I=Pw(v.stops.map(re=>re[0]),p),L=function(re,oe,le,ge){const _e=ge-le,Te=re-le;return _e===0?0:oe===1?Te/_e:(Math.pow(oe,Te)-1)/(Math.pow(oe,_e)-1)}(p,w,v.stops[I][0],v.stops[I+1][0]),$=v.stops[I][1],V=v.stops[I+1][1];let X=Gh[h.type]||Wp;if(v.colorSpace&&v.colorSpace!=="rgb"){const re=E4[v.colorSpace];X=(oe,le)=>re.reverse(re.interpolate(re.forward(oe),re.forward(le),L))}return typeof $.evaluate=="function"?{evaluate(...re){const oe=$.evaluate.apply(void 0,re),le=V.evaluate.apply(void 0,re);if(oe!==void 0&&le!==void 0)return X(oe,le,L)}}:X($,V,L)}function Uw(v,h,p){return h.type==="color"?p=Vr.parse(p):h.type==="formatted"?p=Td.fromString(p.toString()):h.type==="resolvedImage"?p=Ed.build(p.toString()):ty(p)===h.type||h.type==="enum"&&h.values[p]||(p=void 0),Kp(p,v.default,h.default)}wc.register(fb,{error:[{kind:"error"},[wi],(v,[h])=>{throw new hl(h.evaluate(v))}],typeof:[wi,[Zi],(v,[h])=>Il(kl(h.evaluate(v)))],"to-rgba":[Tu(yn,4),[bh],(v,[h])=>h.evaluate(v).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Tu(yn,4),[bh],(v,[h])=>h.evaluate(v).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[bh,[yn,yn,yn],pb],rgba:[bh,[yn,yn,yn,yn],pb],hsl:[bh,[yn,yn,yn],zw],hsla:[bh,[yn,yn,yn,yn],zw],has:{type:Bi,overloads:[[[wi],(v,[h])=>Dv(h.evaluate(v),v.properties())],[[wi,qp],(v,[h,p])=>Dv(h.evaluate(v),p.evaluate(v))]]},get:{type:Zi,overloads:[[[wi],(v,[h])=>Bw(h.evaluate(v),v.properties())],[[wi,qp],(v,[h,p])=>Bw(h.evaluate(v),p.evaluate(v))]]},"feature-state":[Zi,[wi],(v,[h])=>Bw(h.evaluate(v),v.featureState||{})],properties:[qp,[],v=>v.properties()],"geometry-type":[wi,[],v=>v.geometryType()],worldview:[wi,[],v=>v.globals.worldview||""],"is-active-floor":[Bi,$g(wi),(v,h)=>{if(!(v.globals&&v.globals.activeFloors&&v.globals.activeFloors.size>0))return!1;if(h.length===0)return!0;const p=v.globals.activeFloors;return h.some(w=>{const T=w.evaluate(v);return p.has(T)})}],id:[Zi,[],v=>v.id()],zoom:[yn,[],v=>v.globals.zoom],pitch:[yn,[],v=>v.globals.pitch||0],"distance-from-center":[yn,[],v=>v.distanceFromCenter()],"measure-light":[yn,[wi],(v,[h])=>v.measureLight(h.evaluate(v))],"heatmap-density":[yn,[],v=>v.globals.heatmapDensity||0],"line-progress":[yn,[],v=>v.globals.lineProgress||0],"raster-value":[yn,[],v=>v.globals.rasterValue||0],"raster-particle-speed":[yn,[],v=>v.globals.rasterParticleSpeed||0],"sky-radial-progress":[yn,[],v=>v.globals.skyRadialProgress||0],accumulated:[Zi,[],v=>v.globals.accumulated===void 0?null:v.globals.accumulated],"+":[yn,$g(yn),(v,h)=>{let p=0;for(const w of h)p+=w.evaluate(v);return p}],"*":[yn,$g(yn),(v,h)=>{let p=1;for(const w of h)p*=w.evaluate(v);return p}],"-":{type:yn,overloads:[[[yn,yn],(v,[h,p])=>h.evaluate(v)-p.evaluate(v)],[[yn],(v,[h])=>-h.evaluate(v)]]},"/":[yn,[yn,yn],(v,[h,p])=>h.evaluate(v)/p.evaluate(v)],"%":[yn,[yn,yn],(v,[h,p])=>h.evaluate(v)%p.evaluate(v)],ln2:[yn,[],()=>Math.LN2],pi:[yn,[],()=>Math.PI],e:[yn,[],()=>Math.E],"^":[yn,[yn,yn],(v,[h,p])=>Math.pow(h.evaluate(v),p.evaluate(v))],sqrt:[yn,[yn],(v,[h])=>Math.sqrt(h.evaluate(v))],log10:[yn,[yn],(v,[h])=>Math.log(h.evaluate(v))/Math.LN10],ln:[yn,[yn],(v,[h])=>Math.log(h.evaluate(v))],log2:[yn,[yn],(v,[h])=>Math.log2(h.evaluate(v))],sin:[yn,[yn],(v,[h])=>Math.sin(h.evaluate(v))],cos:[yn,[yn],(v,[h])=>Math.cos(h.evaluate(v))],tan:[yn,[yn],(v,[h])=>Math.tan(h.evaluate(v))],asin:[yn,[yn],(v,[h])=>Math.asin(h.evaluate(v))],acos:[yn,[yn],(v,[h])=>Math.acos(h.evaluate(v))],atan:[yn,[yn],(v,[h])=>Math.atan(h.evaluate(v))],min:[yn,$g(yn),(v,h)=>Math.min(...h.map(p=>p.evaluate(v)))],max:[yn,$g(yn),(v,h)=>Math.max(...h.map(p=>p.evaluate(v)))],abs:[yn,[yn],(v,[h])=>Math.abs(h.evaluate(v))],round:[yn,[yn],(v,[h])=>{const p=h.evaluate(v);return p<0?-Math.round(-p):Math.round(p)}],floor:[yn,[yn],(v,[h])=>Math.floor(h.evaluate(v))],ceil:[yn,[yn],(v,[h])=>Math.ceil(h.evaluate(v))],"filter-==":[Bi,[wi,Zi],(v,[h,p])=>v.properties()[h.value]===p.value],"filter-id-==":[Bi,[Zi],(v,[h])=>v.id()===h.value],"filter-type-==":[Bi,[wi],(v,[h])=>v.geometryType()===h.value],"filter-<":[Bi,[wi,Zi],(v,[h,p])=>{const w=v.properties()[h.value],T=p.value;return typeof w==typeof T&&w{const p=v.id(),w=h.value;return typeof p==typeof w&&p":[Bi,[wi,Zi],(v,[h,p])=>{const w=v.properties()[h.value],T=p.value;return typeof w==typeof T&&w>T}],"filter-id->":[Bi,[Zi],(v,[h])=>{const p=v.id(),w=h.value;return typeof p==typeof w&&p>w}],"filter-<=":[Bi,[wi,Zi],(v,[h,p])=>{const w=v.properties()[h.value],T=p.value;return typeof w==typeof T&&w<=T}],"filter-id-<=":[Bi,[Zi],(v,[h])=>{const p=v.id(),w=h.value;return typeof p==typeof w&&p<=w}],"filter->=":[Bi,[wi,Zi],(v,[h,p])=>{const w=v.properties()[h.value],T=p.value;return typeof w==typeof T&&w>=T}],"filter-id->=":[Bi,[Zi],(v,[h])=>{const p=v.id(),w=h.value;return typeof p==typeof w&&p>=w}],"filter-has":[Bi,[Zi],(v,[h])=>h.value in v.properties()],"filter-has-id":[Bi,[],v=>v.id()!==null&&v.id()!==void 0],"filter-type-in":[Bi,[Tu(wi)],(v,[h])=>h.value.indexOf(v.geometryType())>=0],"filter-id-in":[Bi,[Tu(Zi)],(v,[h])=>h.value.indexOf(v.id())>=0],"filter-in-small":[Bi,[wi,Tu(Zi)],(v,[h,p])=>p.value.indexOf(v.properties()[h.value])>=0],"filter-in-large":[Bi,[wi,Tu(Zi)],(v,[h,p])=>function(w,T,I,L){for(;I<=L;){const $=I+L>>1;if(T[$]===w)return!0;T[$]>w?L=$-1:I=$+1}return!1}(v.properties()[h.value],p.value,0,p.value.length-1)],all:{type:Bi,overloads:[[[Bi,Bi],(v,[h,p])=>h.evaluate(v)&&p.evaluate(v)],[$g(Bi),(v,h)=>{for(const p of h)if(!p.evaluate(v))return!1;return!0}]]},any:{type:Bi,overloads:[[[Bi,Bi],(v,[h,p])=>h.evaluate(v)||p.evaluate(v)],[$g(Bi),(v,h)=>{for(const p of h)if(p.evaluate(v))return!0;return!1}]]},"!":[Bi,[Bi],(v,[h])=>!h.evaluate(v)],"is-supported-script":[Bi,[wi],(v,[h])=>{const p=v.globals&&v.globals.isSupportedScript;return!p||p(h.evaluate(v))}],upcase:[wi,[wi],(v,[h])=>h.evaluate(v).toUpperCase()],downcase:[wi,[wi],(v,[h])=>h.evaluate(v).toLowerCase()],concat:[wi,$g(Zi),(v,h)=>h.map(p=>Hn(p.evaluate(v))).join("")],"resolved-locale":[wi,[Vp],(v,[h])=>h.evaluate(v).resolvedLocale()],random:[yn,[yn,yn,Zi],(v,h)=>{const[p,w,T]=h.map(L=>L.evaluate(v));if(p>w||p===w)return p;let I;if(typeof T=="string")I=function(L){let $=0;if(L.length===0)return $;for(let V=0;VJSON.stringify(oe)).join(", ")}, but found ${JSON.stringify(re)} instead.`);return re}catch(re){const oe=re;return this._warningHistory[oe.message]||(this._warningHistory[oe.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${oe.message}`)),this._defaultValue}}}function cy(v){return Array.isArray(v)&&v.length>0&&typeof v[0]=="string"&&v[0]in fb}function Yp(v,h,p,w,T){const I=new Iw(fb,[],h?function($){const V={color:bh,string:wi,number:yn,enum:wi,boolean:Bi,formatted:J0,resolvedImage:eb};return $.type==="array"?Tu(V[$.value]||Zi,$.length):V[$.type]}(h):void 0,void 0,void 0,p,w,T),L=I.parse(v,void 0,void 0,void 0,h&&h.type==="string"?{typeAnnotation:"coerce"}:void 0);return L?aN(new Rv(L,h,p,w,T)):jc(I.errors)}class Ug{constructor(h,p,w,T){this.kind=h,this._styleExpression=p,this.isLightConstant=w,this.isLineProgressConstant=T,this.isStateDependent=h!=="constant"&&!iy(p.expression),this.configDependencies=$w(p.expression),this.isIndoorDependent=xb(p.expression)}evaluateWithoutErrorHandling(h,p,w,T,I,L){return this._styleExpression.evaluateWithoutErrorHandling(h,p,w,T,I,L)}evaluate(h,p,w,T,I,L,$){return this._styleExpression.evaluate(h,p,w,T,I,L,void 0,void 0,$)}}class Zp{constructor(h,p,w,T,I,L){this.kind=h,this.zoomStops=w,this._styleExpression=p,this.isStateDependent=h!=="camera"&&!iy(p.expression),this.isIndoorDependent=xb(p.expression),this.isLightConstant=I,this.isLineProgressConstant=L,this.configDependencies=$w(p.expression),this.interpolationType=T}evaluateWithoutErrorHandling(h,p,w,T,I,L){return this._styleExpression.evaluateWithoutErrorHandling(h,p,w,T,I,L)}evaluate(h,p,w,T,I,L){return this._styleExpression.evaluate(h,p,w,T,I,L)}interpolationFactor(h,p,w){return this.interpolationType?Qd.interpolationFactor(this.interpolationType,h,p,w):0}}function qw(v,h,p,w,T){if((v=Yp(v,h,p,w,T)).result==="error")return v;const I=v.value.expression,L=ay(I);if(!L&&!wf(h))return jc([new Cu("","data expressions not supported")]);const $=Yh(I,["zoom","pitch","distance-from-center"]);if(!$&&!oN(h))return jc([new Cu("","zoom expressions not supported")]);const V=Yh(I,["measure-light"]);if(!V&&!iN(h))return jc([new Cu("","measure-light expression not supported")]);const X=Yh(I,["line-progress"]);if(!X&&!function(le){return Xh(le.expression,"line-progress")}(h))return jc([new Cu("","line-progress expression not supported")]);const re=h.expression&&h.expression.relaxZoomRestriction,oe=jf(I);return oe||$||re?oe instanceof Cu?jc([oe]):oe instanceof Qd&&!$m(h)?jc([new Cu("",'"interpolate" expressions cannot be used with this property')]):aN(oe?new Zp(L&&X?"camera":"composite",v.value,oe.labels,oe instanceof Qd?oe.interpolation:void 0,V,X):new Ug(L&&X?"constant":"source",v.value,V,X)):jc([new Cu("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class gb{constructor(h,p){this._parameters=h,this._specification=p,Object.assign(this,jM(this._parameters,this._specification))}static deserialize(h){return new gb(h._parameters,h._specification)}static serialize(h){return{_parameters:h._parameters,_specification:h._specification}}}function jf(v){let h=null;if(v instanceof Pv)h=jf(v.result);else if(v instanceof db){for(const p of v.args)if(h=jf(p),h)break}else(v instanceof Lw||v instanceof Qd)&&v.input instanceof wc&&v.input.name==="zoom"&&(h=v);return h instanceof Cu||v.eachChild(p=>{const w=jf(p);w instanceof Cu?h=w:h&&w&&h!==w&&(h=new Cu("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),h}var cN,dN,Vw=function(){if(dN)return cN;dN=1,cN=h;var v=3;function h(p,w,T){var I=this.cells=[];if(p instanceof ArrayBuffer){this.arrayBuffer=p;var L=new Int32Array(this.arrayBuffer);p=L[0],this.d=(w=L[1])+2*(T=L[2]);for(var $=0;$=le[Te+0]&&I>=le[Te+1])?(V[_e]=!0,$.push(oe[_e])):V[_e]=!1}}},h.prototype._forEachCell=function(p,w,T,I,L,$,V,X){for(var re=this._convertToCellCoord(p),oe=this._convertToCellCoord(w),le=this._convertToCellCoord(T),ge=this._convertToCellCoord(I),_e=re;_e<=le;_e++)for(var Te=oe;Te<=ge;Te++){var Fe=this.d*Te+_e;if((!X||X(this._convertFromCellCoord(_e),this._convertFromCellCoord(Te),this._convertFromCellCoord(_e+1),this._convertFromCellCoord(Te+1)))&&L.call(this,p,w,T,I,Fe,$,V,X))return}},h.prototype._convertFromCellCoord=function(p){return(p-this.padding)/this.scale},h.prototype._convertToCellCoord=function(p){return Math.max(0,Math.min(this.d-1,Math.floor(p*this.scale)+this.padding))},h.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var p=this.cells,w=v+this.cells.length+1+1,T=0,I=0;I=0||(T[I]=ec(v[I],h)));v instanceof Error&&(T.message=v.message)}if(T.$name)throw new Error("$name property is reserved for worker serialization logic.");return w!=="Object"&&(T.$name=w),T}throw new Error("can't serialize object of type "+typeof v)}function Hl(v){if(v==null||typeof v=="boolean"||typeof v=="number"||typeof v=="string"||v instanceof Boolean||v instanceof Number||v instanceof String||v instanceof Date||v instanceof RegExp||uo(v)||v instanceof ImageBitmap||ArrayBuffer.isView(v)||v instanceof ImageData)return v;if(Array.isArray(v))return v.map(Hl);if(typeof v=="object"){const h=v.$name||"Object";if(h==="Map"){const T=v.entries||[],I=new Map;for(let L=0;Lv>=1536&&v<=1791,jh=v=>v>=1872&&v<=1919,Hg=v=>v>=2208&&v<=2303,Zc=v=>v>=11904&&v<=12031,Nf=v=>v>=12032&&v<=12255,Gg=v=>v>=12272&&v<=12287,dy=v=>v>=12288&&v<=12351,Ov=v=>v>=12352&&v<=12447,Xp=v=>v>=12448&&v<=12543,Nh=v=>v>=12544&&v<=12591,yb=v=>v>=12704&&v<=12735,mp=v=>v>=12736&&v<=12783,Bx=v=>v>=12784&&v<=12799,Fv=v=>v>=12800&&v<=13055,Hw=v=>v>=13056&&v<=13311,Gw=v=>v>=13312&&v<=19903,Qp=v=>v>=19968&&v<=40959,uy=v=>v>=40960&&v<=42127,$x=v=>v>=42128&&v<=42191,vb=v=>v>=44032&&v<=55215,hy=v=>v>=63744&&v<=64255,Ww=v=>v>=64336&&v<=65023,Kw=v=>v>=65040&&v<=65055,bb=v=>v>=65072&&v<=65103,Ju=v=>v>=65104&&v<=65135,Ux=v=>v>=65136&&v<=65279,Um=v=>v>=65280&&v<=65519;function kh(v){for(const h of v)if(D4(h.charCodeAt(0)))return!0;return!1}function SM(v){for(const h of v)if(!P4(h.charCodeAt(0)))return!1;return!0}function P4(v){return!(Eu(v)||jh(v)||Hg(v)||Ww(v)||Ux(v))}function L4(v){return!(v<11904||!(yb(v)||Nh(v)||bb(v)||hy(v)||Hw(v)||Zc(v)||mp(v)||dy(v)||Gw(v)||Qp(v)||Fv(v)||Um(v)||Ov(v)||Gg(v)||Nf(v)||Bx(v)||Xp(v)||Kw(v)||$x(v)||uy(v)))}function D4(v){return!(v!==746&&v!==747&&(v<4352||!(yb(v)||Nh(v)||bb(v)&&!(v>=65097&&v<=65103)||hy(v)||Hw(v)||Zc(v)||mp(v)||!(!dy(v)||v>=12296&&v<=12305||v>=12308&&v<=12319||v===12336)||Gw(v)||Qp(v)||Fv(v)||(h=>h>=12592&&h<=12687)(v)||(h=>h>=43360&&h<=43391)(v)||(h=>h>=55216&&h<=55295)(v)||(h=>h>=4352&&h<=4607)(v)||vb(v)||Ov(v)||Gg(v)||(h=>h>=12688&&h<=12703)(v)||Nf(v)||Bx(v)||Xp(v)&&v!==12540||!(!Um(v)||v===65288||v===65289||v===65293||v>=65306&&v<=65310||v===65339||v===65341||v===65343||v>=65371&&v<=65503||v===65507||v>=65512&&v<=65519)||!(!Ju(v)||v>=65112&&v<=65118||v>=65123&&v<=65126)||(h=>h>=5120&&h<=5759)(v)||(h=>h>=6320&&h<=6399)(v)||Kw(v)||(h=>h>=19904&&h<=19967)(v)||uy(v)||$x(v))))}function Wg(v){return v===12312||v===12313||v===12316||v===12540||v===12448}function my(v){return!(D4(v)||function(h){return!!((p=>p>=128&&p<=255)(h)&&(h===167||h===169||h===174||h===177||h===188||h===189||h===190||h===215||h===247)||(p=>p>=8192&&p<=8303)(h)&&(h===8214||h===8224||h===8225||h===8240||h===8241||h===8251||h===8252||h===8258||h===8263||h===8264||h===8265||h===8273)||(p=>p>=8448&&p<=8527)(h)||(p=>p>=8528&&p<=8591)(h)||(p=>p>=8960&&p<=9215)(h)&&(h>=8960&&h<=8967||h>=8972&&h<=8991||h>=8996&&h<=9e3||h===9003||h>=9085&&h<=9114||h>=9150&&h<=9165||h===9167||h>=9169&&h<=9179||h>=9186&&h<=9215)||(p=>p>=9216&&p<=9279)(h)&&h!==9251||(p=>p>=9280&&p<=9311)(h)||(p=>p>=9312&&p<=9471)(h)||(p=>p>=9632&&p<=9727)(h)||(p=>p>=9728&&p<=9983)(h)&&!(h>=9754&&h<=9759)||(p=>p>=11008&&p<=11263)(h)&&(h>=11026&&h<=11055||h>=11088&&h<=11097||h>=11192&&h<=11243)||dy(h)||Xp(h)||(p=>p>=57344&&p<=63743)(h)||bb(h)||Ju(h)||Um(h)||h===8734||h===8756||h===8757||h>=9984&&h<=10087||h>=10102&&h<=10131||h===65532||h===65533)}(v))}function R4(v){return Eu(v)||jh(v)||Hg(v)||Ww(v)||Ux(v)}function Yw(v){return v>=1424&&v<=2303||Ww(v)||Ux(v)}function qx(v,h){return!(!h&&Yw(v)||v>=2304&&v<=3583||v>=3840&&v<=4255||(p=>p>=6016&&p<=6143)(v))}function CM(v){for(const h of v)if(Yw(h.charCodeAt(0)))return!0;return!1}const Qh={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let fp=null,Md=Qh.unavailable,kf=null;const TM=function(v){v&&typeof v=="string"&&v.indexOf("NetworkError")>-1&&(Md=Qh.error),fp&&fp(v)};function uN(){hN.fire(new _c("pluginStateChange",{pluginStatus:Md,pluginURL:kf}))}const hN=new xf,Kg=function(){return Md},EM=function(){if(Md!==Qh.deferred||!kf)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Md=Qh.loading,uN(),kf&&X0({url:kf},v=>{v?TM(v):(Md=Qh.loaded,uN())})},Jh={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Md===Qh.loaded||Jh.applyArabicShaping!=null,isLoading:()=>Md===Qh.loading,setState(v){Md=v.pluginStatus,kf=v.pluginURL},isParsing:()=>Md===Qh.parsing,isParsed:()=>Md===Qh.parsed,getPluginURL:()=>kf},O4=function(){Jh.isLoading()||Jh.isLoaded()||Kg()!=="deferred"||EM()};class ja{constructor(h,p){this.zoom=h,p?(this.now=p.now,this.fadeDuration=p.fadeDuration,this.transition=p.transition,this.pitch=p.pitch,this.brightness=p.brightness,this.worldview=p.worldview,this.activeFloors=p.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(h){return function(p,w){for(const T of p)if(!qx(T.charCodeAt(0),w))return!1;return!0}(h,Jh.isLoaded())}}class _b{constructor(h,p,w,T,I){this.property=h,this.value=p,this.expression=function(L,$,V,X,re){if(lN(L))return new gb(L,$);if(cy(L)||Array.isArray(L)&&L.length>0){const oe=qw(L,$,V,X,re);if(oe.result==="error")throw new Error(oe.value.map(le=>`${le.key}: ${le.message}`).join(", "));return oe.value}{let oe=L;return typeof L=="string"&&$.type==="color"&&(oe=Vr.parse(L)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>oe}}}(p===void 0?h.specification.default:p,h.specification,w,T,I)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(h,p,w,T){return this.property.possiblyEvaluate(this,h,p,w,T)}}class Zw{constructor(h,p,w,T){this.property=h,this.value=new _b(h,void 0,p,w,T)}transitioned(h,p){return new wb(this.property,this.value,p,Object.assign({},h.transition,this.transition),h.now)}untransitioned(){return new wb(this.property,this.value,null,{},0)}}class mN{constructor(h,p,w,T){this._properties=h,this._values=Object.create(h.defaultTransitionablePropertyValues),this._scope=p,this._options=w,this._iconImageUseTheme=T,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(h){return cr(this._values[h].value.value)}setValue(h,p){this._values.hasOwnProperty(h)||(this._values[h]=new Zw(this._values[h].property,this._scope,this._options,this._iconImageUseTheme)),this._values[h].value=new _b(this._values[h].property,p===null?void 0:cr(p),this._scope,this._options,this._iconImageUseTheme),this._values[h].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[h].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[h].value.isIndoorDependent())}setTransitionOrValue(h,p){p&&(this._options=p);const w=this._properties.properties;if(h)for(const T in h){const I=h[T];if(T.endsWith("-transition")){const L=T.slice(0,-11);w[L]&&this.setTransition(L,I)}else w.hasOwnProperty(T)&&this.setValue(T,I)}}getTransition(h){return cr(this._values[h].transition)}setTransition(h,p){this._values.hasOwnProperty(h)||(this._values[h]=new Zw(this._values[h].property)),this._values[h].transition=cr(p)||void 0}serialize(){const h={};for(const p of Object.keys(this._values)){const w=this.getValue(p);w!==void 0&&(h[p]=w);const T=this.getTransition(p);T!==void 0&&(h[`${p}-transition`]=T)}return h}transitioned(h,p){const w=new fN(this._properties);for(const T of Object.keys(this._values))w._values[T]=this._values[T].transitioned(h,p._values[T]);return w}untransitioned(){const h=new fN(this._properties);for(const p of Object.keys(this._values))h._values[p]=this._values[p].untransitioned();return h}isIndoorDependent(){return this._isIndoorDependent}}class wb{constructor(h,p,w,T,I){const L=T.delay||0,$=T.duration||0;I=I||0,this.property=h,this.value=p,this.begin=I+L,this.end=this.begin+$,h.specification.transition&&(T.delay||T.duration)&&(this.prior=w)}possiblyEvaluate(h,p,w){const T=h.now||0,I=this.value.possiblyEvaluate(h,p,w),L=this.prior;if(L){if(T>this.end)return this.prior=null,I;if(this.value.isDataDriven())return this.prior=null,I;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 Xw(v){return v instanceof Number||v instanceof String||v instanceof Boolean?v.valueOf():v}function jb(v){if(Array.isArray(v))return v.map(jb);if(v instanceof Object&&!(v instanceof Number||v instanceof String||v instanceof Boolean)){const h={};for(const p in v)h[p]=jb(v[p]);return h}return Xw(v)}function Qw(v){if(v===!0||v===!1)return!0;if(!Array.isArray(v)||v.length===0)return!1;switch(v[0]){case"has":return v.length>=2&&v[1]!=="$id"&&v[1]!=="$type";case"in":return v.length>=3&&(typeof v[1]!="string"||Array.isArray(v[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return v.length!==3||Array.isArray(v[1])||Array.isArray(v[2]);case"any":case"all":for(const h of v.slice(1))if(!Qw(h)&&typeof h!="boolean")return!1;return!0;default:return!0}}function xN(v,h="",p=null,w="fill"){if(v==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};Qw(v)||(v=yN(v));const T=v;let I=!0;try{I=function(re){if(!Bv(re))return re;let oe=jb(re);return z4(oe),oe=F4(oe),oe}(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 L=null,$=null;if(w!=="background"&&w!=="sky"&&w!=="slot"){$=as[`filter_${w}`];const re=Yp(I,$,h,p);if(re.result==="error")throw new Error(re.value.map(oe=>`${oe.key}: ${oe.message}`).join(", "));L=(oe,le,ge)=>re.value.evaluate(oe,le,{},ge)}let V=null,X=null;if(I!==T){const re=Yp(T,$,h,p);if(re.result==="error")throw new Error(re.value.map(oe=>`${oe.key}: ${oe.message}`).join(", "));V=(oe,le,ge,_e,Te)=>re.value.evaluate(oe,le,{},ge,void 0,void 0,_e,Te),X=!ay(re.value.expression)}return{filter:L,dynamicFilter:V||void 0,needGeometry:AM(I),needFeature:!!X}}function F4(v){if(!Array.isArray(v))return v;const h=function(p){if(B4.has(p[0])){for(let w=1;wF4(p))}function z4(v){let h=!1;const p=[];if(v[0]==="case"){for(let w=1;w",">=","<","<=","to-boolean"]);function gN(v,h){return vh?1:0}function AM(v){if(!Array.isArray(v))return!1;if(v[0]==="within"||v[0]==="distance")return!0;for(let h=1;h"||h==="<="||h===">="?Y(v[1],v[2],h):h==="any"?(p=v.slice(1),["any"].concat(p.map(yN))):h==="all"?["all"].concat(v.slice(1).map(yN)):h==="none"?["all"].concat(v.slice(1).map(yN).map(Ue)):h==="in"?J(v[1],v.slice(2)):h==="!in"?Ue(J(v[1],v.slice(2))):h==="has"?be(v[1]):h!=="!has"||Ue(be(v[1]));var p}function Y(v,h,p){switch(v){case"$type":return[`filter-type-${p}`,h];case"$id":return[`filter-id-${p}`,h];default:return[`filter-${p}`,v,h]}}function J(v,h){if(h.length===0)return!1;switch(v){case"$type":return["filter-type-in",["literal",h]];case"$id":return["filter-id-in",["literal",h]];default:return h.length>200&&!h.some(p=>typeof p!=typeof h[0])?["filter-in-large",v,["literal",h.sort(gN)]]:["filter-in-small",v,["literal",h]]}}function be(v){switch(v){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",v]}}function Ue(v){return["!",v]}const Je="";function yt(v,h){return h?`${v}${Je}${h}`:v}function ns(v){const h=v.indexOf(Je);return h>=0?v.slice(h+1):""}let ur;const Hr=()=>ur||(ur=new Io({"icon-size":new gr(as.layout_symbol["icon-size"]),"icon-image":new gr(as.layout_symbol["icon-image"]),"icon-rotate":new gr(as.layout_symbol["icon-rotate"]),"icon-offset":new gr(as.layout_symbol["icon-offset"]),"text-size":new gr(as.layout_symbol["text-size"]),"text-rotate":new gr(as.layout_symbol["text-rotate"]),"text-offset":new gr(as.layout_symbol["text-offset"])}));let Ln;const La=()=>Ln||(Ln=new Io({"icon-opacity":new gr(as.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new gr(as.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new gr(as.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new gr(as.paint_symbol["text-emissive-strength"]),"icon-color":new gr(as.paint_symbol["icon-color"]),"icon-halo-color":new gr(as.paint_symbol["icon-halo-color"]),"icon-halo-width":new gr(as.paint_symbol["icon-halo-width"]),"icon-halo-blur":new gr(as.paint_symbol["icon-halo-blur"]),"icon-translate":new gr(as.paint_symbol["icon-translate"]),"text-opacity":new gr(as.paint_symbol["text-opacity"]),"text-occlusion-opacity":new gr(as.paint_symbol["text-occlusion-opacity"]),"text-color":new gr(as.paint_symbol["text-color"],{runtimeType:bh,getOverride:v=>v.textColor,hasOverride:v=>!!v.textColor}),"text-halo-color":new gr(as.paint_symbol["text-halo-color"]),"text-halo-width":new gr(as.paint_symbol["text-halo-width"]),"text-halo-blur":new gr(as.paint_symbol["text-halo-blur"]),"text-translate":new gr(as.paint_symbol["text-translate"]),"symbol-z-offset":new gr(as.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"})}));class ro{constructor(h,p,w,T,I,L){this._conditionSpec=h,this._propertiesSpec=w;const $=Yp(h,as.appearance.condition);if($.result==="success"&&(this.condition=$.value),this.name=p,w){this.layoutProperties=new Id(Hr()),this.unevaluatedLayout=new pN(Hr(),T,I,L),this.paintProperties=new Id(La()),this.unevaluatedPaint=new pN(La(),T,I,"");for(const V in w)V in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(V,w[V]):V in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(V,w[V])}}isActive(h){return!(this.condition||!h.isHidden||this.name!=="hidden")||this.condition.evaluate(h.globals,h.feature,h.featureState,h.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(h){return this.layoutProperties.get(h)}getPaintProperty(h){return this.paintProperties.get(h)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(h){return this.unevaluatedLayout._values[h]}getUnevaluatedPaintProperty(h){return this.unevaluatedPaint._values[h]}recalculate(h,p,w){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(h,void 0,p,w)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(h,void 0,p,""))}serialize(){const h={};h.condition=this.condition.expression.serialize(),this.name&&(h.name=this.name);const p=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},w=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},T=Object.assign({},p,w);return Object.keys(T).length>0&&(h.properties=T),h}hasIconLayoutProperties(){const h=this.hasLayoutProperty("icon-image"),p=this.hasLayoutProperty("icon-size"),w=this.hasLayoutProperty("icon-offset"),T=this.hasLayoutProperty("icon-rotate");return h||p||w||T}hasTextLayoutProperties(){const h=this.hasLayoutProperty("text-size"),p=this.hasLayoutProperty("text-offset"),w=this.hasLayoutProperty("text-rotate");return h||p||w}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(h=>!h.endsWith("-use-theme")).some(h=>(h.startsWith("icon-")||h==="symbol-z-offset")&&this.hasPaintProperty(h))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(h=>!h.endsWith("-use-theme")).some(h=>(h.startsWith("text-")||h==="symbol-z-offset")&&this.hasPaintProperty(h))}hasLayoutProperty(h){return this.unevaluatedLayout&&this.unevaluatedLayout._values[h].value!==void 0}hasPaintProperty(h){return this.unevaluatedPaint&&this.unevaluatedPaint._values[h].value!==void 0}}const ga="-transition",oc=new Set(["fill","line","background","hillshade","raster"]);class no extends xf{constructor(h,p,w,T,I,L){if(super(),this.id=h.id,this.fqid=yt(this.id,w),this.type=h.type,this.scope=w,this.lut=T,this.options=I,this.iconImageUseTheme=L,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},h.type!=="custom"){if(this.metadata=h.metadata,this.minzoom=h.minzoom,this.maxzoom=h.maxzoom,h.type&&h.type!=="background"&&h.type!=="sky"&&h.type!=="slot"){this.source=h.source,this.sourceLayer=h["source-layer"],this.filter=h.filter;const $=Yp(this.filter,as[`filter_${h.type}`]);$.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...$.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||$.value.isIndoorDependent)}if(h.slot&&(this.slot=h.slot),h.appearances&&this.setAppearances(h.appearances),p.layout&&(this._unevaluatedLayout=new pN(p.layout,this.scope,I,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),p.paint){this._transitionablePaint=new mN(p.paint,this.scope,I);for(const $ in h.paint)this.setPaintProperty($,h.paint[$]);for(const $ in h.layout)this.setLayoutProperty($,h.layout[$]);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 Id(p.paint)}}}onAdd(h){}onRemove(h){}isDraped(h){return!this.is3D(!0)&&oc.has(this.type)}getLayoutProperty(h){return h==="visibility"?this.visibility:this._unevaluatedLayout.getValue(h)}setLayoutProperty(h,p){if(this.type==="custom"&&h==="visibility")return void(this.visibility=p);const w=this._unevaluatedLayout;w._properties.properties[h]&&(w.setValue(h,p),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...w.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||w.isIndoorDependent(),h==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(h){this.appearances=[],h.forEach(p=>{this.appearances.push(new ro(p.condition,p.name,p.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(h){return h.endsWith(ga)?this._transitionablePaint.getTransition(h.slice(0,-11)):this._transitionablePaint.getValue(h)}isPaintProperty(h){return!!this._transitionablePaint._properties.properties[h]}setPaintProperty(h,p){const w=this._transitionablePaint,T=w._properties.properties;if(h.endsWith(ga)){const oe=h.slice(0,-11);return T[oe]&&w.setTransition(oe,p||void 0),!1}if(!T[h])return!1;const I=w._values[h],L=I.value.isDataDriven(),$=I.value;w.setValue(h,p),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...w.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||w.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(h);const V=w._values[h].value,X=V.isDataDriven(),re=h.endsWith("pattern")||h==="line-dasharray";return X||L||re||this._handleOverridablePaintPropertyUpdate(h,$,V)}_handleSpecialPaintPropertyUpdate(h){}getProgramIds(){return null}getDefaultProgramParams(h,p,w){return null}_handleOverridablePaintPropertyUpdate(h,p,w){return!1}isHidden(h){return!!(this.minzoom&&h=this.maxzoom)||this.visibility==="none"}updateTransitions(h){this._transitioningPaint=this._transitionablePaint.transitioned(h,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(h,p){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(h,void 0,p,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(h,void 0,p)}serialize(){const h={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&&(h.appearances=this.appearances.map(p=>p.serialize())),us(h,(p,w)=>!(p===void 0||w==="layout"&&!Object.keys(p).length||w==="paint"&&!Object.keys(p).length))}is3D(h){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 h in this.paint._values){const p=this.paint.get(h);if(p instanceof zv&&wf(p.property.specification)&&(p.value.kind==="source"||p.value.kind==="composite")&&p.value.isStateDependent)return!0}for(const h of this.appearances)if(!iy(h.condition.expression))return!0;return!1}compileFilter(h){this._filterCompiled||(this._featureFilter=xN(this.filter,this.scope,h),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(h){this._stats&&(h.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(h,p,w){return{}}queryRadius(h){}queryIntersectsFeature(h,p,w,T,I,L,$,V,X,re){}}const eh={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Cf{constructor(h,p){this._structArray=h,this._pos1=p*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Fr=new ArrayBuffer(0);class Us{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(h,p){return h._trim(),p&&h.arrayBuffer&&p.add(h.arrayBuffer),{length:h.length,arrayBuffer:h.arrayBuffer}}static deserialize(h){const p=Object.create(this.prototype);return p.arrayBuffer=h.arrayBuffer,p.length=h.length,h.arrayBuffer?p.capacity=h.arrayBuffer.byteLength/p.bytesPerElement:(p.capacity=0,p.arrayBuffer=Fr),p._refreshViews(),p}_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(h){this.reserve(h),this.length=h}reserve(h){if(h>this.capacity){this._reallocCount++,this.capacity=Math.max(h,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const p=this.uint8;this._refreshViews(),p&&this.uint8.set(p)}}reserveForAdditional(h){this.reserve(this.length+h)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...h){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...h){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 rr(v,h=1){let p=0,w=0;return{members:v.map(T=>{const I=eh[T.type].BYTES_PER_ELEMENT,L=p=Na(p,Math.max(h,I)),$=T.components||1;return w=Math.max(w,I),p+=I*$,{name:T.name,type:T.type,components:$,offset:L}}),size:Na(p,Math.max(w,h)),alignment:h}}function Na(v,h){return Math.ceil(v/h)*h}class Ra extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h,p){const w=this.length;return this.resize(w+1),this.emplace(w,h,p)}emplace(h,p,w){const T=2*h;return this.int16[T+0]=p,this.int16[T+1]=w,h}}Ra.prototype.bytesPerElement=4,Wr(Ra,"StructArrayLayout2i4");class Ai extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h,p,w){const T=this.length;return this.resize(T+1),this.emplace(T,h,p,w)}emplace(h,p,w,T){const I=3*h;return this.int16[I+0]=p,this.int16[I+1]=w,this.int16[I+2]=T,h}}Ai.prototype.bytesPerElement=6,Wr(Ai,"StructArrayLayout3i6");class Ja extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(h,p,w,T){const I=this.length;return this.resize(I+1),this.emplace(I,h,p,w,T)}emplace(h,p,w,T,I){const L=4*h;return this.int16[L+0]=p,this.int16[L+1]=w,this.uint16[L+2]=T,this.uint16[L+3]=I,h}}Ja.prototype.bytesPerElement=8,Wr(Ja,"StructArrayLayout2i2ui8");class eo extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h){const p=this.length;return this.resize(p+1),this.emplace(p,h)}emplace(h,p){return this.float32[1*h+0]=p,h}}eo.prototype.bytesPerElement=4,Wr(eo,"StructArrayLayout1f4");class Pd extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w){const T=this.length;return this.resize(T+1),this.emplace(T,h,p,w)}emplace(h,p,w,T){const I=4*h,L=2*h;return this.int16[I+0]=p,this.int16[I+1]=w,this.float32[L+1]=T,h}}Pd.prototype.bytesPerElement=8,Wr(Pd,"StructArrayLayout2i1f8");class Qo extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h,p,w){const T=this.length;return this.resize(T+1),this.emplace(T,h,p,w)}emplace(h,p,w,T){const I=4*h;return this.int16[I+0]=p,this.int16[I+1]=w,this.int16[I+2]=T,h}}Qo.prototype.bytesPerElement=8,Wr(Qo,"StructArrayLayout3i8");class Vx extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h,p,w,T){const I=this.length;return this.resize(I+1),this.emplace(I,h,p,w,T)}emplace(h,p,w,T,I){const L=4*h;return this.int16[L+0]=p,this.int16[L+1]=w,this.int16[L+2]=T,this.int16[L+3]=I,h}}Vx.prototype.bytesPerElement=8,Wr(Vx,"StructArrayLayout4i8");class $4 extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I){const L=this.length;return this.resize(L+1),this.emplace(L,h,p,w,T,I)}emplace(h,p,w,T,I,L){const $=5*h;return this.int16[$+0]=p,this.int16[$+1]=w,this.int16[$+2]=T,this.int16[$+3]=I,this.int16[$+4]=L,h}}$4.prototype.bytesPerElement=10,Wr($4,"StructArrayLayout5i10");class U4 extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L,$){const V=this.length;return this.resize(V+1),this.emplace(V,h,p,w,T,I,L,$)}emplace(h,p,w,T,I,L,$,V){const X=6*h,re=12*h,oe=3*h;return this.int16[X+0]=p,this.int16[X+1]=w,this.uint8[re+4]=T,this.uint8[re+5]=I,this.uint8[re+6]=L,this.uint8[re+7]=$,this.float32[oe+2]=V,h}}U4.prototype.bytesPerElement=12,Wr(U4,"StructArrayLayout2i4ub1f12");class Hx extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w){const T=this.length;return this.resize(T+1),this.emplace(T,h,p,w)}emplace(h,p,w,T){const I=3*h;return this.float32[I+0]=p,this.float32[I+1]=w,this.float32[I+2]=T,h}}Hx.prototype.bytesPerElement=12,Wr(Hx,"StructArrayLayout3f12");class fy extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I){const L=this.length;return this.resize(L+1),this.emplace(L,h,p,w,T,I)}emplace(h,p,w,T,I,L){const $=6*h,V=3*h;return this.uint16[$+0]=p,this.uint16[$+1]=w,this.uint16[$+2]=T,this.uint16[$+3]=I,this.float32[V+2]=L,h}}fy.prototype.bytesPerElement=12,Wr(fy,"StructArrayLayout4ui1f12");class vN extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(h,p,w,T){const I=this.length;return this.resize(I+1),this.emplace(I,h,p,w,T)}emplace(h,p,w,T,I){const L=4*h;return this.uint16[L+0]=p,this.uint16[L+1]=w,this.uint16[L+2]=T,this.uint16[L+3]=I,h}}vN.prototype.bytesPerElement=8,Wr(vN,"StructArrayLayout4ui8");class MM extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L){const $=this.length;return this.resize($+1),this.emplace($,h,p,w,T,I,L)}emplace(h,p,w,T,I,L,$){const V=6*h;return this.int16[V+0]=p,this.int16[V+1]=w,this.int16[V+2]=T,this.int16[V+3]=I,this.int16[V+4]=L,this.int16[V+5]=$,h}}MM.prototype.bytesPerElement=12,Wr(MM,"StructArrayLayout6i12");class wD extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L,$,V,X,re,oe,le){const ge=this.length;return this.resize(ge+1),this.emplace(ge,h,p,w,T,I,L,$,V,X,re,oe,le)}emplace(h,p,w,T,I,L,$,V,X,re,oe,le,ge){const _e=12*h;return this.int16[_e+0]=p,this.int16[_e+1]=w,this.int16[_e+2]=T,this.int16[_e+3]=I,this.uint16[_e+4]=L,this.uint16[_e+5]=$,this.uint16[_e+6]=V,this.uint16[_e+7]=X,this.int16[_e+8]=re,this.int16[_e+9]=oe,this.int16[_e+10]=le,this.int16[_e+11]=ge,h}}wD.prototype.bytesPerElement=24,Wr(wD,"StructArrayLayout4i4ui4i24");class jD extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L){const $=this.length;return this.resize($+1),this.emplace($,h,p,w,T,I,L)}emplace(h,p,w,T,I,L,$){const V=10*h,X=5*h;return this.int16[V+0]=p,this.int16[V+1]=w,this.int16[V+2]=T,this.float32[X+2]=I,this.float32[X+3]=L,this.float32[X+4]=$,h}}jD.prototype.bytesPerElement=20,Wr(jD,"StructArrayLayout3i3f20");class $v extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T){const I=this.length;return this.resize(I+1),this.emplace(I,h,p,w,T)}emplace(h,p,w,T,I){const L=4*h;return this.float32[L+0]=p,this.float32[L+1]=w,this.float32[L+2]=T,this.float32[L+3]=I,h}}$v.prototype.bytesPerElement=16,Wr($v,"StructArrayLayout4f16");class q4 extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(h){const p=this.length;return this.resize(p+1),this.emplace(p,h)}emplace(h,p){return this.uint32[1*h+0]=p,h}}q4.prototype.bytesPerElement=4,Wr(q4,"StructArrayLayout1ul4");class Gx extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(h,p){const w=this.length;return this.resize(w+1),this.emplace(w,h,p)}emplace(h,p,w){const T=2*h;return this.uint16[T+0]=p,this.uint16[T+1]=w,h}}Gx.prototype.bytesPerElement=4,Wr(Gx,"StructArrayLayout2ui4");class IM extends Us{_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(h,p,w,T,I,L,$,V,X,re,oe,le,ge){const _e=this.length;return this.resize(_e+1),this.emplace(_e,h,p,w,T,I,L,$,V,X,re,oe,le,ge)}emplace(h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e){const Te=20*h,Fe=10*h;return this.int16[Te+0]=p,this.int16[Te+1]=w,this.int16[Te+2]=T,this.int16[Te+3]=I,this.int16[Te+4]=L,this.float32[Fe+3]=$,this.float32[Fe+4]=V,this.float32[Fe+5]=X,this.float32[Fe+6]=re,this.int16[Te+14]=oe,this.uint32[Fe+8]=le,this.uint16[Te+18]=ge,this.uint16[Te+19]=_e,h}}IM.prototype.bytesPerElement=40,Wr(IM,"StructArrayLayout5i4f1i1ul2ui40");class V4 extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L,$){const V=this.length;return this.resize(V+1),this.emplace(V,h,p,w,T,I,L,$)}emplace(h,p,w,T,I,L,$,V){const X=8*h;return this.int16[X+0]=p,this.int16[X+1]=w,this.int16[X+2]=T,this.int16[X+4]=I,this.int16[X+5]=L,this.int16[X+6]=$,this.int16[X+7]=V,h}}V4.prototype.bytesPerElement=16,Wr(V4,"StructArrayLayout3i2i2i16");class ND extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I){const L=this.length;return this.resize(L+1),this.emplace(L,h,p,w,T,I)}emplace(h,p,w,T,I,L){const $=4*h,V=8*h;return this.float32[$+0]=p,this.float32[$+1]=w,this.float32[$+2]=T,this.int16[V+6]=I,this.int16[V+7]=L,h}}ND.prototype.bytesPerElement=16,Wr(ND,"StructArrayLayout2f1f2i16");class H4 extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L){const $=this.length;return this.resize($+1),this.emplace($,h,p,w,T,I,L)}emplace(h,p,w,T,I,L,$){const V=20*h,X=5*h;return this.uint8[V+0]=p,this.uint8[V+1]=w,this.float32[X+1]=T,this.float32[X+2]=I,this.float32[X+3]=L,this.float32[X+4]=$,h}}H4.prototype.bytesPerElement=20,Wr(H4,"StructArrayLayout2ub4f20");class Gl extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(h,p,w){const T=this.length;return this.resize(T+1),this.emplace(T,h,p,w)}emplace(h,p,w,T){const I=3*h;return this.uint16[I+0]=p,this.uint16[I+1]=w,this.uint16[I+2]=T,h}}Gl.prototype.bytesPerElement=6,Wr(Gl,"StructArrayLayout3ui6");class PM extends Us{_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(h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot,st,mt,bt){const wt=this.length;return this.resize(wt+1),this.emplace(wt,h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot,st,mt,bt)}emplace(h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot,st,mt,bt,wt){const Gt=30*h,Ot=15*h,Ht=60*h;return this.int16[Gt+0]=p,this.int16[Gt+1]=w,this.int16[Gt+2]=T,this.float32[Ot+2]=I,this.float32[Ot+3]=L,this.uint16[Gt+8]=$,this.uint16[Gt+9]=V,this.uint32[Ot+5]=X,this.uint32[Ot+6]=re,this.uint32[Ot+7]=oe,this.uint16[Gt+16]=le,this.uint16[Gt+17]=ge,this.uint16[Gt+18]=_e,this.float32[Ot+10]=Te,this.float32[Ot+11]=Fe,this.uint8[Ht+48]=He,this.uint8[Ht+49]=ot,this.uint8[Ht+50]=st,this.uint32[Ot+13]=mt,this.int16[Gt+28]=bt,this.uint8[Ht+58]=wt,h}}PM.prototype.bytesPerElement=60,Wr(PM,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class kD extends Us{_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(h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot,st,mt,bt,wt,Gt,Ot,Ht,Bt,$t,Es,Os,Hs,Qs,Gs,hr){const Ss=this.length;return this.resize(Ss+1),this.emplace(Ss,h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot,st,mt,bt,wt,Gt,Ot,Ht,Bt,$t,Es,Os,Hs,Qs,Gs,hr)}emplace(h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot,st,mt,bt,wt,Gt,Ot,Ht,Bt,$t,Es,Os,Hs,Qs,Gs,hr,Ss){const Zs=20*h,tr=40*h,mr=80*h;return this.float32[Zs+0]=p,this.float32[Zs+1]=w,this.int16[tr+4]=T,this.int16[tr+5]=I,this.int16[tr+6]=L,this.int16[tr+7]=$,this.int16[tr+8]=V,this.int16[tr+9]=X,this.int16[tr+10]=re,this.int16[tr+11]=oe,this.int16[tr+12]=le,this.uint16[tr+13]=ge,this.uint16[tr+14]=_e,this.uint16[tr+15]=Te,this.uint16[tr+16]=Fe,this.uint16[tr+17]=He,this.uint16[tr+18]=ot,this.uint16[tr+19]=st,this.uint16[tr+20]=mt,this.uint16[tr+21]=bt,this.uint16[tr+22]=wt,this.uint16[tr+23]=Gt,this.uint16[tr+24]=Ot,this.uint16[tr+25]=Ht,this.uint16[tr+26]=Bt,this.uint16[tr+27]=$t,this.uint32[Zs+14]=Es,this.float32[Zs+15]=Os,this.float32[Zs+16]=Hs,this.float32[Zs+17]=Qs,this.float32[Zs+18]=Gs,this.uint8[mr+76]=hr,this.uint16[tr+39]=Ss,h}}kD.prototype.bytesPerElement=80,Wr(kD,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class LM extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L){const $=this.length;return this.resize($+1),this.emplace($,h,p,w,T,I,L)}emplace(h,p,w,T,I,L,$){const V=6*h;return this.float32[V+0]=p,this.float32[V+1]=w,this.float32[V+2]=T,this.float32[V+3]=I,this.float32[V+4]=L,this.float32[V+5]=$,h}}LM.prototype.bytesPerElement=24,Wr(LM,"StructArrayLayout6f24");class Jw extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I){const L=this.length;return this.resize(L+1),this.emplace(L,h,p,w,T,I)}emplace(h,p,w,T,I,L){const $=5*h;return this.float32[$+0]=p,this.float32[$+1]=w,this.float32[$+2]=T,this.float32[$+3]=I,this.float32[$+4]=L,h}}Jw.prototype.bytesPerElement=20,Wr(Jw,"StructArrayLayout5f20");class G4 extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L,$){const V=this.length;return this.resize(V+1),this.emplace(V,h,p,w,T,I,L,$)}emplace(h,p,w,T,I,L,$,V){const X=7*h;return this.float32[X+0]=p,this.float32[X+1]=w,this.float32[X+2]=T,this.float32[X+3]=I,this.float32[X+4]=L,this.float32[X+5]=$,this.float32[X+6]=V,h}}G4.prototype.bytesPerElement=28,Wr(G4,"StructArrayLayout7f28");class SD extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L,$,V,X,re,oe){const le=this.length;return this.resize(le+1),this.emplace(le,h,p,w,T,I,L,$,V,X,re,oe)}emplace(h,p,w,T,I,L,$,V,X,re,oe,le){const ge=11*h;return this.float32[ge+0]=p,this.float32[ge+1]=w,this.float32[ge+2]=T,this.float32[ge+3]=I,this.float32[ge+4]=L,this.float32[ge+5]=$,this.float32[ge+6]=V,this.float32[ge+7]=X,this.float32[ge+8]=re,this.float32[ge+9]=oe,this.float32[ge+10]=le,h}}SD.prototype.bytesPerElement=44,Wr(SD,"StructArrayLayout11f44");class CD extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L,$,V,X){const re=this.length;return this.resize(re+1),this.emplace(re,h,p,w,T,I,L,$,V,X)}emplace(h,p,w,T,I,L,$,V,X,re){const oe=9*h;return this.float32[oe+0]=p,this.float32[oe+1]=w,this.float32[oe+2]=T,this.float32[oe+3]=I,this.float32[oe+4]=L,this.float32[oe+5]=$,this.float32[oe+6]=V,this.float32[oe+7]=X,this.float32[oe+8]=re,h}}CD.prototype.bytesPerElement=36,Wr(CD,"StructArrayLayout9f36");class ej extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p){const w=this.length;return this.resize(w+1),this.emplace(w,h,p)}emplace(h,p,w){const T=2*h;return this.float32[T+0]=p,this.float32[T+1]=w,h}}ej.prototype.bytesPerElement=8,Wr(ej,"StructArrayLayout2f8");class TD extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(h,p,w,T){const I=this.length;return this.resize(I+1),this.emplace(I,h,p,w,T)}emplace(h,p,w,T,I){const L=6*h;return this.uint32[3*h+0]=p,this.uint16[L+2]=w,this.uint16[L+3]=T,this.uint16[L+4]=I,h}}TD.prototype.bytesPerElement=12,Wr(TD,"StructArrayLayout1ul3ui12");class tj extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(h){const p=this.length;return this.resize(p+1),this.emplace(p,h)}emplace(h,p){return this.uint16[1*h+0]=p,h}}tj.prototype.bytesPerElement=2,Wr(tj,"StructArrayLayout1ui2");class ED extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe){const He=this.length;return this.resize(He+1),this.emplace(He,h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe)}emplace(h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He){const ot=16*h;return this.float32[ot+0]=p,this.float32[ot+1]=w,this.float32[ot+2]=T,this.float32[ot+3]=I,this.float32[ot+4]=L,this.float32[ot+5]=$,this.float32[ot+6]=V,this.float32[ot+7]=X,this.float32[ot+8]=re,this.float32[ot+9]=oe,this.float32[ot+10]=le,this.float32[ot+11]=ge,this.float32[ot+12]=_e,this.float32[ot+13]=Te,this.float32[ot+14]=Fe,this.float32[ot+15]=He,h}}ED.prototype.bytesPerElement=64,Wr(ED,"StructArrayLayout16f64");class DM extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(h,p,w,T,I,L,$){const V=this.length;return this.resize(V+1),this.emplace(V,h,p,w,T,I,L,$)}emplace(h,p,w,T,I,L,$,V){const X=10*h,re=5*h;return this.uint16[X+0]=p,this.uint16[X+1]=w,this.uint16[X+2]=T,this.uint16[X+3]=I,this.float32[re+2]=L,this.float32[re+3]=$,this.float32[re+4]=V,h}}DM.prototype.bytesPerElement=20,Wr(DM,"StructArrayLayout4ui3f20");class RM extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(h){const p=this.length;return this.resize(p+1),this.emplace(p,h)}emplace(h,p){return this.int16[1*h+0]=p,h}}RM.prototype.bytesPerElement=2,Wr(RM,"StructArrayLayout1i2");class OM extends Us{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(h){const p=this.length;return this.resize(p+1),this.emplace(p,h)}emplace(h,p){return this.uint8[1*h+0]=p,h}}OM.prototype.bytesPerElement=1,Wr(OM,"StructArrayLayout1ub1");class h$ extends Cf{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]}}h$.prototype.size=40;class AD extends IM{get(h){return new h$(this,h)}}Wr(AD,"CollisionBoxArray");class m$ extends Cf{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(h){this._structArray.uint8[this._pos1+49]=h}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(h){this._structArray.uint8[this._pos1+50]=h}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(h){this._structArray.uint32[this._pos4+13]=h}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(h){this._structArray.uint8[this._pos1+58]=h}}m$.prototype.size=60;class f$ extends PM{get(h){return new m$(this,h)}}Wr(f$,"PlacedSymbolArray");class W4 extends Cf{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(h){this._structArray.uint32[this._pos4+14]=h}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(h){this._structArray.float32[this._pos4+18]=h}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}W4.prototype.size=80;class p$ extends kD{get(h){return new W4(this,h)}}Wr(p$,"SymbolInstanceArray");class x$ extends eo{getoffsetX(h){return this.float32[1*h+0]}}Wr(x$,"GlyphOffsetArray");class K4 extends Ra{getx(h){return this.int16[2*h+0]}gety(h){return this.int16[2*h+1]}}Wr(K4,"SymbolLineVertexArray");class g$ extends Cf{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]}}g$.prototype.size=12;class MD extends TD{get(h){return new g$(this,h)}}Wr(MD,"FeatureIndexArray");class y$ extends Gx{geta_centroid_pos0(h){return this.uint16[2*h+0]}geta_centroid_pos1(h){return this.uint16[2*h+1]}}Wr(y$,"FillExtrusionCentroidArray");class ID extends Cf{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]}}ID.prototype.size=6;class PD extends Ai{get(h){return new ID(this,h)}}Wr(PD,"FillExtrusionWallArray");const v$=rr([{name:"a_pos",components:2,type:"Int16"}],4),sve=rr([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),rve=rr([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class jo{constructor(h=[]){this.segments=h}_prepareSegment(h,p,w,T,I){let L=this.segments[this.segments.length-1];return h>jo.MAX_VERTEX_ARRAY_LENGTH&&Kr(`Max vertices per segment is ${jo.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${h}`),(!L||L.vertexLength+h>jo.MAX_VERTEX_ARRAY_LENGTH||L.sortKey!==T||I!==void 0&&L&&L.batchIndex!==void 0&&L.batchIndex!==I)&&(L={vertexOffset:p,primitiveOffset:w,vertexLength:0,primitiveLength:0},T!==void 0&&(L.sortKey=T),I!==void 0&&(L.batchIndex=I),this.segments.push(L)),L}prepareSegment(h,p,w,T,I){return this._prepareSegment(h,p.length,w.length,T,I)}get(){return this.segments}destroy(){for(const h of this.segments)for(const p in h.vaos)h.vaos[p].destroy()}static simpleSegment(h,p,w,T){return new jo([{vertexOffset:h,primitiveOffset:p,vertexLength:w,primitiveLength:T,vaos:{},sortKey:0}])}}function FM(v,h){return 256*(v=Ke(Math.floor(v),0,255))+Ke(Math.floor(h),0,255)}jo.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Wr(jo,"SegmentVector");const nve=rr([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),ave=rr([{name:"a_pattern_b",components:4,type:"Uint16"}]),ive=rr([{name:"a_dash",components:4,type:"Uint16"}]);class Y4{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(h,p,w,T){this.ids.push(LD(h)),this.positions.push(p,w,T)}eachPosition(h,p){const w=LD(h);let T=0,I=this.ids.length-1;for(;T>1;this.ids[L]>=w?I=L:T=L+1}for(;this.ids[T]===w;)p(this.positions[3*T],this.positions[3*T+1],this.positions[3*T+2]),T++}static serialize(h,p){const w=new Float64Array(h.ids),T=new Uint32Array(h.positions);return Z4(w,T,0,w.length-1),p&&(p.add(w.buffer),p.add(T.buffer)),{ids:w,positions:T}}static deserialize(h){const p=new Y4;let w;p.ids=h.ids,p.positions=h.positions;for(const T of p.ids)T!==w&&p.uniqueIds.push(T),w=T;return p.indexed=!0,p}}function LD(v){const h=+v;return Number.isSafeInteger(h)?h:md(String(v))}function Z4(v,h,p,w){for(;p>1];let I=p-1,L=w+1;for(;;){do I++;while(v[I]T);if(I>=L)break;Jp(v,I,L),Jp(h,3*I,3*L),Jp(h,3*I+1,3*L+1),Jp(h,3*I+2,3*L+2)}L-p`u_${I}`),this.type=w,this.context=T}setUniform(h,p,w,T,I){const L=T.constantOr(this.value);p.set(h,I,L instanceof Vr?L.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):L)}getBinding(h,p){return this.type==="color"?new lve(h):new Xc(h)}}class ie{constructor(h,p){this.uniformNames=p.map(w=>`u_${w}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(h,p){this.pixelRatio=h.pixelRatio||1,this.pattern=h.tl.concat(h.br),this.patternTransition=p?p.tl.concat(p.br):this.pattern}setUniform(h,p,w,T,I){let L=null;I!=="u_pattern"&&I!=="u_dash"||(L=this.pattern),I==="u_pattern_b"&&(L=this.patternTransition),I==="u_pixel_ratio"&&(L=this.pixelRatio),L&&p.set(h,I,L)}getBinding(h,p){return p==="u_pattern"||p==="u_pattern_b"||p==="u_dash"?new ove(h):new Xc(h)}}class pe{constructor(h,p,w,T){this.expression=h,this.type=w,this.maxValue=0,this.paintVertexAttributes=p.map(I=>({name:`a_${I}`,type:"Float32",components:w==="color"?2:1,offset:0})),this.paintVertexArray=new T}populatePaintArray(h,p,w,T,I,L,$,V){const X=this.paintVertexArray.length,re=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new ja(0,{brightness:L,worldview:V}),p,{},I,T,$):this.expression.kind==="constant"&&this.expression.value,oe=G(this.lutExpression,p,{},T,I,L,$,V);this.paintVertexArray.resize(h),this._setPaintValue(X,h,re,oe?null:this.context.lut)}updatePaintArray(h,p,w,T,I,L,$,V){const X=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:$,worldview:V},w,T,void 0,I):this.expression.kind==="constant"&&this.expression.value,re=G(this.lutExpression,w,T,I,void 0,$,void 0,V);this._setPaintValue(h,p,X,re?null:this.context.lut)}_setPaintValue(h,p,w,T){if(this.type==="color"){const I=H(w.toPremultipliedRenderColor(T));for(let L=h;L`u_${$}_t`),this.type=w,this.useIntegerZoom=T,this.context=I,this.maxValue=0,this.paintVertexAttributes=p.map($=>({name:`a_${$}`,type:"Float32",components:w==="color"?4:2,offset:0})),this.paintVertexArray=new L}populatePaintArray(h,p,w,T,I,L,$,V){const X=this.expression.evaluate(new ja(this.context.zoom,{brightness:L,worldview:V}),p,{},I,T,$),re=this.expression.evaluate(new ja(this.context.zoom+1,{brightness:L,worldview:V}),p,{},I,T,$),oe=G(this.lutExpression,p,{},T,I,L,$,V),le=this.paintVertexArray.length;this.paintVertexArray.resize(h),this._setPaintValue(le,h,X,re,oe?null:this.context.lut)}updatePaintArray(h,p,w,T,I,L,$,V){const X=this.expression.evaluate({zoom:this.context.zoom,brightness:$,worldview:V},w,T,void 0,I),re=this.expression.evaluate({zoom:this.context.zoom+1,brightness:$,worldview:V},w,T,void 0,I),oe=G(this.lutExpression,w,T,I,void 0,$,void 0,V);this._setPaintValue(h,p,X,re,oe?null:this.context.lut)}_setPaintValue(h,p,w,T,I){if(this.type==="color"){const L=H(w.toPremultipliedRenderColor(I)),$=H(T.toPremultipliedRenderColor(I));for(let V=h;V!0){this.binders={},this._buffers=[],this.context=p;const T=[],I=h;for(const L in h.paint._values){const $=I.paint.get(L);if(L.endsWith("-use-theme")||!w(L)||!($ instanceof zv&&wf($.property.specification)))continue;const V=Ye(L,h.type),X=$.value,re=$.property.specification.type,oe=!!$.property.useIntegerZoom,le=L==="line-dasharray"||L.endsWith("pattern"),ge=I.paint.get(`${L}-use-theme`),_e=L==="line-dasharray"&&I.layout.get("line-cap").value.kind!=="constant"||ge&&ge.value.kind!=="constant";if(X.kind!=="constant"||_e)if(X.kind==="source"||_e||le){const Te=jt(L,re,"source");this.binders[L]=le?new De(X,V,re,Te,h.id):new pe(X,V,re,Te),T.push(`/a_${L}`)}else{const Te=jt(L,re,"composite");this.binders[L]=new ye(X,V,re,oe,p,Te),T.push(`/z_${L}`)}else this.binders[L]=le?new ie(X.value,V):new ee(X.value,V,re,p),T.push(`/u_${L}`);ge&&(this.binders[L].lutExpression=ge.value)}this.cacheKey=T.sort().join("")}getMaxValue(h){const p=this.binders[h];return p instanceof pe||p instanceof ye?p.maxValue:0}populatePaintArrays(h,p,w,T,I,L,$,V){for(const X in this.binders){const re=this.binders[X];re.context=this.context,(re instanceof pe||re instanceof ye||re instanceof De)&&re.populatePaintArray(h,p,w,T,I,L,$,V)}}setConstantPatternPositions(h,p){for(const w in this.binders){const T=this.binders[w];T instanceof ie&&T.setConstantPatternPositions(h,p)}}getPatternTransitionVertexBuffer(h){const p=this.binders[h];return p instanceof De?p.paintTransitionVertexBuffer:null}updatePaintArrays(h,p,w,T,I,L,$,V,X,re){let oe=!1;const le=Object.keys(h),ge=le.length!==0&&!V,_e=ge?le:p.uniqueIds;this.context.lut=I.lut;for(const Te in this.binders){const Fe=this.binders[Te];if(Fe.context=this.context,(Fe instanceof pe||Fe instanceof ye||Fe instanceof De)&&Fe.expression&&Fe.expression.kind&&Fe.expression.kind!=="constant"&&(Fe.expression.isStateDependent===!0||Fe.expression.isLightConstant===!1)){const He=I.paint.get(Te);Fe.expression=He.value;for(const ot of _e){const st=h[ot.toString()];p.eachPosition(ot,(mt,bt,wt)=>{const Gt=T.feature(mt);Fe.updatePaintArray(bt,wt,Gt,st,L,$,X,re)})}if(!ge)for(const ot of w.uniqueIds){const st=h[ot.toString()];w.eachPosition(ot,(mt,bt,wt)=>{const Gt=T.feature(mt);Fe.updatePaintArray(bt,wt,Gt,st,L,$,X,re)})}oe=!0}}return oe}defines(){const h=[];for(const p in this.binders){const w=this.binders[p];(w instanceof ee||w instanceof ie)&&h.push(...w.uniformNames.map(T=>`#define HAS_UNIFORM_${T}`))}return h}getPaintVertexBuffers(){return this._buffers}getUniforms(h){const p=[];for(const w in this.binders){const T=this.binders[w];if(T instanceof ee||T instanceof ie||T instanceof ye)for(const I of T.uniformNames)p.push({name:I,property:w,binding:T.getBinding(h,I)})}return p}setUniforms(h,p,w,T,I){for(const{name:L,property:$,binding:V}of w)this.binders[$].setUniform(h,V,I,T.get($),L)}updatePaintBuffers(){this._buffers=[];for(const h in this.binders){const p=this.binders[h];(p instanceof pe||p instanceof ye||p instanceof De)&&p.paintVertexBuffer&&this._buffers.push(p.paintVertexBuffer),p instanceof De&&p.paintTransitionVertexBuffer&&this._buffers.push(p.paintTransitionVertexBuffer)}}upload(h){for(const p in this.binders){const w=this.binders[p];(w instanceof pe||w instanceof ye||w instanceof De)&&w.upload(h)}this.updatePaintBuffers()}destroy(){for(const h in this.binders){const p=this.binders[h];(p instanceof pe||p instanceof ye||p instanceof De)&&p.destroy()}}}class Be{constructor(h,p,w=()=>!0){this.programConfigurations={};for(const T of h)this.programConfigurations[T.id]=new Ae(T,p,w);this.needsUpload=!1,this._featureMap=new Y4,this._featureMapWithoutIds=new Y4,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(h,p,w,T,I,L,$,V,X){for(const re in this.programConfigurations)this.programConfigurations[re].populatePaintArrays(h,p,T,I,L,$,V,X);p.id!==void 0?this._featureMap.add(p.id,w,this._bufferOffset,h):(this._featureMapWithoutIds.add(this._idlessCounter,w,this._bufferOffset,h),this._idlessCounter+=1),this._bufferOffset=h,this.needsUpload=!0}updatePaintArrays(h,p,w,T,I,L,$,V){for(const X of w)this.needsUpload=this.programConfigurations[X.id].updatePaintArrays(h,this._featureMap,this._featureMapWithoutIds,p,X,T,I,L,$||0,V)||this.needsUpload}get(h){return this.programConfigurations[h]}upload(h){if(this.needsUpload){for(const p in this.programConfigurations)this.programConfigurations[p].upload(h);this.needsUpload=!1}}destroy(){for(const h in this.programConfigurations)this.programConfigurations[h].destroy()}}const tt={"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 Ye(v,h){return tt[v]||[v.replace(`${h}-`,"").replace(/-/g,"_")]}const ut={"line-pattern":{source:fy,composite:fy},"fill-pattern":{source:fy,composite:fy},"fill-extrusion-pattern":{source:fy,composite:fy},"line-dasharray":{source:vN,composite:vN}},dt={color:{source:ej,composite:$v},number:{source:eo,composite:ej}};function jt(v,h,p){const w=ut[v];return w&&w[p]||dt[h][p]}Wr(ee,"ConstantBinder"),Wr(ie,"PatternConstantBinder"),Wr(pe,"SourceExpressionBinder"),Wr(De,"PatternCompositeBinder"),Wr(ye,"CompositeExpressionBinder"),Wr(Ae,"ProgramConfiguration",{omit:["_buffers"]}),Wr(Be,"ProgramConfigurationSet");const Tt=Lr/Math.PI/2,ft=64,Kt=[ft,32,16],Rt=-Tt,Wt=Tt;function Et(v,h,p,w=Tt){return p=ps(p),[v*Math.sin(p)*w,-h*w,v*Math.cos(p)*w]}function Lt(v,h,p){return Et(Math.cos(ps(v)),Math.sin(ps(v)),h,p)}const Vt=63710088e-1,ds=2*Math.PI*Vt;class Zt{constructor(h,p){if(isNaN(h)||isNaN(p))throw new Error(`Invalid LngLat object: (${h}, ${p})`);if(this.lng=+h,this.lat=+p,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Zt(Nt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(h){const p=Math.PI/180,w=this.lat*p,T=h.lat*p,I=Math.sin(w)*Math.sin(T)+Math.cos(w)*Math.cos(T)*Math.cos((h.lng-this.lng)*p);return Vt*Math.acos(Math.min(I,1))}toBounds(h=0){const p=360*h/40075017,w=p/Math.cos(Math.PI/180*this.lat);return new Is({lng:this.lng-w,lat:this.lat-p},{lng:this.lng+w,lat:this.lat+p})}toEcef(h){return Lt(this.lat,this.lng,Tt+h*Tt/Vt)}static convert(h){if(h instanceof Zt)return h;if(Array.isArray(h)&&(h.length===2||h.length===3))return new Zt(Number(h[0]),Number(h[1]));if(!Array.isArray(h)&&typeof h=="object"&&h!==null)return new Zt(Number("lng"in h?h.lng:h.lon),Number(h.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 Is{constructor(h,p){h&&(p?this.setSouthWest(h).setNorthEast(p):Array.isArray(h)&&h.length===4?this.setSouthWest([h[0],h[1]]).setNorthEast([h[2],h[3]]):this.setSouthWest(h[0]).setNorthEast(h[1]))}setNorthEast(h){return this._ne=h instanceof Zt?new Zt(h.lng,h.lat):Zt.convert(h),this}setSouthWest(h){return this._sw=h instanceof Zt?new Zt(h.lng,h.lat):Zt.convert(h),this}extend(h){const p=this._sw,w=this._ne;let T,I;if(h instanceof Zt)T=h,I=h;else{if(!(h instanceof Is))return Array.isArray(h)?h.length===4||h.every(Array.isArray)?this.extend(Is.convert(h)):this.extend(Zt.convert(h)):typeof h=="object"&&h!==null&&h.hasOwnProperty("lat")&&(h.hasOwnProperty("lon")||h.hasOwnProperty("lng"))?this.extend(Zt.convert(h)):this;if(T=h._sw,I=h._ne,!T||!I)return this}return p||w?(p.lng=Math.min(T.lng,p.lng),p.lat=Math.min(T.lat,p.lat),w.lng=Math.max(I.lng,w.lng),w.lat=Math.max(I.lat,w.lat)):(this._sw=new Zt(T.lng,T.lat),this._ne=new Zt(I.lng,I.lat)),this}getCenter(){return new Zt((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 Zt(this.getWest(),this.getNorth())}getSouthEast(){return new Zt(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(h){const{lng:p,lat:w}=Zt.convert(h);let T=this._sw.lng<=p&&p<=this._ne.lng;return this._sw.lng>this._ne.lng&&(T=this._sw.lng>=p&&p>=this._ne.lng),this._sw.lat<=w&&w<=this._ne.lat&&T}static convert(h){if(h)return h instanceof Is?h:new Is(h)}}function Ns(v){return ds*Math.cos(v*Math.PI/180)}function er(v){return(180+v)/360}function lr(v){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+v*Math.PI/360)))/360}function hs(v,h){return v/Ns(h)}function ss(v){return 360*v-180}function Ts(v){return 360/Math.PI*Math.atan(Math.exp((180-360*v)*Math.PI/180))-90}function Rs(v,h){return v*Ns(Ts(h))}const qs=85.051129;function Cr(v){return Math.cos(ps(Ke(v,-85.051129,qs)))}function br(v,h){const p=Ke(h,0,25.5),w=Math.pow(2,p);return Cr(v)*ds/(512*w)}function _r(v){return 1/Math.cos(v*Math.PI/180)}function nr(v,h=0){const p=Math.exp(Math.PI*(1-(v.y+h/Lr)/(1<=V?(gn(v,h,p,X,re,I,oe,$,V),gn(v,X,re,w,T,oe,L,$,V)):v.push(L)}function en(v,h,p){let w=v[0],T=w.x,I=w.y;h(w);const L=[w];for(let $=1;$v.x+1||wv.y+1)&&Kr("Geometry exceeds allowed extent, reduce your vector tile buffer size"),v}function zn(v,h,p){const w=v.loadGeometry(),T=v.extent,I=Lr/T;if(h&&p&&p.projection.isReprojectedInTileSpace){const L=1<{const ge=ss((h.x+le.x/T)/L),_e=Ts((h.y+le.y/T)/L),Te=re.project(ge,_e);le.x=(Te.x*$-V)*T,le.y=(Te.y*$-X)*T};for(let le=0;le=T||_e.y<0||_e.y>=T||(oe(_e),ge.push(_e));w[le]=ge}}for(const L of w)for(const $ of L)Oa($,I);return w}function Fa(v,h){return{type:v.type,id:v.id,properties:v.properties,geometry:h?zn(v):[]}}class ia{constructor(h,p,w,T,I){this.properties={},this.extent=w,this.type=0,this.id=void 0,this._pbf=h,this._geometry=-1,this._keys=T,this._values=I,h.readFields(ji,this,p)}loadGeometry(){const h=this._pbf;h.pos=this._geometry;const p=h.readVarint()+h.pos,w=[];let T,I=1,L=0,$=0,V=0;for(;h.pos>3}if(L--,I===1||I===2)$+=h.readSVarint(),V+=h.readSVarint(),I===1&&(T&&w.push(T),T=[]),T&&T.push(new gs($,V));else{if(I!==7)throw new Error(`unknown command ${I}`);T&&T.push(T[0].clone())}}return T&&w.push(T),w}bbox(){const h=this._pbf;h.pos=this._geometry;const p=h.readVarint()+h.pos;let w=1,T=0,I=0,L=0,$=1/0,V=-1/0,X=1/0,re=-1/0;for(;h.pos>3}if(T--,w===1||w===2)I+=h.readSVarint(),L+=h.readSVarint(),I<$&&($=I),I>V&&(V=I),Lre&&(re=L);else if(w!==7)throw new Error(`unknown command ${w}`)}return[$,X,V,re]}toGeoJSON(h,p,w){const T=this.extent*Math.pow(2,w),I=this.extent*h,L=this.extent*p,$=this.loadGeometry();function V(le){return[360*(le.x+I)/T-180,360/Math.PI*Math.atan(Math.exp((1-2*(le.y+L)/T)*Math.PI))-90]}function X(le){return le.map(V)}let re;if(this.type===1){const le=[];for(const _e of $)le.push(_e[0]);const ge=X(le);re=le.length===1?{type:"Point",coordinates:ge[0]}:{type:"MultiPoint",coordinates:ge}}else if(this.type===2){const le=$.map(X);re=le.length===1?{type:"LineString",coordinates:le[0]}:{type:"MultiLineString",coordinates:le}}else{if(this.type!==3)throw new Error("unknown feature type");{const le=function(_e){const Te=_e.length;if(Te<=1)return[_e];const Fe=[];let He,ot;for(let st=0;st=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[h];const p=this._pbf.readVarint()+this._pbf.pos;return new ia(this._pbf,p,this.extent,this._keys,this._values)}}function No(v,h,p){v===15?h.version=p.readVarint():v===1?h.name=p.readString():v===5?h.extent=p.readVarint():v===2?h._features.push(p.pos):v===3?h._keys.push(p.readString()):v===4&&h._values.push(function(w){let T=null;const I=w.readVarint()+w.pos;for(;w.pos>3;T=L===1?w.readString():L===2?w.readFloat():L===3?w.readDouble():L===4?w.readVarint64():L===5?w.readVarint():L===6?w.readSVarint():L===7?w.readBoolean():null}if(T==null)throw new Error("unknown feature value");return T}(p))}class Ii{constructor(h,p){this.layers=h.readFields(Ta,{},p)}}function Ta(v,h,p){if(v===3){const w=new ml(p,p.readVarint()+p.pos);w.length&&(h[w.name]=w)}}const Ea="3d_elevation_id",ko="level";class bl{constructor(){this._valid=!1}reset(h){return this.feature=h,this._valid=!0,this._geometry=h.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(h,p){return this._valid&&h(p(this._geometry)),this}require(h,p,w){return this.get(h,!0,p,w)}optional(h,p,w){return this.get(h,!1,p,w)}success(){return this._valid}get(h,p,w,T){const I=this.feature.properties.hasOwnProperty(h)?+this.feature.properties[h]:void 0;return this._valid&&I!==void 0&&!Number.isNaN(I)?w(T?T(I):I):p&&(this._valid=!1),this}}class Pi{constructor(h,p){this.featureFunc=h,this.vertexFunc=p}parseFeature(h,p,w){return this.featureFunc(h,p,w)}parseVertex(h,p,w){return this.vertexFunc(h,p,w)}}const ya=new Pi((v,h,p)=>v.reset(h).require(Ea,w=>{p.id=w}).optional("fixed_height_relative",w=>{p.constantHeight=w},fo.decodeRelativeHeight).geometry(w=>{p.bounds=w},nb).success(),(v,h,p)=>v.reset(h).require(Ea,w=>{p.id=w}).require("elevation_idx",w=>{p.idx=w}).require("extent",w=>{p.extent=w}).require("height_relative",w=>{p.height=w},fo.decodeRelativeHeight).geometry(w=>{p.position=w},fo.getPoint).success()),al=new Pi((v,h,p)=>v.reset(h).require(Ea,w=>{p.id=w}).optional("fixed_height",w=>{p.constantHeight=w},fo.decodeMetricHeight).geometry(w=>{p.bounds=w},nb).success(),(v,h,p)=>v.reset(h).require(Ea,w=>{p.id=w}).require("elevation_idx",w=>{p.idx=w}).require("extent",w=>{p.extent=w}).require("height",w=>{p.height=w},fo.decodeMetricHeight).geometry(w=>{p.position=w},fo.getPoint).success());class fo{static getPoint(h){return Jt(h[0][0].x,h[0][0].y)}static decodeRelativeHeight(h){return 1e-4*h*5}static decodeMetricHeight(h){return 1e-4*h}static getVersionSchema(h){return h?h==="1.0.1"?al:void 0:ya}static parse(h){const p=[],w=[],T=h.length,I=new bl;for(let L=0;L=0);if(I===0)return 0;I!==h.length&&(p=!1)}return p?2:1}function Qc(v,h){for(const p of v.projections){const w=Pc(h,v.points[0],p.axis);if(p.projection[1]w[1])return 0}return 1}function Jd(v,h){let p=0;const w=[0,0,0,0];for(let T=0;T=0&&p++;return p}class pp{constructor(h,p){this.points=h||new Array(8).fill([0,0,0]),this.planes=p||new Array(6).fill([0,0,0,0]),this.bounds=Xi.fromPoints(this.points),this.projections=[],this.frustumEdges=[We([],this.points[2],this.points[3]),We([],this.points[0],this.points[3]),We([],this.points[4],this.points[0]),We([],this.points[5],this.points[1]),We([],this.points[6],this.points[2]),We([],this.points[7],this.points[3])];for(const w of this.frustumEdges){const T=[0,-w[2],w[1]],I=[w[2],0,-w[0]];this.projections.push({axis:T,projection:Pc(this.points,this.points[0],T)}),this.projections.push({axis:I,projection:Pc(this.points,this.points[0],I)})}}static fromInvProjectionMatrix(h,p,w,T){const I=Math.pow(2,w),L=[[-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 re=vt([],X,h),oe=1/re[3]/p*I;return(le=re)[0]=(ge=re)[0]*(_e=[oe,oe,T?1/re[3]:oe,oe])[0],le[1]=ge[1]*_e[1],le[2]=ge[2]*_e[2],le[3]=ge[3]*_e[3],le;var le,ge,_e}),$=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(X=>{const re=Ve([],$e([],We([],L[X[0]],L[X[1]]),We([],L[X[2]],L[X[1]]))),oe=-Le(re,L[X[1]]);return re.concat(oe)}),V=[];for(let X=0;XX[1]||X[0]>V[1])return 0}return 1}containsPoint(h){for(const p of this.planes){const w=p[3];if(Le([p[0],p[1],p[2]],h)+w<0)return!1}return!0}}class Xi{static fromPoints(h){const p=[1/0,1/0,1/0],w=[-1/0,-1/0,-1/0];for(const T of h)fe(p,p,T),je(w,w,T);return new Xi(p,w)}static fromTileIdAndHeight(h,p,w){const T=1<h.max[p]||h.min[p]>this.max[p])return!1;return!0}intersectsAabbXY(h){return!(this.min[0]>h.max[0]||h.min[0]>this.max[0]||this.min[1]>h.max[1]||h.min[1]>this.max[1])}encapsulate(h){for(let p=0;p<3;p++)this.min[p]=Math.min(this.min[p],h.min[p]),this.max[p]=Math.max(this.max[p],h.max[p])}encapsulatePoint(h){for(let p=0;p<3;p++)this.min[p]=Math.min(this.min[p],h[p]),this.max[p]=Math.max(this.max[p],h[p])}closestPoint(h){return[Math.max(Math.min(this.max[0],h[0]),this.min[0]),Math.max(Math.min(this.max[1],h[1]),this.min[1]),Math.max(Math.min(this.max[2],h[2]),this.min[2])]}}Wr(Xi,"Aabb");class ex{constructor(h,p){this.feature=h,this.metersToTile=p,this.index=0}get(){const h=this.feature.vertices[this.index],p=this.feature.vertexProps[this.index].dir,w=p[1],T=-p[0],I=(h.extent+1)*this.metersToTile;return[new gs(Math.trunc(h.position[0]+w*I),Math.trunc(h.position[1]+T*I)),new gs(Math.trunc(h.position[0]-w*I),Math.trunc(h.position[1]-T*I))]}next(){this.index++}valid(){return this.index{return $.a0?xe(V,V,1/X):ae(V,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(h){if(this.edges.length===0)return;let p=0,w=Number.POSITIVE_INFINITY,T=0;const[I,L,$,V,X,re,oe]=this._tmpVec2;Ms(oe,h.x,h.y);const le=new lc(oe,null);for(let ge=0;ge0?or(V,$)/mt:0,wt=Ke(bt,0,1),Gt=Math.abs((bt-wt)*this.edgeProps[ge].len);Xs(X,oe,Fe),Ms(re,Te[1],-Te[0]);const Ot=Gt+Math.abs(or(X,re));Ot=0;--L){const $=this.edges[L].a,V=this.edges[L].b,{position:X,height:re,extent:oe}=this.vertices[$],{position:le,height:ge,extent:_e}=this.vertices[V],Te=this.vertexProps[$].dir,Fe=this.vertexProps[V].dir;if(ae(p,X[0]/h,X[1]/h,re),ae(w,le[0]/h,le[1]/h,ge),ae(T,Te[1],-Te[0],0),xe(T,T,oe),ae(I,Fe[1],-Fe[0],0),xe(I,I,_e),this.distSqLines(ne(p[0]+.5*T[0],p[1]+.5*T[1],p[2]+.5*T[2]),ne(w[0]-.5*I[0],w[1]-.5*I[1],w[2]-.5*I[2]),ne(p[0]-.5*T[0],p[1]-.5*T[1],p[2]-.5*T[2]),ne(w[0]+.5*I[0],w[1]+.5*I[1],w[2]+.5*I[2]))<=.0025000000000000005)continue;const He=this.vertices.length,ot=ts(ht(),X,le);this.vertices.push({position:js(ot,ot,.5),height:.5*(re+ge),extent:.5*(oe+_e)});const st=ts(ht(),Te,Fe);this.vertexProps.push({dir:Js(st,st)}),this.edges.splice(L,1),this.edgeProps.splice(L,1),this.edges.push({a:$,b:He}),this.edges.push({a:He,b:V});const mt=Xs(ht(),this.vertices[He].position,X),bt=$s(mt),wt={vec:mt,dir:js(ht(),mt,1/bt),len:bt};this.edgeProps.push(wt),this.edgeProps.push(wt)}}distSqLines(h,p,w,T){const I=me(Q(),p,h),L=me(Q(),T,w),$=me(Q(),h,w),V=Le(I,I),X=Le(I,L),re=Le(I,$),oe=Le(L,L),le=Le(L,$),ge=V*oe-X*X;if(ge===0)return Oe(ve(I,w,T,Le($,L)/Le(L,L)),h);const _e=(V*le-X*re)/ge;return Oe(ve(I,h,p,(X*le-re*oe)/ge),ve(L,w,T,_e))}}class To{static parseFrom(h,p){const w=fo.parse(h);if(!w)return[];let{vertices:T,features:I}=w;const L=1/nr(p);I.sort((re,oe)=>re.id-oe.id),T.sort((re,oe)=>re.id-oe.id||re.idx-oe.idx),T=T.filter((re,oe,le)=>oe===le.findIndex(ge=>ge.id===re.id&&ge.idx===re.idx));const $=new Array;let V=0;const X=T.length;for(const re of I){if(re.constantHeight){$.push(new tx(re.id,re.bounds,re.constantHeight));continue}for(;V!==X&&T[V].idT.id===w)}}class Po{constructor(h,p){this.zScale=1,this.xOffset=0,this.yOffset=0,h.equals(p)||(this.zScale=Math.pow(2,p.z-h.z),this.xOffset=(h.x*this.zScale-p.x)*Lr,this.yOffset=(h.y*this.zScale-p.y)*Lr)}constantElevation(h,p){if(h.constantHeight!=null)return this.computeBiasedHeight(h.constantHeight,p)}pointElevation(h,p,w){const T=this.constantElevation(p,w);return T??(h.x=h.x*this.zScale+this.xOffset,h.y=h.y*this.zScale+this.yOffset,this.computeBiasedHeight(p.pointElevation(h),w))}computeBiasedHeight(h,p){return p<=0?h:h+p*at(0,p,h>=0?h:Math.abs(.5*h))}}Wr(tx,"ElevationFeature");class ao{constructor(h){this.zoom=h.zoom,this.overscaling=h.overscaling,this.layers=h.layers,this.layerIds=this.layers.map(p=>p.fqid),this.index=h.index,this.hasPattern=!1,this.projection=h.projection,this.layoutVertexArray=new Ra,this.indexArray=new Gl,this.segments=new jo,this.programConfigurations=new Be(h.layers,{zoom:h.zoom,lut:h.lut}),this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new eo),this.worldview=h.worldview,this.hasAppearances=null}updateFootprints(h,p){}updateAppearances(h,p,w,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(h,p,w,T){const I=this.layers[0],L=[];let $=null;I.type==="circle"&&($=I.layout.get("circle-sort-key"));for(const{feature:X,id:re,index:oe,sourceLayerIndex:le}of h){const ge=this.layers[0]._featureFilter.needGeometry,_e=Fa(X,ge);if(!this.layers[0]._featureFilter.filter(new ja(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),_e,w))continue;const Te=$?$.evaluate(_e,{},w):void 0,Fe={id:re,properties:X.properties,type:X.type,sourceLayerIndex:le,index:oe,geometry:ge?_e.geometry:zn(X,w,T),patterns:{},sortKey:Te};L.push(Fe)}$&&L.sort((X,re)=>X.sortKey-re.sortKey);let V=null;T.projection.name==="globe"&&(this.globeExtVertexArray=new MM,V=T.projection);for(const X of L){const{geometry:re,index:oe,sourceLayerIndex:le}=X,ge=h[oe].feature;this.addFeature(X,re,oe,p.availableImages,w,V,p.brightness,p.elevationFeatures),p.featureIndex.insert(ge,re,oe,le,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(h,p,w,T,I,L,$){this.programConfigurations.updatePaintArrays(h,p,I,w,T,L,$,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(h){this.uploaded||(this.layoutVertexBuffer=h.createVertexBuffer(this.layoutVertexArray,v$.members),this.indexBuffer=h.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=h.createVertexBuffer(this.globeExtVertexArray,rve.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=h.createVertexBuffer(this.elevatedLayoutVertexArray,sve.members))),this.programConfigurations.upload(h),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(h,p,w,T,I,L,$,V){let X;this.elevationMode!=="none"&&(X=To.getElevationFeature(h,V));for(const re of p)for(const oe of re){const le=oe.x,ge=oe.y;if(le<0||le>=Lr||ge<0||ge>=Lr)continue;if(L){const Fe=L.projectTilePoint(le,ge,I),He=L.upVector(I,le,ge);this.addGlobeExtVertex(Fe,He),this.addGlobeExtVertex(Fe,He),this.addGlobeExtVertex(Fe,He),this.addGlobeExtVertex(Fe,He)}const _e=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,h.sortKey),Te=_e.vertexLength;if(this.addCircleVertex(le,ge,-1,-1),this.addCircleVertex(le,ge,1,-1),this.addCircleVertex(le,ge,1,1),this.addCircleVertex(le,ge,-1,1),this.elevationMode!=="none"){const Fe=X?X.pointElevation(new gs(le,ge)):0;this.hasElevation=this.hasElevation||Fe!==0;for(let He=0;He<4;He++)this.elevatedLayoutVertexArray.emplaceBack(Fe)}this.indexArray.emplaceBack(Te,Te+1,Te+2),this.indexArray.emplaceBack(Te,Te+2,Te+3),_e.vertexLength+=4,_e.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,h,w,{},T,I,$,void 0,this.worldview)}addCircleVertex(h,p,w,T){this.layoutVertexArray.emplaceBack(2*h+(w+1)/2,2*p+(T+1)/2)}addGlobeExtVertex(h,p){this.globeExtVertexArray.emplaceBack(h.x,h.y,h.z,p[0]*16384,p[1]*16384,p[2]*16384)}}function tc(v,h){for(let p=0;p1){if(Nb(v,h))return!0;for(let w=0;w1?p:p.sub(h)._mult(T)._add(h))}function _N(v,h){let p,w,T,I=!1;for(let L=0;Lh.y!=T.y>h.y&&h.x<(T.x-w.x)*(h.y-w.y)/(T.y-w.y)+w.x&&(I=!I)}return I}function Tf(v,h){let p=!1;for(let w=0,T=v.length-1;wh.y!=L.y>h.y&&h.x<(L.x-I.x)*(h.y-I.y)/(L.y-I.y)+I.x&&(p=!p)}return p}function kb(v,h,p,w,T){for(const L of v)if(h<=L.x&&p<=L.y&&w>=L.x&&T>=L.y)return!0;const I=[new gs(h,p),new gs(h,T),new gs(w,T),new gs(w,p)];if(v.length>2){for(const L of I)if(Tf(v,L))return!0}for(let L=0;LT.x&&h.x>T.x||v.yT.y&&h.y>T.y)return!1;const I=mn(v,h,p[0]);return I!==mn(v,h,p[1])||I!==mn(v,h,p[2])||I!==mn(v,h,p[3])}function Cb(v,h,p,w,T,I){let L=h.y-v.y,$=v.x-h.x;if(I=I||0){const V=L*L+$*$;if(V===0)return!0;const X=Math.sqrt(V);L/=X,$/=X}return!((p.x-v.x)*L+(p.y-v.y)*$-I<0||(w.x-v.x)*L+(w.y-v.y)*$-I<0||(T.x-v.x)*L+(T.y-v.y)*$-I<0)}function BM(v,h,p,w,T,I,L){return!(Cb(v,h,w,T,I,L)||Cb(h,p,w,T,I,L)||Cb(p,v,w,T,I,L)||Cb(w,T,v,h,p,L)||Cb(T,I,v,h,p,L)||Cb(I,w,v,h,p,L))}function wN(v,h,p){const w=h.paint.get(v).value;return w.kind==="constant"?w.value:p.programConfigurations.get(h.id).getMaxValue(v)}function b$(v){return Math.sqrt(v[0]*v[0]+v[1]*v[1])}function JIe(v,h,p,w,T){if(!h[0]&&!h[1])return v;const I=gs.convert(h)._mult(T);p==="viewport"&&I._rotate(-w);const L=[];for(let $=0;$>p&&h.y===this.y>>p}url(h,p){const w=function(I,L,$){const V=2**$,X=2*Math.PI*6378137,re=X*(I/V-.5),oe=X*(.5-(L+1)/V);return`${re},${oe},${re+X/V},${oe+X/V}`}(this.x,this.y,this.z),T=function(I,L,$){let V,X="";for(let re=I;re>0;re--)V=1<this.canonical.z?new qm(h,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new qm(h,this.wrap,h,this.canonical.x>>p,this.canonical.y>>p)}calculateScaledKey(h,p=!0){if(this.overscaledZ===h&&p)return this.key;if(h>this.canonical.z)return $M(this.wrap*+p,h,this.canonical.z,this.canonical.x,this.canonical.y);{const w=this.canonical.z-h;return $M(this.wrap*+p,h,h,this.canonical.x>>w,this.canonical.y>>w)}}isChildOf(h){if(h.wrap!==this.wrap)return!1;const p=this.canonical.z-h.canonical.z;return h.overscaledZ===0||h.overscaledZ>p&&h.canonical.y===this.canonical.y>>p}children(h){if(this.overscaledZ>=h)return[new qm(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const p=this.canonical.z+1,w=2*this.canonical.x,T=2*this.canonical.y;return[new qm(p,this.wrap,p,w,T),new qm(p,this.wrap,p,w+1,T),new qm(p,this.wrap,p,w,T+1),new qm(p,this.wrap,p,w+1,T+1)]}isLessThan(h){return this.wraph.wrap)&&(this.overscaledZh.overscaledZ)&&(this.canonical.xh.canonical.x)&&this.canonical.y{let h=v.canonical.x-1,p=v.wrap;return h<0&&(h=(1<{let h=v.canonical.x+1,p=v.wrap;return h===1<new qm(v.overscaledZ,v.wrap,v.canonical.z,v.canonical.x,(v.canonical.y===0?1<new qm(v.overscaledZ,v.wrap,v.canonical.z,v.canonical.x,v.canonical.y===(1<1?null:function(w,T,I,L){const $=Math.sin(I);return w*(Math.sin((1-L)*I)/$)+T*(Math.sin(L*I)/$)}(v.a[h],v.b[h],v.angle,Ke(p,0,1))+v.center[h]}function Tb(v){if(v.z<=1)return Fwt[v.z+2*v.y+v.x];const h=dve(j$(v));return Xi.fromPoints(h)}function nj(v,h,p){return xe(v,v,1-p),Ee(v,v,h,p)}function iPe(v,h){const p=aj(h.zoom);if(p===0)return Tb(v);const w=j$(v),T=dve(w),I=er(w.getWest())*h.worldSize,L=er(w.getEast())*h.worldSize,$=lr(w.getNorth())*h.worldSize,V=lr(w.getSouth())*h.worldSize,X=[I,$,0],re=[L,$,0],oe=[I,V,0],le=[L,V,0],ge=j([],h.globeMatrix);return Qe(X,X,ge),Qe(re,re,ge),Qe(oe,oe,ge),Qe(le,le,ge),T[0]=nj(T[0],oe,p),T[1]=nj(T[1],le,p),T[2]=nj(T[2],re,p),T[3]=nj(T[3],X,p),Xi.fromPoints(T)}function oPe(v,h,p){for(const w of v)Qe(w,w,h),xe(w,w,p)}function lPe(v,h,p,w){const T=h/v.worldSize,I=v.globeMatrix;if(p.z<=1){const Ht=Tb(p).getCorners();return oPe(Ht,I,T),Xi.fromPoints(Ht)}const L=j$(p,w),$=dve(L,Tt+w$(v._tileCoverLift));oPe($,I,T);const V=Number.MAX_VALUE,X=[-V,-V,-V],re=[V,V,V];if(L.contains(v.center)){for(const $t of $)fe(re,re,$t),je(X,X,$t);X[2]=0;const Ht=v.point,Bt=[Ht.x*T,Ht.y*T,0];return fe(re,re,Bt),je(X,X,Bt),new Xi(re,X)}if(v._tileCoverLift>0){for(const Ht of $)fe(re,re,Ht),je(X,X,Ht);return new Xi(re,X)}const oe=[I[12]*T,I[13]*T,I[14]*T],le=L.getCenter(),ge=Ke(v.center.lat,-85.051129,qs),_e=Ke(le.lat,-85.051129,qs),Te=er(v.center.lng),Fe=lr(ge);let He=Te-er(le.lng);const ot=Fe-lr(_e);He>.5?He-=1:He<-.5&&(He+=1);let st=0;Math.abs(He)>Math.abs(ot)?st=He>=0?1:3:(st=ot>=0?0:2,Ee(oe,oe,[I[4]*T,I[5]*T,I[6]*T],-Math.sin(ps(ot>=0?L.getSouth():L.getNorth()))*Tt));const mt=$[st],bt=$[(st+1)%4],wt=new zwt(mt,bt,oe),Gt=[cve(wt,0)||mt[0],cve(wt,1)||mt[1],cve(wt,2)||mt[2]],Ot=aj(v.zoom);if(Ot>0){const Ht=function({x:$t,y:Es,z:Os},Hs,Qs,Gs,hr){const Ss=1/(1<.5?tn=-1:Mr<-.5&&(tn=1),Zs=((Zs+tn)*Hs-(Gs*=Hs))*Qs+Gs,tr=((tr+tn)*Hs-Gs)*Qs+Gs,mr=(mr*Hs-(hr*=Hs))*Qs+hr,wr=(wr*Hs-hr)*Qs+hr,[[Zs,wr,0],[tr,wr,0],[tr,mr,0],[Zs,mr,0]]}(p,h,v._pixelsPerMercatorPixel,Te,Fe);for(let $t=0;$t<$.length;$t++)nj($[$t],Ht[$t],Ot);const Bt=ue([],Ht[st],Ht[(st+1)%4]);xe(Bt,Bt,.5),nj(Gt,Bt,Ot)}for(const Ht of $)fe(re,re,Ht),je(X,X,Ht);return re[2]=Math.min(mt[2],bt[2]),fe(re,re,Gt),je(X,X,Gt),new Xi(re,X)}function j$({x:v,y:h,z:p},w=!1){const T=1/(1<Math.PI/2*1.01}const mPe=ps(85),Bwt=Math.cos(mPe),$wt=Math.sin(mPe),Uwt=y(),fPe=v=>{const h=[];return v.paint.get("circle-pitch-alignment")==="map"&&h.push("PITCH_WITH_MAP"),v.paint.get("circle-pitch-scale")==="map"&&h.push("SCALE_WITH_MAP"),h};function pPe(v,h,p,w,T,I,L,$,V){if(I&&v.queryGeometry.isAboveHorizon)return!1;I&&(V*=v.pixelToTileUnitsFactor);const X=v.tileID.canonical,re=p.projection.upVectorScale(X,p.center.lat,p.worldSize).metersToTile;for(const oe of h)for(const le of oe){const ge=le.add($),_e=T&&p.elevation?p.elevation.exaggeration()*T.getElevationAt(ge.x,ge.y,!0):0,Te=p.projection.projectTilePoint(ge.x,ge.y,X);if(_e>0){const st=p.projection.upVector(X,ge.x,ge.y);Te.x+=st[0]*re*_e,Te.y+=st[1]*re*_e,Te.z+=st[2]*re*_e}const Fe=I?ge:qwt(Te.x,Te.y,Te.z,w),He=I?v.tilespaceRays.map(st=>Hwt(st,_e)):v.queryGeometry.screenGeometry,ot=vt([],[Te.x,Te.y,Te.z,1],w);if(!L&&I?V*=ot[3]/p.cameraToCenterDistance:L&&!I&&(V*=p.cameraToCenterDistance/ot[3]),I){const st=Ts((le.y/Lr+X.y)/(1<v.width||T.height>v.height||p.x>v.width-T.width||p.y>v.height-T.height)throw new RangeError("out of range source coordinates for image copy");if(T.width>h.width||T.height>h.height||w.x>h.width-T.width||w.y>h.height-T.height)throw new RangeError("out of range destination coordinates for image copy");const V=v.data,X=h.data,re=I===4&&$;for(let oe=0;oe{h[v.evaluationKey]=V;const X=v.expression.evaluate(h),re=X?X.toNonPremultipliedRenderColor(null):null;re&&(T.data[L+$+0]=Math.floor(255*re.r),T.data[L+$+1]=Math.floor(255*re.g),T.data[L+$+2]=Math.floor(255*re.b),T.data[L+$+3]=Math.floor(255*re.a))};if(v.clips)for(let L=0,$=0;L80*p){$=v[0],V=v[1];let re=$,oe=V;for(let le=p;lere&&(re=ge),_e>oe&&(oe=_e)}X=Math.max(re-$,oe-V),X=X!==0?32767/X:0}return zD(I,L,p,$,V,X,0),L}function kPe(v,h,p,w,T){let I;if(T===function(L,$,V,X){let re=0;for(let oe=$,le=V-X;oe0)for(let L=h;L=h;L-=w)I=EPe(L/w|0,v[L],v[L+1],I);return I&&qM(I,I.next)&&(UD(I),I=I.next),I}function eC(v,h){if(!v)return v;h||(h=v);let p,w=v;do if(p=!1,w.steiner||!qM(w,w.next)&&eu(w.prev,w,w.next)!==0)w=w.next;else{if(UD(w),w=h=w.prev,w===w.next)break;p=!0}while(p||w!==h);return h}function zD(v,h,p,w,T,I,L){if(!v)return;!L&&I&&function(V,X,re,oe){let le=V;do le.z===0&&(le.z=pve(le.x,le.y,X,re,oe)),le.prevZ=le.prev,le.nextZ=le.next,le=le.next;while(le!==V);le.prevZ.nextZ=null,le.prevZ=null,function(ge){let _e,Te=1;do{let Fe,He=ge;ge=null;let ot=null;for(_e=0;He;){_e++;let st=He,mt=0;for(let wt=0;wt0||bt>0&&st;)mt!==0&&(bt===0||!st||He.z<=st.z)?(Fe=He,He=He.nextZ,mt--):(Fe=st,st=st.nextZ,bt--),ot?ot.nextZ=Fe:ge=Fe,Fe.prevZ=ot,ot=Fe;He=st}ot.nextZ=null,Te*=2}while(_e>1)}(le)}(v,w,T,I);let $=v;for(;v.prev!==v.next;){const V=v.prev,X=v.next;if(I?Xwt(v,w,T,I):Zwt(v))h.push(V.i,v.i,X.i),UD(v),v=X.next,$=X.next;else if((v=X)===$){L?L===1?zD(v=Qwt(eC(v),h),h,p,w,T,I,2):L===2&&Jwt(v,h,p,w,T,I):zD(eC(v),h,p,w,T,I,1);break}}}function Zwt(v){const h=v.prev,p=v,w=v.next;if(eu(h,p,w)>=0)return!1;const T=h.x,I=p.x,L=w.x,$=h.y,V=p.y,X=w.y,re=Math.min(T,I,L),oe=Math.min($,V,X),le=Math.max(T,I,L),ge=Math.max($,V,X);let _e=w.next;for(;_e!==h;){if(_e.x>=re&&_e.x<=le&&_e.y>=oe&&_e.y<=ge&&BD(T,$,I,V,L,X,_e.x,_e.y)&&eu(_e.prev,_e,_e.next)>=0)return!1;_e=_e.next}return!0}function Xwt(v,h,p,w){const T=v.prev,I=v,L=v.next;if(eu(T,I,L)>=0)return!1;const $=T.x,V=I.x,X=L.x,re=T.y,oe=I.y,le=L.y,ge=Math.min($,V,X),_e=Math.min(re,oe,le),Te=Math.max($,V,X),Fe=Math.max(re,oe,le),He=pve(ge,_e,h,p,w),ot=pve(Te,Fe,h,p,w);let st=v.prevZ,mt=v.nextZ;for(;st&&st.z>=He&&mt&&mt.z<=ot;){if(st.x>=ge&&st.x<=Te&&st.y>=_e&&st.y<=Fe&&st!==T&&st!==L&&BD($,re,V,oe,X,le,st.x,st.y)&&eu(st.prev,st,st.next)>=0||(st=st.prevZ,mt.x>=ge&&mt.x<=Te&&mt.y>=_e&&mt.y<=Fe&&mt!==T&&mt!==L&&BD($,re,V,oe,X,le,mt.x,mt.y)&&eu(mt.prev,mt,mt.next)>=0))return!1;mt=mt.nextZ}for(;st&&st.z>=He;){if(st.x>=ge&&st.x<=Te&&st.y>=_e&&st.y<=Fe&&st!==T&&st!==L&&BD($,re,V,oe,X,le,st.x,st.y)&&eu(st.prev,st,st.next)>=0)return!1;st=st.prevZ}for(;mt&&mt.z<=ot;){if(mt.x>=ge&&mt.x<=Te&&mt.y>=_e&&mt.y<=Fe&&mt!==T&&mt!==L&&BD($,re,V,oe,X,le,mt.x,mt.y)&&eu(mt.prev,mt,mt.next)>=0)return!1;mt=mt.nextZ}return!0}function Qwt(v,h){let p=v;do{const w=p.prev,T=p.next.next;!qM(w,T)&&CPe(w,p,p.next,T)&&$D(w,T)&&$D(T,w)&&(h.push(w.i,p.i,T.i),UD(p),UD(p.next),p=v=T),p=p.next}while(p!==v);return eC(p)}function Jwt(v,h,p,w,T,I){let L=v;do{let $=L.next.next;for(;$!==L.prev;){if(L.i!==$.i&&njt(L,$)){let V=TPe(L,$);return L=eC(L,L.next),V=eC(V,V.next),zD(L,h,p,w,T,I,0),void zD(V,h,p,w,T,I,0)}$=$.next}L=L.next}while(L!==v)}function ejt(v,h){let p=v.x-h.x;return p===0&&(p=v.y-h.y,p===0)&&(p=(v.next.y-v.y)/(v.next.x-v.x)-(h.next.y-h.y)/(h.next.x-h.x)),p}function tjt(v,h){const p=function(T,I){let L=I;const $=T.x,V=T.y;let X,re=-1/0;if(qM(T,L))return L;do{if(qM(T,L.next))return L.next;if(V<=L.y&&V>=L.next.y&&L.next.y!==L.y){const Te=L.x+(V-L.y)*(L.next.x-L.x)/(L.next.y-L.y);if(Te<=$&&Te>re&&(re=Te,X=L.x=L.x&&L.x>=le&&$!==L.x&&SPe(VX.x||L.x===X.x&&sjt(X,L)))&&(X=L,_e=Te)}L=L.next}while(L!==oe);return X}(v,h);if(!p)return h;const w=TPe(p,v);return eC(w,w.next),eC(p,p.next)}function sjt(v,h){return eu(v.prev,v,h.prev)<0&&eu(h.next,v,v.next)<0}function pve(v,h,p,w,T){return(v=1431655765&((v=858993459&((v=252645135&((v=16711935&((v=(v-p)*T|0)|v<<8))|v<<4))|v<<2))|v<<1))|(h=1431655765&((h=858993459&((h=252645135&((h=16711935&((h=(h-w)*T|0)|h<<8))|h<<4))|h<<2))|h<<1))<<1}function rjt(v){let h=v,p=v;do(h.x=(v-L)*(I-$)&&(v-L)*(w-$)>=(p-L)*(h-$)&&(p-L)*(I-$)>=(T-L)*(w-$)}function BD(v,h,p,w,T,I,L,$){return!(v===L&&h===$)&&SPe(v,h,p,w,T,I,L,$)}function njt(v,h){return v.next.i!==h.i&&v.prev.i!==h.i&&!function(p,w){let T=p;do{if(T.i!==p.i&&T.next.i!==p.i&&T.i!==w.i&&T.next.i!==w.i&&CPe(T,T.next,p,w))return!0;T=T.next}while(T!==p);return!1}(v,h)&&($D(v,h)&&$D(h,v)&&function(p,w){let T=p,I=!1;const L=(p.x+w.x)/2,$=(p.y+w.y)/2;do T.y>$!=T.next.y>$&&T.next.y!==T.y&&L<(T.next.x-T.x)*($-T.y)/(T.next.y-T.y)+T.x&&(I=!I),T=T.next;while(T!==p);return I}(v,h)&&(eu(v.prev,v,h.prev)||eu(v,h.prev,h))||qM(v,h)&&eu(v.prev,v,v.next)>0&&eu(h.prev,h,h.next)>0)}function eu(v,h,p){return(h.y-v.y)*(p.x-h.x)-(h.x-v.x)*(p.y-h.y)}function qM(v,h){return v.x===h.x&&v.y===h.y}function CPe(v,h,p,w){const T=S$(eu(v,h,p)),I=S$(eu(v,h,w)),L=S$(eu(p,w,v)),$=S$(eu(p,w,h));return T!==I&&L!==$||!(T!==0||!k$(v,p,h))||!(I!==0||!k$(v,w,h))||!(L!==0||!k$(p,v,w))||!($!==0||!k$(p,h,w))}function k$(v,h,p){return h.x<=Math.max(v.x,p.x)&&h.x>=Math.min(v.x,p.x)&&h.y<=Math.max(v.y,p.y)&&h.y>=Math.min(v.y,p.y)}function S$(v){return v>0?1:v<0?-1:0}function $D(v,h){return eu(v.prev,v,v.next)<0?eu(v,h,v.next)>=0&&eu(v,v.prev,h)>=0:eu(v,h,v.prev)<0||eu(v,v.next,h)<0}function TPe(v,h){const p=xve(v.i,v.x,v.y),w=xve(h.i,h.x,h.y),T=v.next,I=h.prev;return v.next=h,h.prev=v,p.next=T,T.prev=p,w.next=p,p.prev=w,I.next=w,w.prev=I,w}function EPe(v,h,p,w){const T=xve(v,h,p);return w?(T.next=w.next,T.prev=w,w.next.prev=T,w.next=T):(T.prev=T,T.next=T),T}function UD(v){v.next.prev=v.prev,v.prev.next=v.next,v.prevZ&&(v.prevZ.nextZ=v.nextZ),v.nextZ&&(v.nextZ.prevZ=v.prevZ)}function xve(v,h,p){return{i:v,x:h,y:p,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function qD(v,h){const p=v.length;if(p<=1)return[v];const w=[];let T,I;for(let L=0;L1)for(let L=0;L=Lr&&p>=Lr}static evaluate(h){if(h.length===0)return new ij;let p=[];for(const V of h)p.push(...V.portals);if(p.length===0)return new ij;for(const V of p){const X=V.va,re=V.vb;(ij.isOnBorder(X.x,re.x)||ij.isOnBorder(X.y,re.y))&&(V.type="border")}const w=p.filter(V=>V.type!=="unevaluated"),T=p.filter(V=>V.type==="unevaluated");if(T.length===0)return new ij;T.sort((V,X)=>V.hash===X.hash?V.isTunnel===X.isTunnel?0:V.isTunnel?-1:1:V.hashV.hashI!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Be(p,{zoom:w,lut:T},I=>I!=="fill-bridge-guard-rail-color")}addVertices(h,p){const w=this.unevalVertices.length;for(let T=0;T=I.min.x&&oe.x<=I.max.x&&oe.y>=I.min.y&&oe.y<=I.max.y||le.x>=I.min.x&&le.x<=I.max.x&&le.y>=I.min.y&&le.y<=I.max.y||Sb(oe,le,$))||this.isOnBorder(oe.x,le.x)||this.isOnBorder(oe.y,le.y))continue;const ge=sx.computeEdgeHash(this.unevalVertices[X],this.unevalVertices[re]);let _e,Te=this.vertexHashLookup.get(sx.computePosHash(oe));Te!=null?_e=Te.next:(Te=this.vertexHashLookup.get(sx.computePosHash(le)),_e=Te!=null?Te.prev:ge),this.unevalEdges.push({polygonIdx:h,a:X,b:re,hash:ge,portalHash:_e,isTunnel:T,type:"unevaluated",featureInfo:L})}}addPortalCandidates(h,p,w,T,I){if(p.length!==0){this.vertexHashLookup.clear();for(const L of p){if(L.length===0)continue;const $=L[0];let V=sx.computeEdgeHash($[$.length-2],$[$.length-1]);for(let X=0;X<$.length-1;X++){const re=$[X+0],oe=$[X+1],le=Jt(oe.x-re.x,oe.y-re.y),ge=$s(le);if(ge===0)continue;let _e="unevaluated";const Te=T.pointElevation(re),Fe=T.pointElevation(oe);Math.abs(Te)<.01&&Math.abs(Fe)<.01?_e="entrance":(this.isOnBorder(re.x,oe.x)||this.isOnBorder(re.y,oe.y))&&(_e="border");const He=sx.computeEdgeHash(re,oe);this.unevaluatedPortals.portals.push({connection:{a:h,b:void 0},va:re,vb:oe,vab:le,length:ge,hash:He,isTunnel:w,type:_e});const ot=sx.computePosHash(re);this.vertexHashLookup.set(ot,{prev:V,next:He}),V=He}}}}construct(h){if(this.unevalVertices.length===0)return;const p=()=>({vertexOffset:0,primitiveOffset:this.indexArray.length}),w=le=>{le.primitiveLength=this.indexArray.length-le.primitiveOffset},T=new ijt(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(h.portals,this.unevalEdges);const I=p(),L=p(),$=p(),V=(le,ge)=>{le.sort((Te,Fe)=>Te.type===ge&&Fe.type!==ge?-1:Te.type!==ge&&Fe.type===ge?1:0);const _e=le.findIndex(Te=>Te.type!==ge);return _e>=0?_e:le.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)),w($);const re=p(),oe=p();if(this.unevalEdges.length>0){const le=this.unevalEdges.splice(X),ge=V(le,"tunnel")+X;this.unevalEdges.push(...le),this.constructTunnelStructures(T,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},{min:X,max:ge})}w(re),T.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),w(oe),T.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),w(L),T.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),w(I),this.maskSegments=jo.simpleSegment(0,oe.primitiveOffset,0,oe.primitiveLength),this.depthSegments=jo.simpleSegment(0,L.primitiveOffset,0,L.primitiveLength),this.renderableBridgeSegments=jo.simpleSegment(0,$.primitiveOffset,0,$.primitiveLength),this.renderableTunnelSegments=jo.simpleSegment(0,re.primitiveOffset,0,re.primitiveLength),this.shadowCasterSegments=jo.simpleSegment(0,I.primitiveOffset,0,I.primitiveLength)}update(h,p,w,T,I,L,$,V){this.bridgeProgramConfigurations.updatePaintArrays(h,p,I,w,T,L,$,V),this.tunnelProgramConfigurations.updatePaintArrays(h,p,I,w,T,L,$,V)}upload(h){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=h.createVertexBuffer(this.vertexPositions,Kwt.members),this.vertexBufferNormal=h.createVertexBuffer(this.vertexNormals,Ywt.members),this.indexBuffer=h.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(h),this.tunnelProgramConfigurations.upload(h))}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(h,p,w,T,I){const L=($,V)=>{for(let X=0;Xae(Qs,p[Gs].x,p[Gs].y,w[Gs]*V),oe=Q(),le=Q(),ge=Q(),_e=Q(),Te=Q(),Fe=(Qs,Gs)=>{const hr=$.get(sx.computePosHash(p[Gs])),Ss=hr.from,Zs=hr.to;if(!Ss||!Zs)return;re(oe,Ss),re(le,Gs),re(ge,Zs),Se(_e),Ge(oe,le)||(We(Te,le,oe),Ve(_e,Te)),Ge(ge,le)||(We(Te,ge,le),ue(_e,_e,Ve(Te,Te)));const tr=qe(_e);return tr>0?xe(Qs,_e,1/tr):void 0};let He=Number.POSITIVE_INFINITY;this.sortSubarray(T,I.min,I.max,(Qs,Gs)=>Qs.featureInfo.featureIndex-Gs.featureInfo.featureIndex);const ot=Q(),st=Q(),mt=Q(),bt=Q(),wt=Q(),Gt=Q(),Ot=Q(),Ht=Q(),Bt=Q(),$t=[Q(),Q(),Q(),Q()],Es=[Q(),Q(),Q(),Q()],Os=[{coord:new gs(0,0),height:0},{coord:new gs(0,0),height:0}],Hs=(Qs,Gs)=>Qs>Gs;for(let Qs=I.min;QsHe.featureInfo.featureIndex-ot.featureInfo.featureIndex;this.sortSubarray(T,I.min,I.max,V),this.sortSubarray(T,L.min,L.max,V);const X=He=>Ve(He,He),re=[{coord:new gs(0,0),height:0},{coord:new gs(0,0),height:0}],oe=(He,ot)=>He$.hash===V.hash?V.polygonIdx-$.polygonIdx:V.hash>$.hash?1:-1);let w=0,T=0,I=0,L=p[w].polygonIdx;do T++,(T===p.length||p[w].hash!==p[T].hash)&&((T-w===1||p[T-1].polygonIdx!==L)&&(IX.portalHashre.hash?$++:re.hash>X.portalHash?V++:(X.type=re.type,$++)}}}isOnBorder(h,p){return h<=0&&p<=0||h>=Lr&&p>=Lr}addFeatureSection(h,p,w,T){return h!==p&&(p=h,w.push({featureIndex:h,vertexStart:T.getVertexCount()}),T.clearVertexLookup()),p}sortSubarray(h,p,w,T){const I=h.slice(p,w);I.sort(T),h.splice(p,I.length,...I)}static computeEdgeHash(h,p){return(h.y===p.y&&h.x>p.x||h.y>p.y)&&([h,p]=[p,h]),BigInt(sx.computePosHash(h))<<32n|BigInt(sx.computePosHash(p))}static computePosHash(h){return((65535&h.x)<<16|65535&h.y)>>>0}}function ojt(v,h){return v>h?1:v0))return p;p=p.left}}return null}contains(h){for(var p=this._root,w=this._compare;p;){var T=w(h,p.key);if(T===0)return!0;p=T<0?p.left:p.right}return!1}remove(h){var p=this.find(h);if(!p)return!1;if(this.splay(p),p.left)if(p.right){var w=this.minNode(p.right);w.parent!==p&&(this.replace(w,w.right),w.right=p.right,w.right.parent=w),this.replace(p,w),w.left=p.left,w.left.parent=w}else this.replace(p,p.left);else this.replace(p,p.right);return this._size--,!0}removeNode(h){if(!h)return!1;if(this.splay(h),h.left)if(h.right){var p=this.minNode(h.right);p.parent!==h&&(this.replace(p,p.right),p.right=h.right,p.right.parent=p),this.replace(h,p),p.left=h.left,p.left.parent=p}else this.replace(h,h.left);else this.replace(h,h.right);return this._size--,!0}erase(h){var p=this.find(h);if(p){this.splay(p);var w=p.left,T=p.right,I=null;w&&(w.parent=null,I=this.maxNode(w),this.splay(I),this._root=I),T&&(w?I.right=T:this._root=T,T.parent=I),this._size--}}pop(){var h=this._root,p=null;if(h){for(;h.left;)h=h.left;p={key:h.key,data:h.data},this.remove(h.key)}return p}next(h){var p=h;if(p)if(p.right)for(p=p.right;p&&p.left;)p=p.left;else for(p=h.parent;p&&p.right===h;)h=p,p=p.parent;return p}prev(h){var p=h;if(p)if(p.left)for(p=p.left;p&&p.right;)p=p.right;else for(p=h.parent;p&&p.left===h;)h=p,p=p.parent;return p}forEach(h){for(var p=this._root,w=[],T=!1,I=0;!T;)p?(w.push(p),p=p.left):w.length>0?(h(p=w.pop(),I++),p=p.right):T=!0;return this}range(h,p,w,T){const I=[],L=this._compare;let $,V=this._root;for(;I.length!==0||V;)if(V)I.push(V),V=V.left;else{if(V=I.pop(),$=L(V.key,p),$>0)break;if(L(V.key,h)>=0&&w.call(T,V))return this;V=V.right}return this}keys(){for(var h=this._root,p=[],w=[],T=!1;!T;)h?(p.push(h),h=h.left):p.length>0?(h=p.pop(),w.push(h.key),h=h.right):T=!0;return w}values(){for(var h=this._root,p=[],w=[],T=!1;!T;)h?(p.push(h),h=h.left):p.length>0?(h=p.pop(),w.push(h.data),h=h.right):T=!0;return w}at(h){for(var p=this._root,w=[],T=!1,I=0;!T;)if(p)w.push(p),p=p.left;else if(w.length>0){if(p=w.pop(),I===h)return p;I++,p=p.right}else T=!0;return null}load(h=[],p=[],w=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const T=h.length;return w&&_ve(h,p,0,T-1,this._compare),this._root=bve(null,h,p,0,T),this._size=T,this}min(){var h=this.minNode(this._root);return h?h.key:null}max(){var h=this.maxNode(this._root);return h?h.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(h,p,w,T,I){return new vve(w,I).load(h,p,T)}}function bve(v,h,p,w,T){const I=T-w;if(I>0){const L=w+Math.floor(I/2),$={key:h[L],data:p[L],parent:v};return $.left=bve($,h,p,w,L),$.right=bve($,h,p,L+1,T),$}return null}function _ve(v,h,p,w,T){if(p>=w)return;const I=v[p+w>>1];let L=p-1,$=w+1;for(;;){do L++;while(T(v[L],I)<0);do $--;while(T(v[$],I)>0);if(L>=$)break;let V=v[L];v[L]=v[$],v[$]=V,V=h[L],h[L]=h[$],h[$]=V}_ve(v,h,p,$,T),_ve(v,h,$+1,w,T)}const MPe=11102230246251565e-32,gp=134217729,ljt=(3+8*MPe)*MPe;function wve(v,h,p,w,T){let I,L,$,V,X=h[0],re=w[0],oe=0,le=0;re>X==re>-X?(I=X,X=h[++oe]):(I=re,re=w[++le]);let ge=0;if(oeX==re>-X?(L=X+I,$=I-(L-X),X=h[++oe]):(L=re+I,$=I-(L-re),re=w[++le]),I=L,$!==0&&(T[ge++]=$);oeX==re>-X?(L=I+X,V=L-I,$=I-(L-V)+(X-V),X=h[++oe]):(L=I+re,V=L-I,$=I-(L-V)+(re-V),re=w[++le]),I=L,$!==0&&(T[ge++]=$);for(;oe0:(w[0]-h[0])*(p[1]-h[1])-(p[0]-h[0])*(w[1]-h[1])>0}isAbove(h){return!this.isBelow(h)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const h=new HM(this.point,this.left,this.otherEvent,this.isSubject,this.type);return h.contourId=this.contourId,h.resultTransition=this.resultTransition,h.prevInResult=this.prevInResult,h.isExteriorRing=this.isExteriorRing,h.inOut=this.inOut,h.otherInOut=this.otherInOut,h}}function Eb(v,h){return v[0]===h[0]&&v[1]===h[1]}function jve(v,h,p){const w=function(T,I,L,$,V,X){const re=(I-X)*(L-V),oe=(T-V)*($-X),le=re-oe;if(re===0||oe===0||re>0!=oe>0)return le;const ge=Math.abs(re+oe);return Math.abs(le)>=33306690738754716e-32*ge?le:-function(_e,Te,Fe,He,ot,st,mt){let bt,wt,Gt,Ot,Ht,Bt,$t,Es,Os,Hs,Qs,Gs,hr,Ss,Zs,tr,mr,wr;const tn=_e-ot,Mr=Fe-ot,Tr=Te-st,jr=He-st;Ss=tn*jr,Bt=gp*tn,$t=Bt-(Bt-tn),Es=tn-$t,Bt=gp*jr,Os=Bt-(Bt-jr),Hs=jr-Os,Zs=Es*Hs-(Ss-$t*Os-Es*Os-$t*Hs),tr=Tr*Mr,Bt=gp*Tr,$t=Bt-(Bt-Tr),Es=Tr-$t,Bt=gp*Mr,Os=Bt-(Bt-Mr),Hs=Mr-Os,mr=Es*Hs-(tr-$t*Os-Es*Os-$t*Hs),Qs=Zs-mr,Ht=Zs-Qs,VM[0]=Zs-(Qs+Ht)+(Ht-mr),Gs=Ss+Qs,Ht=Gs-Ss,hr=Ss-(Gs-Ht)+(Qs-Ht),Qs=hr-tr,Ht=hr-Qs,VM[1]=hr-(Qs+Ht)+(Ht-tr),wr=Gs+Qs,Ht=wr-Gs,VM[2]=Gs-(wr-Ht)+(Qs-Ht),VM[3]=wr;let Xr=function(xi,ba){let bi=ba[0];for(let za=1;za<4;za++)bi+=ba[za];return bi}(0,VM),ln=22204460492503146e-32*mt;if(Xr>=ln||-Xr>=ln||(Ht=_e-tn,bt=_e-(tn+Ht)+(Ht-ot),Ht=Fe-Mr,Gt=Fe-(Mr+Ht)+(Ht-ot),Ht=Te-Tr,wt=Te-(Tr+Ht)+(Ht-st),Ht=He-jr,Ot=He-(jr+Ht)+(Ht-st),bt===0&&wt===0&&Gt===0&&Ot===0)||(ln=11093356479670487e-47*mt+ljt*Math.abs(Xr),Xr+=tn*Ot+jr*bt-(Tr*Gt+Mr*wt),Xr>=ln||-Xr>=ln))return Xr;Ss=bt*jr,Bt=gp*bt,$t=Bt-(Bt-bt),Es=bt-$t,Bt=gp*jr,Os=Bt-(Bt-jr),Hs=jr-Os,Zs=Es*Hs-(Ss-$t*Os-Es*Os-$t*Hs),tr=wt*Mr,Bt=gp*wt,$t=Bt-(Bt-wt),Es=wt-$t,Bt=gp*Mr,Os=Bt-(Bt-Mr),Hs=Mr-Os,mr=Es*Hs-(tr-$t*Os-Es*Os-$t*Hs),Qs=Zs-mr,Ht=Zs-Qs,rx[0]=Zs-(Qs+Ht)+(Ht-mr),Gs=Ss+Qs,Ht=Gs-Ss,hr=Ss-(Gs-Ht)+(Qs-Ht),Qs=hr-tr,Ht=hr-Qs,rx[1]=hr-(Qs+Ht)+(Ht-tr),wr=Gs+Qs,Ht=wr-Gs,rx[2]=Gs-(wr-Ht)+(Qs-Ht),rx[3]=wr;const On=wve(4,VM,4,rx,IPe);Ss=tn*Ot,Bt=gp*tn,$t=Bt-(Bt-tn),Es=tn-$t,Bt=gp*Ot,Os=Bt-(Bt-Ot),Hs=Ot-Os,Zs=Es*Hs-(Ss-$t*Os-Es*Os-$t*Hs),tr=Tr*Gt,Bt=gp*Tr,$t=Bt-(Bt-Tr),Es=Tr-$t,Bt=gp*Gt,Os=Bt-(Bt-Gt),Hs=Gt-Os,mr=Es*Hs-(tr-$t*Os-Es*Os-$t*Hs),Qs=Zs-mr,Ht=Zs-Qs,rx[0]=Zs-(Qs+Ht)+(Ht-mr),Gs=Ss+Qs,Ht=Gs-Ss,hr=Ss-(Gs-Ht)+(Qs-Ht),Qs=hr-tr,Ht=hr-Qs,rx[1]=hr-(Qs+Ht)+(Ht-tr),wr=Gs+Qs,Ht=wr-Gs,rx[2]=Gs-(wr-Ht)+(Qs-Ht),rx[3]=wr;const xn=wve(On,IPe,4,rx,PPe);Ss=bt*Ot,Bt=gp*bt,$t=Bt-(Bt-bt),Es=bt-$t,Bt=gp*Ot,Os=Bt-(Bt-Ot),Hs=Ot-Os,Zs=Es*Hs-(Ss-$t*Os-Es*Os-$t*Hs),tr=wt*Gt,Bt=gp*wt,$t=Bt-(Bt-wt),Es=wt-$t,Bt=gp*Gt,Os=Bt-(Bt-Gt),Hs=Gt-Os,mr=Es*Hs-(tr-$t*Os-Es*Os-$t*Hs),Qs=Zs-mr,Ht=Zs-Qs,rx[0]=Zs-(Qs+Ht)+(Ht-mr),Gs=Ss+Qs,Ht=Gs-Ss,hr=Ss-(Gs-Ht)+(Qs-Ht),Qs=hr-tr,Ht=hr-Qs,rx[1]=hr-(Qs+Ht)+(Ht-tr),wr=Gs+Qs,Ht=wr-Gs,rx[2]=Gs-(wr-Ht)+(Qs-Ht),rx[3]=wr;const va=wve(xn,PPe,4,rx,LPe);return LPe[va-1]}(T,I,L,$,V,X,ge)}(v[0],v[1],h[0],h[1],p[0],p[1]);return w>0?-1:w<0?1:0}function NN(v,h){const p=v.point,w=h.point;return p[0]>w[0]?1:p[0]w[1]?1:-1:function(T,I,L){return T.left!==I.left?T.left?1:-1:jve(L,T.otherEvent.point,I.otherEvent.point)!==0?T.isBelow(I.otherEvent.point)?-1:1:!T.isSubject&&I.isSubject?1:-1}(v,h,p)}function kN(v,h,p){const w=new HM(h,!1,v,v.isSubject),T=new HM(h,!0,v.otherEvent,v.isSubject);return Eb(v.point,v.otherEvent.point)&&console.warn("what is that, a collapsed segment?",v),w.contourId=T.contourId=v.contourId,NN(T,v.otherEvent)>0&&(v.otherEvent.left=!0,T.left=!1),v.otherEvent.otherEvent=T,v.otherEvent=w,p.push(T),p.push(w),p}function C$(v,h){return v[0]*h[1]-v[1]*h[0]}function Nve(v,h){return v[0]*h[0]+v[1]*h[1]}function kve(v,h,p){const w=function(V,X,re,oe){const le=[X[0]-V[0],X[1]-V[1]],ge=[oe[0]-re[0],oe[1]-re[1]];function _e(Gt,Ot,Ht){return[Gt[0]+Ot*Ht[0],Gt[1]+Ot*Ht[1]]}const Te=[re[0]-V[0],re[1]-V[1]];let Fe=C$(le,ge),He=Fe*Fe;const ot=Nve(le,le);if(He>0){const Gt=C$(Te,ge)/Fe;if(Gt<0||Gt>1)return null;const Ot=C$(Te,le)/Fe;return Ot<0||Ot>1?null:Gt===0||Gt===1?[_e(V,Gt,le)]:Ot===0||Ot===1?[_e(re,Ot,ge)]:[_e(V,Gt,le)]}if(Fe=C$(Te,le),He=Fe*Fe,He>0)return null;const st=Nve(le,Te)/ot,mt=st+Nve(le,ge)/ot,bt=Math.min(st,mt),wt=Math.max(st,mt);return bt<=1&&wt>=0?bt===1?[_e(V,bt>0?bt:0,le)]:wt===0?[_e(V,wt<1?wt:1,le)]:[_e(V,bt>0?bt:0,le),_e(V,wt<1?wt:1,le)]:null}(v.point,v.otherEvent.point,h.point,h.otherEvent.point),T=w?w.length:0;if(T===0||T===1&&(Eb(v.point,h.point)||Eb(v.otherEvent.point,h.otherEvent.point))||T===2&&v.isSubject===h.isSubject)return 0;if(T===1)return!Eb(v.point,w[0])&&!Eb(v.otherEvent.point,w[0])&&kN(v,w[0],p),!Eb(h.point,w[0])&&!Eb(h.otherEvent.point,w[0])&&kN(h,w[0],p),1;const I=[];let L=!1,$=!1;return Eb(v.point,h.point)?L=!0:NN(v,h)===1?I.push(h,v):I.push(v,h),Eb(v.otherEvent.point,h.otherEvent.point)?$=!0:NN(v.otherEvent,h.otherEvent)===1?I.push(h.otherEvent,v.otherEvent):I.push(v.otherEvent,h.otherEvent),L&&$||L?(h.type=1,v.type=h.inOut===v.inOut?2:3,L&&!$&&kN(I[1].otherEvent,I[0].point,p),2):$?(kN(I[0],I[1].point,p),3):I[0]!==I[3].otherEvent?(kN(I[0],I[1].point,p),kN(I[1],I[2].point,p),3):(kN(I[0],I[1].point,p),kN(I[3].otherEvent,I[2].point,p),3)}function cjt(v,h){if(v===h)return 0;if(jve(v.point,v.otherEvent.point,h.point)!==0||jve(v.point,v.otherEvent.point,h.otherEvent.point)!==0)return Eb(v.point,h.point)?v.isBelow(h.otherEvent.point)?-1:1:v.point[0]===h.point[0]?v.point[1](h.contourId??0)?1:-1}return NN(v,h)===1?1:-1}class djt{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function ujt(v,h,p,w){let T,I=v+1,L=h[v].point;const $=h.length;for(I<$&&(T=h[I].point);I<$&&T[0]===L[0]&&T[1]===L[1];){if(!p[I])return I;I++,I<$&&(T=h[I].point)}for(I=v-1;p[I]&&I>w;)I--;return I}function hjt(v,h,p){const w=new djt;if(v.prevInResult!=null){const T=v.prevInResult,I=T.outputContourId;if(T.resultTransition>0){const L=h[I];if(L.holeOf!=null){const $=L.holeOf;h[$].holeIds.push(p),w.holeOf=$,w.depth=h[I].depth}else h[I].holeIds.push(p),w.holeOf=I,w.depth=h[I].depth+1}else w.holeOf=null,w.depth=h[I].depth}else w.holeOf=null,w.depth=0;return w}const RPe=Math.max,OPe=Math.min;let T$=0;function FPe(v,h,p,w,T,I){let L,$,V,X,re,oe;for(L=0,$=v.length-1;L<$;L++){if(V=v[L],X=v[L+1],re=new HM(V,!1,void 0,h),oe=new HM(X,!1,re,h),re.otherEvent=oe,V[0]===X[0]&&V[1]===X[1])continue;re.contourId=oe.contourId=p,I||(re.isExteriorRing=!1,oe.isExteriorRing=!1),NN(re,oe)>0?oe.left=!0:re.left=!0;const le=V[0],ge=V[1];T[0]=OPe(T[0],le),T[1]=OPe(T[1],ge),T[2]=RPe(T[2],le),T[3]=RPe(T[3],ge),w.push(re),w.push(oe)}}const E$=[];function zPe(v,h,p){let w=v,T=h;typeof v[0][0][0]=="number"&&(w=[v]),typeof h[0][0][0]=="number"&&(T=[h]);let I=function(le,ge,_e){let Te=null;return le.length*ge.length===0&&(_e===0?Te=E$:_e===2?Te=le:(_e===1||_e===3)&&(Te=le.length===0?ge:le)),Te}(w,T,p);if(I)return I===E$?null:I;const L=[1/0,1/0,-1/0,-1/0],$=[1/0,1/0,-1/0,-1/0],V=function(le,ge,_e,Te,Fe){const He=new Og(void 0,NN);let ot,st,mt,bt,wt,Gt;for(mt=0,bt=le.length;mtTe[2]||Te[0]>_e[2]||_e[1]>Te[3]||Te[1]>_e[3])&&(Fe===0?He=E$:Fe===2?He=le:(Fe===1||Fe===3)&&(He=le.concat(ge))),He}(w,T,L,$,p),I)return I===E$?null:I;const X=function(le,ge,_e,Te,Fe,He){const ot=new vve(cjt),st=[],mt=Math.min(Te[2],Fe[2]);let bt,wt,Gt;for(;le.length!==0;){let Ot=le.pop();if(st.push(Ot),He===0&&Ot.point[0]>mt||He===2&&Ot.point[0]>Te[2])break;if(Ot.left){wt=bt=ot.insert(Ot),Gt=ot.minNode(),bt=bt!==Gt?ot.prev(bt):null,wt=ot.next(wt);const Ht=bt?bt.key:null;let Bt;if(HD(Ot,Ht,He),wt&&kve(Ot,wt.key,le)===2&&(HD(Ot,Ht,He),HD(wt.key,Ot,He)),bt&&kve(bt.key,Ot,le)===2){let $t=bt;$t=$t!==Gt?ot.prev($t):null,Bt=$t?$t.key:null,HD(Ht,Bt,He),HD(Ot,Ht,He)}}else Ot=Ot.otherEvent,wt=bt=ot.find(Ot),bt&&wt&&(bt=bt!==Gt?ot.prev(bt):null,wt=ot.next(wt),ot.remove(Ot),wt&&bt&&kve(bt.key,wt.key,le))}return st}(V,0,0,L,$,p),re=function(le){let ge,_e;const Te=function(ot){let st,mt,bt,wt,Gt;const Ot=[];for(mt=0,bt=ot.length;mt{Fe[Gt]=!0,Gt=Te.length)&&Te[bt];);He.push(st)}return He}(X),oe=[];for(let le=0;le{L.push(new gs(oe,V+(oe-$)/(X-$)*(re-V)))}:(L,$,V,X,re,oe)=>{L.push(new gs($+(oe-V)/(re-V)*(X-$),oe))};for(const L of v){const $=[];for(const V of L){if(V.length<=2)continue;const X=[];for(let le=0;leh&&I(X,ge,_e,Te,Fe,h):He>p?ot=h&&I(X,ge,_e,Te,Fe,h),ot>p&&He<=p&&I(X,ge,_e,Te,Fe,p)}let re=V[V.length-1];const oe=w===0?re.x:re.y;oe>=h&&oe<=p&&X.push(re),X.length&&(re=X[X.length-1],X[0].x===re.x&&X[0].y===re.y||X.push(X[0]),$.push(X))}$.length&&T.push($)}return T}function mjt(v,h){const p=zPe(Sve(v),Sve([h]),0);return p==null?[]:BPe(p)}function fjt(v,h,p=0){let T=Sve(v,65536);const I=[];for(;h.valid();h.next()){const[L,$]=h.get();let V=L.x*65536,X=L.y*65536,re=$.x*65536,oe=$.y*65536;const le=re-V,ge=oe-X,_e=Math.hypot(le,ge);if(_e===0)continue;V-=le*p,X-=ge*p,re+=le*p,oe+=ge*p;const Te=Math.trunc(ge/_e*3),Fe=-Math.trunc(le/_e*3);I.push([[[V,X],[re,oe],[re+Te,oe+Fe],[V+Te,X+Fe],[V,X]]])}return I.length>0&&(T=zPe(T,I,2)),BPe(T,1/65536,128)}function Sve(v,h=1){return[v.map(p=>p.map(w=>[w.x*h,w.y*h]))]}function BPe(v,h=1,p){return v.map(w=>w.map((T,I)=>{const L=T.map($=>{let V=$[0],X=$[1];return p&&(V=Math.round(V/p)*p,X=Math.round(X/p)*p),new gs(V*h,X*h)._round()});return I>0&&L.reverse(),L}))}class Cve{constructor(h,p){this.layoutVertexArray=new Ra,this.indexArray=new Gl,this.lineIndexArray=new Gx,this.triangleSegments=new jo,this.lineSegments=new jo,this.programConfigurations=new Be(h.layers,{zoom:h.zoom,lut:h.lut}),this.uploaded=!1,p&&(this.elevatedLayoutVertexArray=new eo)}update(h,p,w,T,I,L,$,V){this.programConfigurations.updatePaintArrays(h,p,I,w,T,L,$,V)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(h){this.uploaded||(this.layoutVertexBuffer=h.createVertexBuffer(this.layoutVertexArray,Gwt.members),this.indexBuffer=h.createIndexBuffer(this.indexArray),this.lineIndexBuffer=h.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=h.createVertexBuffer(this.elevatedLayoutVertexArray,Wwt.members))),this.programConfigurations.upload(h),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(h,p,w,T,I,L,$){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,h,p,w,T,I,L,void 0,$)}}class M${constructor(h){this.zoom=h.zoom,this.pixelRatio=h.pixelRatio,this.overscaling=h.overscaling,this.layers=h.layers,this.layerIds=this.layers.map(p=>p.fqid),this.index=h.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=h.lut,this.bufferData=new Cve(h,!1),this.elevationBufferData=new Cve(h,!0),this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.projection=h.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=h.sourceLayerIndex,this.worldview=h.worldview,this.hasAppearances=null}updateFootprints(h,p){}updateAppearances(h,p,w,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(h,p,w,T){this.hasPattern=gve("fill",this.layers,this.pixelRatio,p);const I=this.layers[0].layout.get("fill-sort-key"),L=[];for(const{feature:$,id:V,index:X,sourceLayerIndex:re}of h){const oe=this.layers[0]._featureFilter.needGeometry,le=Fa($,oe);if(!this.layers[0]._featureFilter.filter(new ja(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),le,w))continue;const ge=I?I.evaluate(le,{},w,p.availableImages):void 0,_e={id:V,properties:$.properties,type:$.type,sourceLayerIndex:re,index:X,geometry:oe?le.geometry:zn($,w,T),patterns:{},sortKey:ge};L.push(_e)}I&&L.sort(($,V)=>$.sortKey-V.sortKey);for(const $ of L){const{geometry:V,index:X,sourceLayerIndex:re}=$;if(this.hasPattern){const oe=yve("fill",this.layers,$,this.zoom,this.pixelRatio,p);this.patternFeatures.push(oe)}else this.addFeature($,V,X,w,{},p.availableImages,p.brightness,p.elevationFeatures);p.featureIndex.insert(h[X].feature,V,X,re,this.index)}}update(h,p,w,T,I,L,$){this.bufferData.update(h,p,w,T,I,L,$,this.worldview),this.elevationBufferData.update(h,p,w,T,I,L,$,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(h,p,w,T,I,L,$,this.worldview)}addFeatures(h,p,w,T,I,L){for(const $ of this.patternFeatures)this.addFeature($,$.geometry,$.index,p,w,T,L,h.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(h){this.bufferData.upload(h),this.elevationBufferData.upload(h),this.elevatedStructures&&this.elevatedStructures.upload(h)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(h,p,w,T,I,L=[],$,V){const X=qD(p,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(h,X,T,w,V):this.addGeometry(X,this.bufferData),this.bufferData.populatePaintArrays(h,w,I,L,T,$,this.worldview),this.elevationBufferData.populatePaintArrays(h,w,I,L,T,$,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(h,p,w,T,I){this.elevatedStructures&&(this.elevatedStructures.construct(h),this.elevatedStructures.populatePaintArrays(p,w,T,I,this.worldview))}addElevatedRoadFeature(h,p,w,T,I){const L=new Array,$=To.getElevationFeature(h,I);if(!$)return void this.addGeometry(p,this.bufferData);{const X=this.clipPolygonsToTile(p,1);X.length>0&&L.push({polygons:X,elevationFeature:$,elevationTileID:w})}const V={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(h,{},w),featureIndex:T};for(const X of L)if(X.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new sx(X.elevationTileID,this.layers,this.zoom,this.lut));const oe=X.elevationFeature.isTunnel();let le=0;h.properties.hasOwnProperty(ko)&&(le=+h.properties[ko]),this.elevatedStructures.addPortalCandidates(X.elevationFeature.id,X.polygons,oe,X.elevationFeature,le)}X.elevationFeature.constantHeight==null&&(X.polygons=this.prepareElevatedPolygons(X.polygons,X.elevationFeature,X.elevationTileID));const re=new Po(w,X.elevationTileID);this.addElevatedGeometry(X.polygons,re,X.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,T,V)}}addElevatedGeometry(h,p,w,T,I,L){const $={elevation:w,elevationSampler:p,bias:T,index:I,featureInfo:L},[V,X]=this.addGeometry(h,this.elevationBufferData,$);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(h,p,w){let T=Number.POSITIVE_INFINITY,I=Number.NEGATIVE_INFINITY,L=null;w&&(L=w.elevationSampler.constantElevation(w.elevation,w.bias),L!=null&&(T=L,I=L));const $=(V,X,re)=>{if(w!=null)if(X.push(V),L!=null)p.elevatedLayoutVertexArray.emplaceBack(L),re.push(L);else{const oe=w.elevationSampler.pointElevation(V,w.elevation,w.bias);p.elevatedLayoutVertexArray.emplaceBack(oe),re.push(oe),T=Math.min(T,oe),I=Math.max(I,oe)}};for(const V of h){let X=0;for(const st of V)X+=st.length;const re=p.triangleSegments.prepareSegment(X,p.layoutVertexArray,p.indexArray),oe=re.vertexLength,le=[],ge=[],_e=[],Te=[],Fe=[],He=p.layoutVertexArray.length;for(const st of V){if(st.length===0)continue;st!==V[0]&&ge.push(le.length/2);const mt=p.lineSegments.prepareSegment(st.length,p.layoutVertexArray,p.lineIndexArray),bt=mt.vertexLength;w&&Fe.push(p.layoutVertexArray.length-He),$(st[0],_e,Te),p.layoutVertexArray.emplaceBack(st[0].x,st[0].y),p.lineIndexArray.emplaceBack(bt+st.length-1,bt),le.push(st[0].x),le.push(st[0].y);for(let wt=1;wt0&&w&&this.elevationMode==="hd-road-base"){const st=w.elevation.isTunnel(),mt=w.elevation.safeArea,bt=this.elevatedStructures.addVertices(_e,Te);this.elevatedStructures.addTriangles(ot,bt,st);const wt=Fe.length;if(wt>0){for(let Gt=0;Gt=w&&ge.max.x<=I&&ge.min.y>=T&&ge.max.y<=L?V:X).push(le)}if(V.length===h.length)return h;const re=[new gs(w,T),new gs(I,T),new gs(I,L),new gs(w,L),new gs(w,T)],oe=V;for(const le of X)oe.push(...mjt(le,re));return oe}}let $Pe,UPe,qPe,VPe;Wr(M$,"FillBucket",{omit:["layers","patternFeatures"]}),Wr(Cve,"FillBufferData"),Wr(sx,"ElevatedStructures");class I${constructor(h,p,w,T){if(this.triangleCount=p.length/3,this.min=new gs(0,0),this.max=new gs(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||h.length===0)return;const[I,L]=[h[0].clone(),h[0].clone()];for(let oe=1;oeoe.cellIdx-le.cellIdx||oe.triIdx-le.triIdx);let re=0;for(;rethis.max.x||this.min.x>h.x||h.y>this.max.y||this.min.y>h.y)return;const w=Ab(h.x-this.min.x,this.xScale,this.cellsX),T=Ab(h.y-this.min.y,this.yScale,this.cellsY),I=this.cells[T*this.cellsX+w];if(I){this._lazyInitLookup();for(let L=0;Lthis.max.x||this.min.x>p.x||h.y>this.max.y||this.min.y>p.y)return;this._lazyInitLookup();const T=Ab(h.x-this.min.x,this.xScale,this.cellsX),I=Ab(p.x-this.min.x,this.xScale,this.cellsX),L=Ab(h.y-this.min.y,this.yScale,this.cellsY),$=Ab(p.y-this.min.y,this.yScale,this.cellsY);for(let V=L;V<=$;V++)for(let X=T;X<=I;X++){const re=this.cells[V*this.cellsX+X];if(re)for(let oe=0;oep.fqid),this.index=h.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.footprints=[],this.worldview=h.worldview,this.hasAppearances=null}updateFootprints(h,p){for(const w of this.footprints)p.push({footprint:w,id:h})}updateAppearances(h,p,w,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(h,p,w,T){const I=[];for(const{feature:L,id:$,index:V,sourceLayerIndex:X}of h){const re=this.layers[0]._featureFilter.needGeometry,oe=Fa(L,re);if(!this.layers[0]._featureFilter.filter(new ja(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),oe,w))continue;const le={id:$,properties:L.properties,type:L.type,sourceLayerIndex:X,index:V,geometry:re?oe.geometry:zn(L,w,T),patterns:{}};I.push(le)}for(const L of I){const{geometry:$,index:V,sourceLayerIndex:X}=L;this.addFeature(L,$,V,w,{},p.availableImages,p.brightness),p.featureIndex.insert(h[V].feature,$,V,X,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(h){}update(h,p,w,T,I,L,$){}destroy(){}addFeature(h,p,w,T,I,L=[],$){for(const V of qD(p,2)){const X=[],re=[],oe=[],le=new gs(1/0,1/0),ge=new gs(-1/0,-1/0);for(const Fe of V)if(Fe.length!==0){Fe!==V[0]&&oe.push(re.length/2);for(let He=0;Heh.max.x||v.max.xh.max.y||v.max.ynew gs((V.x+I.x*Lr)*$-L.x*Lr,(V.y+I.y*Lr)*$-L.y*Lr))}return Eve(p,T,v.indices,0,v.indices.length,0,0)}function ZPe(v,h,p,w){const T=Math.pow(2,w.z-p.z);return new gs((v+p.x*Lr)*T-w.x*Lr,(h+p.y*Lr)*T-w.y*Lr)}function XPe(v,h){const p=[];h.grid.queryPoint(v,p);const w=h.indices,T=h.vertices;for(let I=0;I0&&(w.length>1&&p.push(w),w=[])}return w.length>1&&p.push(w),p}const Mve=ia.types,kjt=["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"],Sjt=["fill-extrusion-flood-light-ground-radius"],Cjt=Math.pow(2,13),Tjt=Math.pow(2,15)-1,R$=new gs(0,1),oj=2147483648,O$=1073741824;function WD(v,h,p,w,T,I,L,$){v.emplaceBack((h<<1)+L,(p<<1)+I,(Math.floor(w*Cjt)<<1)+T,Math.round($))}function KD(v,h,p){v.emplaceBack(h.x*Lr,h.y*Lr,p?1:0)}function F$(v,h,p,w,T,I){v.emplaceBack(h.x,h.y,(p.x<<1)+w,(p.y<<1)+T,I)}function YD(v,h,p){v.emplaceBack(h.x,h.y,h.z,p[0]*16384,p[1]*16384,p[2]*16384)}class JPe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class Ive{constructor(){this.centroidXY=new gs(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 gs(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new gs(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new gs(0,0)}span(){return new gs(this.max.x-this.min.x,this.max.y-this.min.y)}}class Pve{constructor(){this.acc=new gs(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(h,p){h.min.x===Number.MAX_VALUE&&(h.min.x=h.max.x=p.x,h.min.y=h.max.y=p.y)}appendEdge(h,p,w){this.accCount++,this.acc._add(p);let T=!!this.borders;p.xh.max.x&&(h.max.x=p.x,T=!0),p.yh.max.y&&(h.max.y=p.y,T=!0),((p.x===0||p.x===Lr)&&p.x===w.x)!=((p.y===0||p.y===Lr)&&p.y===w.y)&&this.processBorderOverlap(p,w),T&&this.checkBorderIntersection(p,w)}checkBorderIntersection(h,p){p.x<0!=h.x<0&&this.addBorderIntersection(0,An(p.y,h.y,(0-p.x)/(h.x-p.x))),p.x>Lr!=h.x>Lr&&this.addBorderIntersection(1,An(p.y,h.y,(Lr-p.x)/(h.x-p.x))),p.y<0!=h.y<0&&this.addBorderIntersection(2,An(p.x,h.x,(0-p.y)/(h.y-p.y))),p.y>Lr!=h.y>Lr&&this.addBorderIntersection(3,An(p.x,h.x,(Lr-p.y)/(h.y-p.y)))}addBorderIntersection(h,p){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 w=this.borders[h];pw[1]&&(w[1]=p)}processBorderOverlap(h,p){if(h.x===p.x){if(h.y===p.y)return;const w=h.x===0?0:1;this.addBorderIntersection(w,p.y),this.addBorderIntersection(w,h.y)}else{const w=h.y===0?2:3;this.addBorderIntersection(w,p.x),this.addBorderIntersection(w,h.x)}}centroid(){return this.accCount===0?new gs(0,0):new gs(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((h,p)=>h+ +(p[0]!==Number.MAX_VALUE),0):0}}function eLe(v,h){const p=v.add(h)._unit(),w=Ke(v.x*p.x+v.y*p.y,-1,1);var T,I,L;return L=Math.acos(w),Math.min(4,Math.max(-4,Math.tan(L)))/4*Tjt*((T=v).x*(I=h).y-T.y*I.x<0?-1:1)}const Ejt=[v=>v.x<0,v=>v.x>Lr,v=>v.y<0,v=>v.y>Lr];function Ajt(v,h,p,w){const T=[4];if(w===0)return T;p._mult(w);const I=v.sub(p),L=h.sub(p),$=[v,h,I,L];for(let V=0;V<4;V++)for(const X of $)if(Ejt[V](X)){T.push(V);break}return T}class Lve{constructor(h){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new $4,this.indexArray=new Gl,this.programConfigurations=new Be(h.layers,{zoom:h.zoom,lut:h.lut},p=>Sjt.includes(p)),this._segments=new jo,this.hiddenByLandmarkVertexArray=new OM,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new jo}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(h,p,w,T=!1){const I=h.length;if(I>2){let L=Math.max(0,this._segments.get().length-1);const $=this._segments._prepareSegment(4*I,this.vertexArray.length,2*this._segmentToGroundQuads[L].length);let V;L!==this._segments.get().length-1&&(L++,this._segmentToGroundQuads[L]=[],this._segmentToRegionTriCounts[L]=[0,0,0,0,0]);{const X=h[0],re=h[1];V=eLe(X.sub(h[I-1])._perp()._unit(),re.sub(X)._perp()._unit())}for(let X=0;XT.region-I.region);for(let w=0;wV+X,0);let $=0;for(let V=0;V<=4;V++){const X=L[V];if(X!==0){let re=this.regionSegments[V];re||(re=this.regionSegments[V]=new jo);const oe={vertexOffset:I.vertexOffset,primitiveOffset:I.primitiveOffset+$,vertexLength:I.vertexLength,primitiveLength:X};re.get().push(oe)}$+=X}for(let V=0;V0?this.hiddenByLandmarkVertexBuffer=h.createVertexBuffer(this.hiddenByLandmarkVertexArray,bjt.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 h=0;h<=4;h++){const p=this.regionSegments[h];p&&p.destroy()}}}}class z${constructor(h){this.zoom=h.zoom,this.canonical=h.canonical,this.overscaling=h.overscaling,this.layers=h.layers,this.pixelRatio=h.pixelRatio,this.layerIds=this.layers.map(p=>p.fqid),this.index=h.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=h.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new Gl,this.footprintVertices=new Ra,this.footprintSegments=[],this.layoutVertexArray=new Vx,this.centroidVertexArray=new y$,this.wallVertexArray=new PD,this.indexArray=new Gl,this.programConfigurations=new Be(h.layers,{zoom:h.zoom,lut:h.lut},p=>kjt.includes(p)),this.segments=new jo,this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.groundEffect=new Lve(h),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=h.worldview,this.hasAppearances=null}updateFootprints(h,p){}updateAppearances(h,p,w,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(h,p,w,T){this.features=[],this.hasPattern=gve("fill-extrusion",this.layers,this.pixelRatio,p),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=nr(w),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:I,id:L,index:$,sourceLayerIndex:V}of h){const X=this.layers[0]._featureFilter.needGeometry,re=Fa(I,X);if(!this.layers[0]._featureFilter.filter(new ja(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),re,w))continue;const oe={id:L,sourceLayerIndex:V,index:$,geometry:X?re.geometry:zn(I,w,T),properties:I.properties,type:I.type,patterns:{}},le=this.layoutVertexArray.length,ge=Mve[oe.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:I.id,feature:yve("fill-extrusion",this.layers,oe,this.zoom,this.pixelRatio,p)});else if(this.wallMode)for(const _e of oe.geometry)for(const Te of QPe(_e,ge))this.addFeature(I.id,oe,[Te],$,w,{},p.availableImages,T,p.brightness);else this.addFeature(I.id,oe,oe.geometry,$,w,{},p.availableImages,T,p.brightness);p.featureIndex.insert(I,oe.geometry,$,V,this.index,le)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(h,p,w,T,I,L){for(const{featureId:$,feature:V}of this.features){const X=Mve[V.type]==="Polygon",{geometry:re}=V;if(this.wallMode)for(const oe of re)for(const le of QPe(oe,X))this.addFeature($,V,[le],V.index,p,w,T,I,L);else this.addFeature($,V,re,V.index,p,w,T,I,L)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(h,p,w,T,I,L,$){this.programConfigurations.updatePaintArrays(h,p,I,w,T,L,$,this.worldview),this.groundEffect.update(h,p,I,w,T,L,$,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(h){this.uploaded||(this.layoutVertexBuffer=h.createVertexBuffer(this.layoutVertexArray,wjt),this.indexBuffer=h.createIndexBuffer(this.indexArray),this.wallVertexBuffer=h.createVertexBuffer(this.wallVertexArray,vjt.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=h.createVertexBuffer(this.layoutVertexExtArray,_jt.members,!0)),this.groundEffect.upload(h)),this.groundEffect.uploadPaintProperties(h),this.programConfigurations.upload(h),this.uploaded=!0}uploadCentroid(h){this.groundEffect.uploadHiddenByLandmark(h),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=h.createVertexBuffer(this.centroidVertexArray,yjt.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(h,p,w,T,I,L,$,V,X){const re=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(p,{})/this.tileToMeter,oe=[new gs(0,0),new gs(Lr,Lr)],le=V.projection,ge=le.name==="globe",_e=this.wallMode||Mve[p.type]==="Polygon",Te=new Pve;Te.centroidDataIndex=this.centroidData.length;const Fe=new Ive;Fe.buildingId=h,p.properties&&p.properties.hasOwnProperty("building_id")&&(Fe.buildingId=Number(p.properties.building_id)),Te.buildingId=Fe.buildingId;const He=this.layers[0].paint.get("fill-extrusion-base").evaluate(p,{},I)<=0,ot=this.layers[0].paint.get("fill-extrusion-height").evaluate(p,{},I);let st;if(Fe.height=ot,Fe.vertexArrayOffset=this.layoutVertexArray.length,Fe.groundVertexArrayOffset=this.groundEffect.vertexArray.length,ge&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new MM),this.wallMode){if(ge)return void Kr("Non zero fill-extrusion-line-width is not yet supported on globe.");if(w.length!==1)return;st=function(Bt){const $t=Bt[0].x===Bt[Bt.length-1].x&&Bt[0].y===Bt[Bt.length-1].y;(function(Tr){let jr=0;const Xr=Tr.length;for(let ln=0;ln=0})(Bt)||(Bt=Bt.reverse());const Os={geometry:[],joinNormals:[],indices:[]},Hs=[],Qs=[],Gs=[];let hr=Bt.length;for(;hr>=2&&Bt[hr-1].equals(Bt[hr-2]);)hr--;if(hr<($t?3:2))return Os;let Ss,Zs,tr,mr,wr,tn=0;for(;tn0;let xn="miter";const va=2;xn==="miter"&&ln>va&&(xn="bevel"),xn==="bevel"&&(ln>100&&(xn="flipbevel"),ln{const Wi=new gs(ba.x,ba.y),Ci=new gs(ba.x,ba.y);Wi.x+=bi.x*Ll,Wi.y+=bi.y*Ll,Ci.x-=bi.x*Math.max(za,1),Ci.y-=bi.y*Math.max(za,1),Gs.push(bi),Hs.push(Wi),Qs.push(Ci)};if(xn==="miter")jr._mult(ln),xi(Ss,jr,0,0);else if(xn==="flipbevel")jr=wr.mult(-1),xi(Ss,jr,0,0),xi(Ss,jr.mult(-1),0,0);else{const ba=-Math.sqrt(ln*ln-1),bi=On?ba:0,za=On?0:ba;Zs&&xi(Ss,mr,bi,za),tr&&xi(Ss,wr,bi,za)}}Os.geometry=[...Hs,...Qs.reverse(),Hs[0]],Os.joinNormals=[...Gs,...Gs.reverse(),Gs[Gs.length-1]];const Mr=Os.geometry.length-1;for(let Tr=0;TrBt<($t.length-1)/2||Bt===$t.length-1,bt=this.wallMode?[w]:qD(w,500);for(let Bt=bt.length-1;Bt>=0;Bt--){const $t=bt[Bt];($t.length===0||Ijt($t[0]))&&bt.splice(Bt,1)}let wt;if(ge)wt=oLe(bt,oe,I);else{wt=[];for(const Bt of bt)wt.push({polygon:Bt,bounds:oe})}const Gt=_e?this.edgeRadius:0,Ot=Gt>0&&this.zoom<17,Ht=(Bt,$t)=>{if(Bt.length===0)return!1;const Es=Bt[Bt.length-1];return $t.x===Es.x&&$t.y===Es.y};for(const{polygon:Bt,bounds:$t}of wt){let Es=0,Os=0;for(const hr of Bt)_e&&!hr[0].equals(hr[hr.length-1])&&hr.push(hr[0]),Os+=_e?hr.length-1:hr.length;const Hs=this.segments.prepareSegment((_e?5:4)*Os,this.layoutVertexArray,this.indexArray);Fe.footprintSegIdx<0&&(Fe.footprintSegIdx=this.footprintSegments.length),Fe.polygonSegIdx<0&&(Fe.polygonSegIdx=this.polygonSegments.length);const Qs={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Gs=new JPe;if(Gs.vertexOffset=this.footprintVertices.length,Gs.indexOffset=3*this.footprintIndices.length,Gs.ringIndices=[],_e){const hr=[],Ss=[];Es=Hs.vertexLength;for(let tr=0;tr4&&nLe(Ss[Ss.length-2],Ss[0],Ss[1]),tr=Gt?Mjt(Ss[Ss.length-2],Ss[0],Ss[1],Gt):0;const mr=[];let wr,tn,Mr;tn=Ss[1].sub(Ss[0])._perp()._unit();let Tr=!0;for(let jr=1,Xr=0;jr0?1:0,bi=ln.dist(On);if(Xr+bi>32768&&(Xr=0),Gt){Mr=xn.sub(On)._perp()._unit();let Ci=sLe(ln,On,xn,tLe(tn,Mr),Gt);isNaN(Ci)&&(Ci=0);const So=On.sub(ln)._unit();ln=ln.add(So.mult(tr))._round(),On=On.add(So.mult(-Ci))._round(),tr=Ci,tn=Mr,He&&this.zoom>=17&&(Ht(mr,ln)||mr.push(ln),Ht(mr,On)||mr.push(On))}const za=Hs.vertexLength,Ll=Ss.length>4&&nLe(ln,On,xn);let Wi=aLe(Xr,Zs,Tr);if(WD(this.layoutVertexArray,ln.x,ln.y,xi,ba,0,0,Wi),WD(this.layoutVertexArray,ln.x,ln.y,xi,ba,0,1,Wi),this.wallMode){const Ci=mt(jr-1,Ss),So=st.joinNormals[jr-1];KD(this.wallVertexArray,So,Ci),KD(this.wallVertexArray,So,Ci)}if(Xr+=bi,Wi=aLe(Xr,Ll,!Tr),Zs=Ll,WD(this.layoutVertexArray,On.x,On.y,xi,ba,0,0,Wi),WD(this.layoutVertexArray,On.x,On.y,xi,ba,0,1,Wi),this.wallMode){const Ci=mt(jr,Ss),So=st.joinNormals[jr];KD(this.wallVertexArray,So,Ci),KD(this.wallVertexArray,So,Ci)}if(Hs.vertexLength+=4,this.indexArray.emplaceBack(za+0,za+1,za+2),this.indexArray.emplaceBack(za+1,za+3,za+2),Hs.primitiveLength+=2,Gt){const Ci=Es+(jr===1?Ss.length-2:jr-2),So=jr===1?Es:Ci+1;if(this.indexArray.emplaceBack(za+1,Ci,za+3),this.indexArray.emplaceBack(Ci,So,za+3),Hs.primitiveLength+=2,wr===void 0&&(wr=za),!Dve(xn,Ss[jr],$t)){const Sl=jr===Ss.length-1?wr:Hs.vertexLength;this.indexArray.emplaceBack(za+2,za+3,Sl),this.indexArray.emplaceBack(za+3,Sl+1,Sl),this.indexArray.emplaceBack(za+3,So,Sl+1),Hs.primitiveLength+=3}Tr=!Tr}if(ge){const Ci=this.layoutVertexExtArray,So=le.projectTilePoint(ln.x,ln.y,I),Sl=le.projectTilePoint(On.x,On.y,I),Dd=le.upVector(I,ln.x,ln.y),Cl=le.upVector(I,On.x,On.y);YD(Ci,So,Dd),YD(Ci,So,Dd),YD(Ci,Sl,Cl),YD(Ci,Sl,Cl)}}_e&&(Es+=Ss.length-1),He&&Gt&&this.zoom>=17&&(mr.length!==0&&Ht(mr,mr[0])&&mr.pop(),this.groundEffect.addData(mr,$t,re,Gt>0))}this.footprintSegments.push(Gs),Qs.triangleCount=this.indexArray.length-Qs.triangleArrayOffset,this.polygonSegments.push(Qs),++Fe.footprintSegLen,++Fe.polygonSegLen}if(Fe.vertexCount=this.layoutVertexArray.length-Fe.vertexArrayOffset,Fe.groundVertexCount=this.groundEffect.vertexArray.length-Fe.groundVertexArrayOffset,Fe.vertexCount!==0){if(Fe.centroidXY=Te.borders?R$:this.encodeCentroid(Te,Fe),p.properties&&p.properties.hasOwnProperty("building_id")){const Bt=Fe.buildingId;let $t=this.buildingGroups.get(Bt);$t||($t={accX:0,accY:0,accCount:0,mergedMin:new gs(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new gs(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Bt,$t)),$t.accX+=Te.acc.x,$t.accY+=Te.acc.y,$t.accCount+=Te.accCount,$t.mergedMin.x=Math.min($t.mergedMin.x,Fe.min.x),$t.mergedMin.y=Math.min($t.mergedMin.y,Fe.min.y),$t.mergedMax.x=Math.max($t.mergedMax.x,Fe.max.x),$t.mergedMax.y=Math.max($t.mergedMax.y,Fe.max.y),$t.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Fe),Te.borders){this.featuresOnBorder.push(Te);const Bt=this.featuresOnBorder.length-1;for(let $t=0;$tthis.featuresOnBorder[p].borders[h][0]-this.featuresOnBorder[w].borders[h][0])}splitToSubtiles(){const h=[];for(let $=0;$Lr),re=2*X+(+(V.min.x+V.max.x>Lr)^X);for(let oe=0;oe$.triangleSegmentIdx===V.triangleSegmentIdx?$.subtile-V.subtile:$.triangleSegmentIdx-V.triangleSegmentIdx);let w=0,T=0,I=0;for(const $ of h){if($.triangleSegmentIdx!==w)break;I++}const L=h.length;for(;T!==h.length;){w=h[T].triangleSegmentIdx;let $=0,V=T,X=T;for(let re=V;re0&&this.triangleSubSegments.push({segment:ge,min:oe,max:le}),V=X;for(let _e=V;_e[Te[0]*(1-He[0])+Fe[0]*He[0],Te[1]*(1-He[1])+Fe[1]*He[1]],ge=[],_e=[];for(const Te of this.triangleSubSegments){ge[0]=Te.min.x/Lr,ge[1]=Te.min.y/Lr,_e[0]=Te.max.x/Lr,_e[1]=Te.max.y/Lr;const Fe=le(re,oe,ge),He=le(re,oe,_e);if(new Xi([Fe[0],Fe[1],I],[He[0],He[1],L]).intersectsPrecise(w)===0){X&&(T.segments.push(X),X=void 0);continue}const ot=Te.segment;X&&X.vertexOffset!==ot.vertexOffset&&(T.segments.push(X),X=void 0),X?(X.vertexLength+=ot.vertexLength,X.primitiveLength+=ot.primitiveLength):X={vertexOffset:ot.vertexOffset,primitiveLength:ot.primitiveLength,vertexLength:ot.vertexLength,primitiveOffset:ot.primitiveOffset,sortKey:void 0,vaos:{}}}return X&&T.segments.push(X),T}encodeCentroid(h,p){const w=h.centroid(),T=p.span(),I=Math.min(7,Math.round(T.x*this.tileToMeter/10)),L=Math.min(6,Math.round(T.y*this.tileToMeter/10));return new gs(Ke(w.x,1,8191)<<3|I,Ke(w.y,1,8191)<<3|L)}encodeBorderCentroid(h){if(!h.borders)return new gs(0,0);const p=h.borders,w=Number.MAX_VALUE;if(p[0][0]!==w||p[1][0]!==w){const T=p[0][0]!==w?0:1;return new gs(6|(p[0][0]!==w?0:65528),(p[T][0]+p[T][1])/2<<3|6)}{const T=p[2][0]!==w?2:3;return new gs((p[T][0]+p[T][1])/2<<3|6,6|(p[2][0]!==w?0:65528))}}showCentroid(h){const p=this.centroidData[h.centroidDataIndex];if(p.flags&=oj,p.groupCentroidPos.x!==0||p.groupCentroidPos.y!==0){const w=p.span(),T=Math.min(7,Math.round(w.x*this.tileToMeter/10)),I=Math.min(6,Math.round(w.y*this.tileToMeter/10));p.centroidXY=new gs(Ke(p.groupCentroidPos.x,1,8191)<<3|T,Ke(p.groupCentroidPos.y,1,8191)<<3|I)}else p.centroidXY=new gs(0,0);this.writeCentroidToBuffer(p)}writeCentroidToBuffer(h){this.groundEffect.updateHiddenByLandmark(h);const p=h.vertexArrayOffset,w=h.vertexCount+h.vertexArrayOffset,T=-1073741824&h.flags?R$:h.centroidXY,I=this.centroidVertexArray.geta_centroid_pos0(p);if(this.centroidVertexArray.geta_centroid_pos1(p)!==T.y||I!==T.x){for(let L=p;LV.max.x||V.min.x>L.max.x||L.min.y>V.max.y||V.min.y>L.max.y||L.footprint.buildingIds.has(V.buildingId)&&(V.flags|=L.clipMask!==D$.None?-1073741824:oj);else for(const V of this.centroidData)if(!(V.flags&oj||V.flags&O$||L.min.x>V.max.x||V.min.x>L.max.x||L.min.y>V.max.y||V.min.y>L.max.y))for(let X=0;Xp!=ge>p&&h<(this.footprintVertices.int16[2*(re+L.vertexOffset)+0]-oe)*(p-le)/(ge-le)+oe&&(T=!T)}$=V}}return T}getHeightAtTileCoord(h,p){let w=Number.NEGATIVE_INFINITY,T=!0;const I=4*(h+Lr)*Lr+(p+Lr);if(this.partLookup.hasOwnProperty(I)){const L=this.partLookup[I];return L?{height:L.height,hidden:!!(L.flags&oj)}:void 0}for(const L of this.centroidData)h>L.max.x||L.min.x>h||p>L.max.y||L.min.y>p||L.height<=w||this.footprintContainsPoint(h,p,L)&&(w=L.height,this.partLookup[I]=L,T=!!(L.flags&oj));if(w!==Number.NEGATIVE_INFINITY)return{height:w,hidden:T};this.partLookup[I]=void 0}}function tLe(v,h){const p=v.add(h)._unit();return v.x*p.x+v.y*p.y}function Mjt(v,h,p,w){const T=h.sub(v)._perp()._unit(),I=p.sub(h)._perp()._unit();return sLe(v,h,p,tLe(T,I),w)}function sLe(v,h,p,w,T){const I=Math.sqrt(1-w*w);return Math.min(v.dist(h)/3,h.dist(p)/3,T*I/w)}function Dve(v,h,p){return v.xp[1].x&&h.x>p[1].x||v.yp[1].y&&h.y>p[1].y}function rLe(v,h){return v.xh[1].x||v.yh[1].y}function Ijt(v){return v.every(h=>h.x<=0)||v.every(h=>h.x>=Lr)||v.every(h=>h.y<=0)||v.every(h=>h.y>=Lr)}function nLe(v,h,p){if(v.x<0||v.x>=Lr||h.x<0||h.x>=Lr||p.x<0||p.x>=Lr)return!1;const w=p.sub(h),T=w.perp(),I=v.sub(h);return(w.x*I.x+w.y*I.y)/Math.sqrt((w.x*w.x+w.y*w.y)*(I.x*I.x+I.y*I.y))>-.866&&T.x*I.x+T.y*I.y<0}function aLe(v,h,p){const w=h?2|v:-3&v;return p?1|w:-2&w}function iLe(){const v=Math.PI/32,h=Math.tan(v),p=Vt;return p*Math.sqrt(1+2*h*h)-p}function oLe(v,h,p){const w=1<{for(const Ot of wt)_e.push({polygon:Ot,bounds:Gt})},Fe=Math.ceil(Math.log2(re)),He=Math.ceil(Math.log2(oe)),ot=Fe-He,st=[];for(let wt=0;wt0?0:1);for(let wt=0;wtGt+1?bt.push({polygons:Hs,bounds:Gs,depth:Gt+1}):Te(Hs,Gs)}if(Qs.length){const Gs=[new gs(Ot===0?Os:Ht.x,Ot===1?Os:Ht.y),Bt];st.length>Gt+1?bt.push({polygons:Qs,bounds:Gs,depth:Gt+1}):Te(Qs,Gs)}}return _e}(v,h,Math.ceil((I-T)/11.25),Math.ceil((L-$)/11.25),1,(V,X,re)=>{if(V===0)return .5*(X+re);{const oe=Ts((p.y+X/Lr)/w);return(lr(.5*(Ts((p.y+re/Lr)/w)+oe))*w-p.y)*Lr}})}function Pjt(v,h,p,w,T,I){const L=Math.pow(2,w.z-T.z);for(let $=0;$=V[L]&&($=h,V=v),$[L]T&&uLe($,V,L,T),$[L]I&&uLe(V,$,L,I)}}function B$(v,h,p,w,T,I){const L=[];for(let $=0;$=w&&_e.x>=w||(ge.x>=w?ge=new gs(w,ge.y+(w-ge.x)/(_e.x-ge.x)*(_e.y-ge.y))._round():_e.x>=w&&(_e=new gs(w,ge.y+(w-ge.x)/(_e.x-ge.x)*(_e.y-ge.y))._round()),ge.y>=T&&_e.y>=T||(ge.y>=T?ge=new gs(ge.x+(T-ge.y)/(_e.y-ge.y)*(_e.x-ge.x),T)._round():_e.y>=T&&(_e=new gs(ge.x+(T-ge.y)/(_e.y-ge.y)*(_e.x-ge.x),T)._round()),X&&ge.equals(X[X.length-1])||(X=[ge],L.push(X),I&&I.push({progress:{min:Fe+mLe(He,ot,ge)*Te,max:1},parentIndex:$,prevPoint:He,nextPoint:ot})),X.push(_e),I&&(I[I.length-1].progress.max=Fe+mLe(He,ot,_e)*Te,I[I.length-1].nextPoint=ot)))))}if(I&&oe>0)for(let le=re;leX.t-re.t);let L=0,$=0,V=[];for(w.push(V);L!==v.length;){if($===I.length){for(;L!==v.length;)V.length!==0&&V[V.length-1].equals(v[L])||V.push(v[L]),L++;break}I[$].t<=L?(V.length!==0&&V[V.length-1].equals(I[$].point)||V.push(I[$].point),Math.trunc(I[$].t),$++):(V.length!==0&&V[V.length-1].equals(v[L])||V.push(v[L]),L++)}}function mLe(v,h,p){return v.x!==h.x?(p.x-v.x)/(h.x-v.x):v.y!==h.y?(p.y-v.y)/(h.y-v.y):0}function ZD(v,h){return v.x*h.x+v.y*h.y}function fLe(v,h){if(v.length===1){let p=0;const w=h[p++];let T;for(;!T||w.equals(T);)if(T=h[p++],!T)return 1/0;for(;p{Os[0]=Hs,Os[1]=Qs,Os[2]=Gs,Os[3]=1},Es=iLe();ge>0&&(ge+=Es),_e+=Es;for(const Os of le){const Hs=[],Qs=[];for(const Gs of Os){const hr=Gs.x+Te.x,Ss=Gs.y+Te.y,Zs=oe.projection.projectTilePoint(hr,Ss,bt),tr=oe.projection.upVector(bt,Gs.x,Gs.y);let mr=ge,wr=_e;if(He){const tn=gLe(hr,Ss,ge,_e,He,ot,st,mt);mr+=tn.base,wr+=tn.top}ge!==0?$t(Ht,Zs.x+tr[0]*Ot*mr,Zs.y+tr[1]*Ot*mr,Zs.z+tr[2]*Ot*mr):$t(Ht,Zs.x,Zs.y,Zs.z),$t(Bt,Zs.x+tr[0]*Ot*wr,Zs.y+tr[1]*Ot*wr,Zs.z+tr[2]*Ot*wr),Qe(Ht,Ht,Fe),Qe(Bt,Bt,Fe),Hs.push(new tC(Ht[0],Ht[1],Ht[2])),Qs.push(new tC(Bt[0],Bt[1],Bt[2]))}wt.push(Hs),Gt.push(Qs)}return[wt,Gt]}(v,h,p,w,T,I,L,$,V,X,re):L?function(oe,le,ge,_e,Te,Fe,He,ot,st){const mt=[],bt=[],wt=[0,0,0,1];for(const Gt of oe){const Ot=[],Ht=[];for(const Bt of Gt){const $t=Bt.x+_e.x,Es=Bt.y+_e.y,Os=gLe($t,Es,le,ge,Fe,He,ot,st);wt[0]=$t,wt[1]=Es,wt[2]=Os.base,wt[3]=1,vt(wt,wt,Te),wt[3]=Math.max(wt[3],1e-5);const Hs=new tC(wt[0]/wt[3],wt[1]/wt[3],wt[2]/wt[3]);wt[0]=$t,wt[1]=Es,wt[2]=Os.top,wt[3]=1,vt(wt,wt,Te),wt[3]=Math.max(wt[3],1e-5);const Qs=new tC(wt[0]/wt[3],wt[1]/wt[3],wt[2]/wt[3]);Ot.push(Hs),Ht.push(Qs)}mt.push(Ot),bt.push(Ht)}return[mt,bt]}(h,p,w,T,I,L,$,V,X):function(oe,le,ge,_e,Te){const Fe=[],He=[],ot=Te[8]*le,st=Te[9]*le,mt=Te[10]*le,bt=Te[11]*le,wt=Te[8]*ge,Gt=Te[9]*ge,Ot=Te[10]*ge,Ht=Te[11]*ge;for(const Bt of oe){const $t=[],Es=[];for(const Os of Bt){const Hs=Os.x+_e.x,Qs=Os.y+_e.y,Gs=Te[0]*Hs+Te[4]*Qs+Te[12],hr=Te[1]*Hs+Te[5]*Qs+Te[13],Ss=Te[2]*Hs+Te[6]*Qs+Te[14],Zs=Te[3]*Hs+Te[7]*Qs+Te[15],tr=Gs+ot,mr=hr+st,wr=Ss+mt,tn=Math.max(Zs+bt,1e-5),Mr=Gs+wt,Tr=hr+Gt,jr=Ss+Ot,Xr=Math.max(Zs+Ht,1e-5);$t.push(new tC(tr/tn,mr/tn,wr/tn)),Es.push(new tC(Mr/Xr,Tr/Xr,jr/Xr))}Fe.push($t),He.push(Es)}return[Fe,He]}(h,p,w,T,I)}function gLe(v,h,p,w,T,I,L,$){const V=L*T.getElevationAt(v,h,!0,!0),X=I[0]!==0,re=X?I[1]===0?L*(I[0]/7-450):L*function(oe,le,ge){const _e=Math.floor(le[0]/8),Te=Math.floor(le[1]/8),Fe=10*(le[0]-8*_e),He=10*(le[1]-8*Te),ot=oe.getElevationAt(_e,Te,!0,!0),st=oe.getMeterToDEM(ge),mt=Math.floor(.5*(Fe*st-1)),bt=Math.floor(.5*(He*st-1)),wt=oe.tileCoordToPixel(_e,Te),Gt=2*mt+1,Ot=2*bt+1,Ht=function(Qs,Gs,hr,Ss,Zs){return[Qs.getElevationAtPixel(Gs,hr,!0),Qs.getElevationAtPixel(Gs+Zs,hr,!0),Qs.getElevationAtPixel(Gs,hr+Zs,!0),Qs.getElevationAtPixel(Gs+Ss,hr+Zs,!0)]}(oe,wt.x-mt,wt.y-bt,Gt,Ot),Bt=Math.abs(Ht[0]-Ht[1]),$t=Math.abs(Ht[2]-Ht[3]),Es=Math.abs(Ht[0]-Ht[2])+Math.abs(Ht[1]-Ht[3]),Os=Math.min(.25,.5*st*(Bt+$t)/Gt),Hs=Math.min(.25,.5*st*Es/Ot);return ot+Math.max(Os*Fe,Hs*He)}(T,I,$):V;return{base:V+(p===0?-1:p),top:X?Math.max(re+w,V+p+2):V+w}}const Rve=4096;class Djt{constructor(h){this.module=h,this.memoryStack=this.module.malloc(Rve),this.memoryStackNextFree=this.memoryStack}createIntArray(h){const p=this.memoryStackNextFree;return this.memoryStackNextFree+=h.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>Rve?-1:(new Int32Array(this.module.heap32.buffer,p,h.length).set(h),p)}createFloatArray(h){const p=this.memoryStackNextFree;return this.memoryStackNextFree+=h.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>Rve?-1:(new Float32Array(this.module.heapF32.buffer,p,h.length).set(h),p)}readStringBuffer(h){let p="";for(;this.module.heapU8[h]!==0;)p+=String.fromCharCode(this.module.heapU8[h]),++h;return p}setStyle(h){const p=h.normalScale;this.module.setStyle(p[0],p[1],p[2],h.tileToMeters)}setAOOptions(h,p){this.module.setAOOptions(h?1:0,p)}setMetricOptions(h,p){this.module.setMetricOptions(h?1:0,p)}setStructuralOptions(h){this.module.setStructuralOptions(h?1:0)}setFacadeOptions(h,p){this.module.setFacadeOptions(h,p?1:0)}setFauxFacadeOptions(h,p,w){this.module.setFauxFacadeOptions(h?1:0,p?1:0,w)}setFacadeClassifierOptions(h){this.module.setFacadeClassifierOptions(h)}generateMesh(h,p){this.memoryStackNextFree=this.memoryStack;for(const $ of h){const V=this.createIntArray($.ringIndices),X=this.createFloatArray($.coordinates);if(V===-1||X===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature($.id,$.sourceId,$.minHeight,$.height,$.roofType,X,V,$.ringIndices.length-1)}for(const $ of p){let V;V=$.entrances?JSON.parse($.entrances):[];const X=this.createFloatArray(V),re=this.createFloatArray($.coordinates);if(X===-1||re===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade($.sourceId,$.crossPerc,$.distanceToRoad,X,V.length,re,$.coordinates.length)}if(!this.module.generateMesh()){const $=this.module.getLastError();return this.readStringBuffer($)}const w=this.module.getMeshCount(),T=new Array(w);for(let $=0;$>2)-3,Fe=ge[_e++]>>2;if(_e++,T.json=JSON.parse(CLe.decode(ge.subarray(_e,_e+Fe))),_e+=Fe,_e>>0,Math.ceil(1.2*mt)),wt=Math.ceil((bt-mt)/65536);try{return Te.grow(wt),Fe(),!0}catch{return!1}},b:He}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(ge,ot):ge.then(st=>st.arrayBuffer()).then(st=>WebAssembly.instantiate(st,ot))).then(st=>{const{Rb:mt,Qb:bt,P:wt,T:Gt,X:Ot,Ja:Ht,La:Bt,Qa:$t,Va:Es,Wa:Os,eb:Hs,jb:Qs,f:Gs,e:hr,yb:Ss,zb:Zs,Ab:tr,Bb:mr,Db:wr,Gb:tn}=st.instance.exports;Te=hr;const Mr=(()=>{let Tr=0,jr=0,Xr=0,ln=0;return On=>{Xr&&(mt(ln),mt(Tr),jr+=Xr,Xr=Tr=0),Tr||(jr+=128,Tr=bt(jr));const xn=On.length+7&-8;let va=Tr;xn>=jr&&(Xr=xn,va=ln=bt(xn));for(let xi=0;xi{qv=ge,XD=void 0}))}()),le&&re.push(function(){if(Ove)return;const ge=function(_e){let Te;const Fe=WebAssembly.instantiateStreaming(_e,{}).then(st=>{Te=st.instance,Te.exports.__wasm_call_ctors()}),He={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},ot={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:Fe,supported:!0,decodeGltfBuffer(st,mt,bt,wt,Gt,Ot){(function(Ht,Bt,$t,Es,Os,Hs,Qs){const Gs=Ht.exports.sbrk,hr=Es+3&-4,Ss=Gs(hr*Os),Zs=Gs(Hs.length),tr=new Uint8Array(Ht.exports.memory.buffer);tr.set(Hs,Zs);const mr=Bt(Ss,Es,Os,Zs,Hs.length);if(mr===0&&Qs&&Qs(Ss,hr,Os),$t.set(tr.subarray(Ss,Ss+Es*Os)),Gs(Ss-Gs(0)),mr!==0)throw new Error(`Malformed buffer data: ${mr}`)})(Te,Te.exports[ot[Gt]],st,mt,bt,wt,Te.exports[He[Ot]])}}}(fetch(Ca()));return ge.ready.then(()=>{Ove=ge})}()),L)for(let ge=0;ge{const $=Z0(w,(V,X)=>{V?L(V):I(X)});T&&T.addEventListener("abort",()=>{$.cancel(),L(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:v,type:"arrayBuffer"},h);return ALe(p,0,v,h)}function zve(v){switch(v){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 Bve(v){switch(v){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 Mb{constructor(h,p,w,T){this.context=h,this.format=w,this.useMipmap=T&&T.useMipmap,this.texture=h.gl.createTexture(),this.update(p,{premultiply:T&&T.premultiply})}update(h,p){const w=h&&h instanceof HTMLVideoElement&&h.width===0?h.videoWidth:h.width,T=h&&h instanceof HTMLVideoElement&&h.height===0?h.videoHeight:h.height,{context:I}=this,{gl:L}=I,{x:$,y:V}=p&&p.position?p.position:{x:0,y:0},X=$+w,re=V+T;this.size&&(this.size[0]!==X||this.size[1]!==re)&&(!p||p.recreateWhenResize===void 0||p.recreateWhenResize)&&(L.bindTexture(L.TEXTURE_2D,null),L.deleteTexture(this.texture),this.texture=L.createTexture(),this.size=null),L.bindTexture(L.TEXTURE_2D,this.texture),I.pixelStoreUnpackFlipY.set(!1),I.pixelStoreUnpack.set(1),I.pixelStoreUnpackPremultiplyAlpha.set(this.format===L.RGBA8&&(!p||p.premultiply!==!1));const oe=h instanceof HTMLImageElement||h instanceof HTMLCanvasElement||h instanceof HTMLVideoElement||h instanceof ImageData||ImageBitmap&&h instanceof ImageBitmap;if(!this.size&&X>0&&re>0){const le=this.useMipmap?Math.floor(Math.log2(Math.max(X,re)))+1:1;L.texStorage2D(L.TEXTURE_2D,le,this.format,X,re),this.size=[X,re]}this.size&&(oe?L.texSubImage2D(L.TEXTURE_2D,0,$,V,zve(this.format),Bve(this.format),h):"data"in h&&h.data&&L.texSubImage2D(L.TEXTURE_2D,0,$,V,w,T,zve(this.format),Bve(this.format),h.data)),this.useMipmap&&L.generateMipmap(L.TEXTURE_2D)}bind(h,p,w=!1){const{context:T}=this,{gl:I}=T;I.bindTexture(I.TEXTURE_2D,this.texture),h!==this.minFilter&&(I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MAG_FILTER,h),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MIN_FILTER,this.useMipmap&&!w?h===I.NEAREST?I.NEAREST_MIPMAP_NEAREST:I.LINEAR_MIPMAP_LINEAR:h),this.minFilter=h),p!==this.wrapS&&(I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_S,p),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_T,p),this.wrapS=p)}bindExtraParam(h,p,w,T,I){const{context:L}=this,{gl:$}=L;$.bindTexture($.TEXTURE_2D,this.texture),p!==this.magFilter&&($.texParameteri($.TEXTURE_2D,$.TEXTURE_MAG_FILTER,p),this.magFilter=p),h!==this.minFilter&&($.texParameteri($.TEXTURE_2D,$.TEXTURE_MIN_FILTER,this.useMipmap?h===$.NEAREST?$.NEAREST_MIPMAP_NEAREST:$.LINEAR_MIPMAP_LINEAR:h),this.minFilter=h),w!==this.wrapS&&($.texParameteri($.TEXTURE_2D,$.TEXTURE_WRAP_S,w),this.wrapS=w),T!==this.wrapT&&($.texParameteri($.TEXTURE_2D,$.TEXTURE_WRAP_T,T),this.wrapT=T),I!==this.compareMode&&(I?($.texParameteri($.TEXTURE_2D,$.TEXTURE_COMPARE_MODE,$.COMPARE_REF_TO_TEXTURE),$.texParameteri($.TEXTURE_2D,$.TEXTURE_COMPARE_FUNC,I)):$.texParameteri($.TEXTURE_2D,$.TEXTURE_COMPARE_MODE,$.NONE),this.compareMode=I)}destroy(){const{gl:h}=this.context;h.deleteTexture(this.texture),this.texture=null}}class JD{constructor(h,p){this.context=h,this.texture=p}bind(h,p){const{context:w}=this,{gl:T}=w;T.bindTexture(T.TEXTURE_2D,this.texture),h!==this.minFilter&&(T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MAG_FILTER,h),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MIN_FILTER,h),this.minFilter=h),p!==this.wrapS&&(T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_S,p),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_T,p),this.wrapS=p)}}const Ujt=rr([{name:"a_pos_3f",components:3,type:"Float32"}]),qjt=rr([{name:"a_color_3f",components:3,type:"Float32"}]),Vjt=rr([{name:"a_color_4f",components:4,type:"Float32"}]),Hjt=rr([{name:"a_uv_2f",components:2,type:"Float32"}]),Gjt=rr([{name:"a_normal_3f",components:3,type:"Float32"}]),Wjt=rr([{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"}]),Kjt=rr([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function ILe(v,h){const p=V$(v.projection,v.zoom,v.width,v.height),w=function(I,L,$,V,X){const re=new Zt($.lng-180*SN,$.lat),oe=new Zt($.lng+180*SN,$.lat),le=I.project(re.lng,re.lat),ge=I.project(oe.lng,oe.lat),_e=-Math.atan2(ge.y-le.y,ge.x-le.x),Te=on.fromLngLat($);Te.y=Ke(Te.y,-1+SN,1-SN);const Fe=Te.toLngLat(),He=I.project(Fe.lng,Fe.lat),ot=on.fromLngLat(Fe);ot.x+=SN;const st=ot.toLngLat(),mt=I.project(st.lng,st.lat),bt=LLe(mt.x-He.x,mt.y-He.y,_e),wt=on.fromLngLat(Fe);wt.y+=SN;const Gt=wt.toLngLat(),Ot=I.project(Gt.lng,Gt.lat),Ht=LLe(Ot.x-He.x,Ot.y-He.y,_e),Bt=Math.abs(bt.x)/Math.abs(Ht.y),$t=b([]);R($t,$t,-_e*(1-(X?0:V)));const Es=b([]);return A(Es,Es,[1,1-(1-Bt)*V,1]),Es[4]=-Ht.x/Ht.y*V,R(Es,Es,_e),N(Es,$t,Es),Es}(v.projection,0,v.center,p,h),T=PLe(v);return A(w,w,[T,T,1]),w}function PLe(v){const h=v.projection,p=V$(v.projection,v.zoom,v.width,v.height),w=$ve(h,v.center),T=$ve(h,Zt.convert(h.center));return Math.pow(2,w*p+(1-p)*T)}function V$(v,h,p,w,T=1/0){const I=v.range;if(!I)return 0;const L=Math.min(T,Math.max(p,w)),$=Math.log2(L/1024);return at(I[0]+$,I[1]+$,h)}const SN=1/4e4;function $ve(v,h){const p=Ke(h.lat,-85.051129,qs),w=new Zt(h.lng-180*SN,p),T=new Zt(h.lng+180*SN,p),I=v.project(w.lng,p),L=v.project(T.lng,p),$=on.fromLngLat(w),V=on.fromLngLat(T),X=L.x-I.x,re=L.y-I.y,oe=V.x-$.x,le=V.y-$.y,ge=Math.sqrt((oe*oe+le*le)/(X*X+re*re));return Math.log2(ge)}function LLe(v,h,p){const w=Math.cos(p),T=Math.sin(p);return{x:v*w-h*T,y:v*T+h*w}}function DLe(v,h,p){b(v),R(v,v,ps(h[2])),E(v,v,ps(h[0])),D(v,v,ps(h[1])),A(v,v,p),N(v,v,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function H$(v,h,p,w,T,I,L,$){const V=[p[0]-h[0],p[1]-h[1],0],X=[w[0]-h[0],w[1]-h[1],0];if(te(V)<1e-12||te(X)<1e-12)return St(v);const re=$e([],V,X);Ve(re,re),me(X,w,h),V[2]=(I-T)*$,X[2]=(L-T)*$;const oe=V;return $e(oe,V,X),Ve(oe,oe),Ut(v,re,oe)}function G$(v,h,p=!1){const w=aj(h.zoom),T=function(I,L,$){const V=L.worldSize,X=[I[12],I[13],I[14]],re=Ts(X[1]/V),oe=ss(X[0]/V),le=b([]),ge=hs(1,re)*V,_e=hs(1,0)*V*br(re,L.zoom),Te=1/hve(V);let Fe=_e*Te;if($){const mt=V$(L.projection,L.zoom,L.width,L.height,1024);Fe=Te*L.projection.pixelSpaceConversion(L.center.lat,V,mt)}const He=Lt(re,oe);ue(He,He,xe([],Ve([],He),ge*Fe*X[2]));const ot=function(mt){const bt=[mt[0],mt[1],mt[2]];let wt=[0,1,0];const Gt=$e([],wt,bt);return $e(wt,bt,Gt),Ie(wt)===0&&(wt=[0,1,0],$e(Gt,bt,wt)),Ve(Gt,Gt),Ve(wt,wt),Ve(bt,bt),[Gt[0],Gt[1],Gt[2],0,wt[0],wt[1],wt[2],0,bt[0],bt[1],bt[2],0,mt[0],mt[1],mt[2],1]}(He);A(le,le,[Fe,Fe,Fe*ge]),C(le,le,[-X[0],-X[1],-X[2]]);const st=N([],L.globeMatrix,ot);return N(st,st,le),N(st,st,I),st}(v,h,p);if(w>0){const I=function(L,$){const V=$.worldSize,X=hs(1,0)*V*br($.center.lat,$.zoom)/hve(V),re=hs(1,$.center.lat)*V,oe=b([]);D(oe,oe,ps($.center.lng)),E(oe,oe,ps($.center.lat)),C(oe,oe,[0,0,Tt]),A(oe,oe,[X,X,X*re]);const le=$.point;return C(oe,oe,[-le.x,-le.y,0]),N(oe,oe,L),N(oe,$.globeMatrix,oe)}(v,h);return function(L,$,V){const X=(_e,Te,Fe)=>{const He=te(_e),ot=te(Te),st=nj(_e,Te,Fe);return xe(st,st,1/te(st)*An(He,ot,Fe))},re=X([L[0],L[1],L[2]],[$[0],$[1],$[2]],V),oe=X([L[4],L[5],L[6]],[$[4],$[5],$[6]],V),le=X([L[8],L[9],L[10]],[$[8],$[9],$[10]],V),ge=nj([L[12],L[13],L[14]],[$[12],$[13],$[14]],V);return[re[0],re[1],re[2],0,oe[0],oe[1],oe[2],0,le[0],le[1],le[2],0,ge[0],ge[1],ge[2],1]}(T,I,w)}return T}function Uve(v,h,p,w){const T=Xi.projectAabbCorners(w,p);let I=Number.MAX_VALUE;for(let $=0;$0||Fe===0&&_e[0]*Te[0]+_e[1]*Te[1]>=0&&_e[0]*_e[0]+_e[1]*_e[1]>Te[0]*Te[0]+Te[1]*Te[1])&&(re=ge)}oe=re}while(oe!==X);return V.length>0&&V.push(V[0]),V}(T);if(tc(v,L))return I}const sC=64,WM={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function W$(v,h,p,w,T,I,L,$,V,X=!1){const re=p.zoom,oe=p.project(w),le=br(w.lat,re),ge=1/le;b(v),C(v,v,[oe.x+L[0]*ge,oe.y+L[1]*ge,L[2]]);let _e=1,Te=1;const Fe=p.worldSize;if(X){if(p.projection.name==="mercator"){let mt=0;p.elevation&&(mt=p.elevation.getAtPointOrZero(new on(oe.x/Fe,oe.y/Fe),0));const bt=vt([],[oe.x,oe.y,mt,1],p.projMatrix)[3]/p.cameraToCenterDistance;_e=bt,Te=bt*br(p.center.lat,re)}else if(p.projection.name==="globe"){const mt=G$(v,p),bt=[0,0,0,1];vt(bt,bt,N([],p.projMatrix,mt));const wt=bt[3]/p.cameraToCenterDistance,Gt=aj(re),Ot=p.projection.pixelsPerMeter(w.lat,Fe)*br(w.lat,re),Ht=p.projection.pixelsPerMeter(p.center.lat,Fe)*br(p.center.lat,re);_e=wt/An(Ot,Cr(p.center.lat),Gt),Te=wt*le/Ot,_e*=Ht,Te*=Ht}}else _e=ge;A(v,v,[_e,_e,Te]);const He=[...v],ot=h.orientation,st=[];if(DLe(st,[ot[0]+(T?T[0]:0),ot[1]+(T?T[1]:0),ot[2]+(T?T[2]:0)],I),N(v,He,st),$&&p.elevation){let mt=0;const bt=[];if(V&&p.elevation){mt=function(Gt,Ot,Ht,Bt,$t){const Es=Ot.elevation;if(!Es)return 0;const Os=Xi.projectAabbCorners(Ht,Bt),Hs=hs(1,$t.lat)*Ot.worldSize,Qs=function(jr,Xr){const ln=[0,0,1],On=[{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 xn of On){const va=jr[xn.corners[0]],xi=jr[xn.corners[1]],ba=jr[xn.corners[2]],bi=[xi[0]-va[0],xi[1]-va[1],Xr*(xi[2]-va[2])],za=$e(bi,bi,[ba[0]-va[0],ba[1]-va[1],Xr*(ba[2]-va[2])]);Ve(za,za),xn.dotProductWithUp=Le(za,ln)}return On.sort((xn,va)=>xn.dotProductWithUp-va.dotProductWithUp),On[0].corners}(Os,Hs),Gs=Os[Qs[0]],hr=Os[Qs[1]],Ss=Os[Qs[2]],Zs=Os[Qs[3]],tr=Es.getAtPointOrZero(new on(Gs[0]/Ot.worldSize,Gs[1]/Ot.worldSize),0),mr=Es.getAtPointOrZero(new on(hr[0]/Ot.worldSize,hr[1]/Ot.worldSize),0),wr=Es.getAtPointOrZero(new on(Ss[0]/Ot.worldSize,Ss[1]/Ot.worldSize),0),tn=Es.getAtPointOrZero(new on(Zs[0]/Ot.worldSize,Zs[1]/Ot.worldSize),0),Mr=(tr+tn)/2,Tr=(mr+wr)/2;return Mr>Tr?mr=h.gl.NEAREST_MIPMAP_NEAREST}),v.uploaded=!0,v.image=null)}function Yjt(v,h,p){v.indexBuffer=h.createIndexBuffer(v.indexArray,!1,!0),v.vertexBuffer=h.createVertexBuffer(v.vertexArray,Ujt.members,!1,!0),v.normalArray&&(v.normalBuffer=h.createVertexBuffer(v.normalArray,Gjt.members,!1,!0)),v.texcoordArray&&(v.texcoordBuffer=h.createVertexBuffer(v.texcoordArray,Hjt.members,!1,!0)),v.colorArray&&(v.colorBuffer=h.createVertexBuffer(v.colorArray,(v.colorArray.bytesPerElement===12?qjt:Vjt).members,!1,!0)),v.featureArray&&(v.pbrBuffer=h.createVertexBuffer(v.featureArray,Kjt.members,!0)),v.segments=jo.simpleSegment(0,0,v.vertexArray.length,v.indexArray.length);const w=v.material;w.pbrMetallicRoughness.baseColorTexture&&eR(w.pbrMetallicRoughness.baseColorTexture,h),w.pbrMetallicRoughness.metallicRoughnessTexture&&eR(w.pbrMetallicRoughness.metallicRoughnessTexture,h),w.normalTexture&&eR(w.normalTexture,h),w.occlusionTexture&&eR(w.occlusionTexture,h,p),w.emissionTexture&&eR(w.emissionTexture,h)}function qve(v,h,p){if(v.meshes)for(const w of v.meshes)Yjt(w,h,p);if(v.children)for(const w of v.children)qve(w,h,p)}function K$(v){if(v.meshes)for(const h of v.meshes)h.indexArray.destroy(),h.vertexArray.destroy(),h.colorArray&&h.colorArray.destroy(),h.normalArray&&h.normalArray.destroy(),h.texcoordArray&&h.texcoordArray.destroy(),h.featureArray&&h.featureArray.destroy();if(v.children)for(const h of v.children)K$(h)}function Zjt(v){v.pbrMetallicRoughness.baseColorTexture&&v.pbrMetallicRoughness.baseColorTexture.gfxTexture&&v.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),v.pbrMetallicRoughness.metallicRoughnessTexture&&v.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&v.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),v.normalTexture&&v.normalTexture.gfxTexture&&v.normalTexture.gfxTexture.destroy(),v.emissionTexture&&v.emissionTexture.gfxTexture&&v.emissionTexture.gfxTexture.destroy(),v.occlusionTexture&&v.occlusionTexture.gfxTexture&&v.occlusionTexture.gfxTexture.destroy()}function Vve(v){if(v.meshes)for(const h of v.meshes)h.vertexBuffer&&(h.vertexBuffer.destroy(),h.indexBuffer.destroy(),h.normalBuffer&&h.normalBuffer.destroy(),h.texcoordBuffer&&h.texcoordBuffer.destroy(),h.colorBuffer&&h.colorBuffer.destroy(),h.pbrBuffer&&h.pbrBuffer.destroy(),h.segments.destroy(),h.material&&Zjt(h.material));if(v.footprintDebugMesh&&(v.footprintDebugMesh.vertexBuffer.destroy(),v.footprintDebugMesh.indexBuffer.destroy(),v.footprintDebugMesh.segments.destroy()),v.children)for(const h of v.children)Vve(h)}function rC(v,h){const p=v.json.bufferViews[h.bufferView],w=U$[h.componentType];return new w(v.buffers[p.buffer],(h.byteOffset||0)+(p.byteOffset||0),h.count*(p.byteStride&&p.byteStride!==QD[h.type]*w.BYTES_PER_ELEMENT?p.byteStride/w.BYTES_PER_ELEMENT:QD[h.type]))}function Hve(v,h,p,w){const T=U$[h.componentType],I=function(re){switch(re){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(T),L=v.json.bufferViews[h.bufferView],$=L.byteStride?L.byteStride/T.BYTES_PER_ELEMENT:QD[h.type],V=p.float32,X=V.length/p.capacity;for(let re=0,oe=0;re0){for(let Fe=0;Fe0){I.texcoordArray=new ej;const le=h.json.accessors[T.TEXCOORD_0];I.texcoordArray.resize(le.count);const ge=rC(h,le);Hve(h,le,I.texcoordArray,ge)}if(T._FEATURE_ID_RGBA4444!==void 0){const le=h.json.accessors[T._FEATURE_ID_RGBA4444];h.json.extensionsUsed&&h.json.extensionsUsed.includes("EXT_meshopt_compression")&&(I.featureData=rC(h,le))}T._FEATURE_RGBA4444!==void 0&&(I.featureData=new Uint32Array(rC(h,h.json.accessors[T._FEATURE_RGBA4444]).buffer));const oe=v.material;return I.material=function(le,ge){const{emissiveFactor:_e=[0,0,0],alphaMode:Te="OPAQUE",alphaCutoff:Fe=.5,normalTexture:He,occlusionTexture:ot,emissiveTexture:st,doubleSided:mt,name:bt}=le,{baseColorFactor:wt=[1,1,1,1],metallicFactor:Gt=1,roughnessFactor:Ot=1,baseColorTexture:Ht,metallicRoughnessTexture:Bt}=le.pbrMetallicRoughness||{},$t=ot?ge[ot.index]:void 0;if(ot&&ot.extensions&&ot.extensions.KHR_texture_transform&&$t){const Es=ot.extensions.KHR_texture_transform;$t.offsetScale=[Es.offset[0],Es.offset[1],Es.scale[0],Es.scale[1]]}return{name:bt,pbrMetallicRoughness:{baseColorFactor:new Vr(...wt),metallicFactor:Gt,roughnessFactor:Ot,baseColorTexture:Ht?ge[Ht.index]:void 0,metallicRoughnessTexture:Bt?ge[Bt.index]:void 0},doubleSided:mt,emissiveFactor:new Vr(..._e),alphaMode:Te,alphaCutoff:Fe,normalTexture:He?ge[He.index]:void 0,occlusionTexture:$t,emissionTexture:st?ge[st.index]:void 0,defined:le.defined===void 0}}(oe!==void 0?h.json.materials[oe]:{defined:!1},p),I}function OLe(v,h,p){const{matrix:w,rotation:T,translation:I,scale:L,mesh:$,extras:V,children:X,name:re}=v,oe={};if(oe.name=re,oe.localMatrix=w||function(le,ge,_e,Te){var Fe=ge[0],He=ge[1],ot=ge[2],st=ge[3],mt=Fe+Fe,bt=He+He,wt=ot+ot,Gt=Fe*mt,Ot=Fe*bt,Ht=Fe*wt,Bt=He*bt,$t=He*wt,Es=ot*wt,Os=st*mt,Hs=st*bt,Qs=st*wt,Gs=Te[0],hr=Te[1],Ss=Te[2];return le[0]=(1-(Bt+Es))*Gs,le[1]=(Ot+Qs)*Gs,le[2]=(Ht-Hs)*Gs,le[3]=0,le[4]=(Ot-Qs)*hr,le[5]=(1-(Gt+Es))*hr,le[6]=($t+Os)*hr,le[7]=0,le[8]=(Ht+Hs)*Ss,le[9]=($t-Os)*Ss,le[10]=(1-(Gt+Bt))*Ss,le[11]=0,le[12]=_e[0],le[13]=_e[1],le[14]=_e[2],le[15]=1,le}([],T||[0,0,0,1],I||[0,0,0],L||[1,1,1]),oe.globalMatrix=_(oe.localMatrix),$!==void 0){oe.meshes=p[$];const le=oe.anchor=[0,0];for(const ge of oe.meshes){const{min:_e,max:Te}=ge.aabb;le[0]+=_e[0]+Te[0],le[1]+=_e[1]+Te[1]}le[0]=Math.floor(le[0]/oe.meshes.length/2),le[1]=Math.floor(le[1]/oe.meshes.length/2)}if(V&&(V.id&&(oe.id=V.id),V.lights&&(oe.lights=function(le){if(!le.length)return[];const ge=function(ot){const st=atob(ot),mt=new Uint8Array(st.length);for(let bt=0;bt1&&w[w.length-1].equals(w[0])&&w.pop();let T=0;for(let L=0;L0&&w.reverse();const I=UM(w.flatMap(L=>[L.x,L.y]),[]);return I.length===0?null:{vertices:w,indices:I}}function e2t(v,h){const p=[],w=[];let T=0;const I=[];for(const L of v){T=p.length;const $=L.vertexArray.float32,V=L.indexArray.uint16;for(let X=0;X0&&([w[L+1],w[L+2]]=[w[L+2],w[L+1]])}return{vertices:p,indices:w}}function Gve(v){const h=function(V,X){const re=[],oe=WebGL2RenderingContext;if(V.json.textures)for(const le of V.json.textures){const ge={magFilter:oe.LINEAR,minFilter:oe.NEAREST,wrapS:oe.REPEAT,wrapT:oe.REPEAT};le.sampler!==void 0&&Object.assign(ge,V.json.samplers[le.sampler]),re.push({image:X[le.source],sampler:ge,uploaded:!1})}return re}(v,v.images),p=function(V,X){const re=[];for(const oe of V.json.meshes){const le=[];for(const ge of oe.primitives)le.push(Xjt(ge,V,X));re.push(le)}return re}(v,h),{scenes:w,scene:T,nodes:I}=v.json,L=w?w[T||0].nodes:[...I.keys()],$=[];for(const V of L)$.push(OLe(I[V],v,p));return function(V,X,re){const oe={},le=new Set;for(let ge=0;ge0){const ge=Array.from(le.values()).sort((_e,Te)=>_e-Te);for(let _e=ge.length-1;_e>=0;_e--)V.splice(ge[_e],1)}}($,L,v.json.nodes),$}function t2t(v){v.heightmap=new Float32Array(4096),v.heightmap.fill(-1);const h=v.vertexArray.float32,p=v.aabb.min[0]-1,w=v.aabb.min[1]-1,T=sC/(v.aabb.max[0]-p+2),I=sC/(v.aabb.max[1]-w+2);for(let L=0;Lv.heightmap[X*sC+V]&&(v.heightmap[X*sC+V]=$)}}function FLe(v,h,p,w,T){p.reserve(p.length+4*v.length),w.reserve(w.length+10*v.length),T.reserve(T.length+10*v.length);let I=w.length;for(const L of v){const $=Math.min(10,Math.max(4,1.3*L.height))*h,V=[-L.normal[1],L.normal[0],0],X=Math.min(.29,.1*L.width/L.depth),re=L.width-2*L.depth*h*(X+.01),oe=Ee([],L.pos,V,re/2),le=Ee([],L.pos,V,-re/2),ge=[oe[0],oe[1],oe[2]+L.height],_e=[le[0],le[1],le[2]+L.height],Te=Ee([],L.normal,V,X);xe(Te,Te,$);const Fe=Ee([],L.normal,V,-X);xe(Fe,Fe,$),ue(Te,oe,Te),ue(Fe,le,Fe),oe[2]+=.1,le[2]+=.1,w.emplaceBack(Te[0],Te[1],Te[2]),w.emplaceBack(Fe[0],Fe[1],Fe[2]),w.emplaceBack(oe[0],oe[1],oe[2]),w.emplaceBack(le[0],le[1],le[2]),w.emplaceBack(ge[0],ge[1],ge[2]),w.emplaceBack(_e[0],_e[1],_e[2]),w.emplaceBack(oe[0],oe[1],oe[2]),w.emplaceBack(le[0],le[1],le[2]),w.emplaceBack(Te[0],Te[1],Te[2]),w.emplaceBack(Fe[0],Fe[1],Fe[2]);const He=re/$/2;T.emplaceBack(-He-X,-1,He,.8),T.emplaceBack(He+X,-1,He,.8),T.emplaceBack(-He,0,He,1.3),T.emplaceBack(He,0,He,1.3),T.emplaceBack(He+X,-.8,He,.7),T.emplaceBack(He+X,-.8,He,.7),T.emplaceBack(0,0,He,1.3),T.emplaceBack(0,0,He,1.3),T.emplaceBack(He+X,-1.2,He,.8),T.emplaceBack(He+X,-1.2,He,.8),p.emplaceBack(6+I,4+I,8+I),p.emplaceBack(7+I,9+I,5+I),p.emplaceBack(0+I,1+I,2+I),p.emplaceBack(1+I,3+I,2+I),I+=10}}function s2t(v,h){const p={};p.indexArray=new Gl,p.vertexArray=new Hx,p.colorArray=new $v,FLe(v,h,p.indexArray,p.vertexArray,p.colorArray);const w={defined:!0};w.emissiveFactor=Vr.black;const T={};return T.baseColorFactor=Vr.white,w.pbrMetallicRoughness=T,p.material=w,p.aabb=new Xi([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),p}const zLe=rr([{name:"a_pos_3f",components:3,type:"Float32"}]),r2t=rr([{name:"a_normal_3",components:3,type:"Int16"}]),n2t=rr([{name:"a_centroid_3",components:3,type:"Int16"}]),BLe=rr([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),a2t=rr([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),i2t=rr([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),o2t=rr([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),l2t=rr([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),c2t=rr([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),$Le=ia.types,Y$=32767;function d2t(v,h){const p=Lr+h;for(const w of v)for(const T of w)if(T.x<-h||T.x>p||T.y<-h||T.y>p)return!1;return!0}function u2t(v){switch(v){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: ${v}`)}}class Wve{constructor(){this.layoutVertexArray=new Hx,this.layoutAttenuationArray=new $v,this.layoutColorArray=new Gx,this.indexArray=new Gl,this.indexArrayForConflation=new Gl,this.segmentsBucket=new jo}}class Kve{constructor(h){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new jo,this.entranceBloom=new Wve;const p=66560;this.layoutVertexArray=new Hx,this.layoutVertexArray.reserve(p),this.layoutNormalArray=new Ai,this.layoutNormalArray.reserve(p),this.layoutCentroidArray=new Ai,this.layoutCentroidArray.reserve(p),this.layoutColorArray=new Gx,this.layoutColorArray.reserve(p),this.layoutFloodLightDataArray=new RM,this.layoutFloodLightDataArray.reserve(p),this.layoutAOArray=new OM,this.layoutAOArray.reserve(p),this.indexArray=new Gl,this.indexArray.reserve(66560),this.indexArrayForConflation=new Gl,this.segmentsBucket=new jo,this.entranceBloom=new Wve,h&&(this.layoutFacadePaintArray=new Gx,this.layoutFacadeDataArray=new vN,this.layoutFacadeVerticalRangeArray=new Gx)}reserve(h,p,w){this.layoutVertexArray.reserveForAdditional(h),this.layoutCentroidArray.reserveForAdditional(h),this.layoutFloodLightDataArray.reserveForAdditional(h),this.layoutNormalArray.reserveForAdditional(h),this.layoutAOArray.reserveForAdditional(h),this.layoutColorArray.reserveForAdditional(h),this.indexArray.reserveForAdditional(p),w&&(this.layoutFacadePaintArray.reserveForAdditional(h),this.layoutFacadeDataArray.reserveForAdditional(h),this.layoutFacadeVerticalRangeArray.reserveForAdditional(h))}}class ULe{constructor(h){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new ej,this.footprintsIndices=new tj,this.footprintsMin=new gs(1/0,1/0),this.footprintsMax=new gs(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new Kve(!1),this.buildingWithFacade=new Kve(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=h.zoom,this.canonical=h.canonical,this.layers=h.layers,this.layerIds=this.layers.map(p=>p.fqid),this.index=h.index,this.hasPattern=!1,this.worldview=h.worldview,this.lut=h.lut,this.programConfigurations=new Be(h.layers,{zoom:h.zoom,lut:h.lut}),this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.projection=h.projection,this.groundEffect=new Lve(h),this.groundEffect.groundRadiusArray=new eo,this.hasAppearances=null}updateFootprints(h,p){const w=new I$([],[],1),T={vertices:[],indices:new Uint32Array(0),grid:w,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};p.push({footprint:T,id:h})}updateAppearances(h,p,w,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if($$!=null||yLe!=null)return null;if(GM!=null)return GM;const h=fetch(Ji());return GM=function(p){let w,T,I,L,$;function V(){w=new Uint8Array($.buffer),T=new Int16Array($.buffer),I=new Int32Array($.buffer),L=new Float32Array($.buffer)}function X(){throw new Error("Unexpected BuildingGen error.")}const re=()=>{},oe={a:{a:X,f:function(le){const ge=w.length,_e=Math.max(le>>>0,Math.ceil(1.2*ge)),Te=Math.ceil((_e-ge)/65536);try{return $.grow(Te),V(),!0}catch{return!1}},g:X,b:re,c:re,d:re,e:re}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(p,oe):p.then(le=>le.arrayBuffer()).then(le=>WebAssembly.instantiate(le,oe))).then(le=>{const ge=le.instance.exports;return(0,ge.g)(),$=ge.f,V(),new Djt({setStyle:ge.h,setAOOptions:ge.i,setMetricOptions:ge.j,setStructuralOptions:ge.k,setFacadeOptions:ge.l,setFauxFacadeOptions:ge.m,setFacadeClassifierOptions:ge.n,addFeature:ge.o,addFacade:ge.p,generateMesh:ge.q,getLastError:ge.r,getOuterRingLength:ge.s,getMeshCount:ge.t,getPositionsPtr:ge.u,getPositionsLength:ge.v,getNormalsPtr:ge.w,getNormalsLength:ge.x,getAOPtr:ge.y,getAOLength:ge.z,getUVPtr:ge.A,getUVLength:ge.B,getFauxFacadePtr:ge.C,getFauxFacadeLength:ge.D,getIndicesPtr:ge.E,getIndicesLength:ge.F,getBuildingPart:ge.G,getRingCount:ge.H,getRingPtr:ge.I,getRingLength:ge.J,malloc:ge.K,free:ge.L,heapU8:w,heap16:T,heap32:I,heapF32:L})})}(h).then(p=>(GM=null,$$=p,$$)).catch(p=>{Kr("Could not load building-gen"),GM=null,yLe=p instanceof Error?p:new Error("Unknown error")}),GM}()}populate(h,p,w,T){const I=Rjt();if(!I)return;const L=nr(w);this.tileToMeter=L,this.brightness=p.brightness,I.setStyle({normalScale:[1,-1,L],tileToMeters:L}),I.setAOOptions(!1,.3),I.setMetricOptions(!1,16),I.setStructuralOptions(!0),I.setFacadeClassifierOptions(3);const $=new Map,V=new Map;let X=0;for(const{feature:He}of h){if($Le[He.type]!=="LineString"){$.set(He.id,He.properties.source_id);continue}const ot=this.layers[0]._featureFilter.needGeometry;if(ot&&!this.layers[0]._featureFilter.filter(new ja(this.zoom),He,w))continue;const st=Fa(He,ot);if(!ot&&!this.layers[0]._featureFilter.filter(new ja(this.zoom),st,w))continue;const mt=ot?st.geometry:zn(He,w,T),bt=[];for(const Ht of mt)for(const Bt of Ht)bt.push(Bt.x),bt.push(Bt.y);const wt={coordinates:bt,crossPerc:He.properties.cross_perc,distanceToRoad:He.properties.distance_to_road,entrances:He.properties.entrances,sourceId:0},Gt=He.properties.source_id;let Ot=V.get(Gt);Ot||(Ot=[],V.set(Gt,Ot)),Ot.push(wt),++X}this.maxHeight=0;const re=new Array,oe=new Set,le=He=>{He!=null&&oe.add(He)},ge=(He,ot)=>{He!=null&&re.push({buildingId:He,footprintIndex:ot})},_e=64*(h.length-X),Te=_e/2;this.buildingWithFacade.reserve(_e,Te,!0),this.buildingWithoutFacade.reserve(2*_e,2*Te,!1),this.footprintsIndices.reserve(16*(h.length-X)),this.footprintsVertices.reserve(8*(h.length-X));for(const{feature:He,id:ot,index:st,sourceLayerIndex:mt}of h){if($Le[He.type]==="LineString")continue;const bt=this.layers[0]._featureFilter.needGeometry;if(bt&&!this.layers[0]._featureFilter.filter(new ja(this.zoom),He,w))continue;let wt=null;if(He.properties&&He.properties.hasOwnProperty("building_id")&&(wt=Number(He.properties.building_id),oe.has(wt)))continue;const Gt=Fa(He,bt);if(!bt&&!this.layers[0]._featureFilter.filter(new ja(this.zoom),Gt,w))continue;const Ot=bt?Gt.geometry:zn(He,w,T),Ht=qD(Ot,500);let Bt=!1;for(const ei of Ht)if(ei.length!==1){Bt=!0;break}if(Bt){le(wt);continue}if(!d2t(Ot,163)){le(wt);continue}const $t=this.layers[0],Es=u2t($t.layout.get("building-roof-shape").evaluate(He,{},w)),Os=$t.layout.get("building-base").evaluate(He,{},w),Hs=$t.layout.get("building-height").evaluate(He,{},w),Qs=$t.layout.get("building-flood-light-ground-radius").evaluate(He,{},w),Gs=$t.paint.get("building-ambient-occlusion-intensity"),hr=Qs/this.tileToMeter;He.properties["building-part"]="roof";const Ss=$t.paint.get("building-color").evaluate(He,{},this.canonical).toPremultipliedRenderColor(this.lut),Zs=$t.paint.get("building-emissive-strength").evaluate(He,{},this.canonical);He.properties["building-part"]="wall";const tr=$t.paint.get("building-color").evaluate(He,{},this.canonical).toPremultipliedRenderColor(this.lut),mr=$t.paint.get("building-emissive-strength").evaluate(He,{},this.canonical);He.properties["building-part"]="window";const wr=$t.paint.get("building-color").evaluate(He,{},this.canonical).toPremultipliedRenderColor(this.lut),tn=$t.paint.get("building-emissive-strength").evaluate(He,{},this.canonical);He.properties["building-part"]="door";const Mr=$t.paint.get("building-color").evaluate(He,{},this.canonical).toPremultipliedRenderColor(this.lut),Tr=$t.paint.get("building-emissive-strength").evaluate(He,{},this.canonical);let jr=$t.layout.get("building-flood-light-wall-radius").evaluate(He,{},w);jr=Ke(jr,0,2048);const Xr=jr/2048*Y$,ln=$.get(ot),On=V.get(ln)||[],xn=On.length!==0&&$t.layout.get("building-facade").evaluate(He,{},w);I.setFacadeOptions(4,!0),I.setFauxFacadeOptions(xn,!1,1);let va=0,xi=0,ba=0,bi=0,za=0,Ll=0,Wi=0,Ci=0,So=0,Sl=0,Dd=0;if(xn){let ei=Math.round($t.layout.get("building-facade-floors").evaluate(He,{},w));if(Os===0){ei=Math.max(1,ei-(On.length>0?1:0));let Yl=4;if(Hs>100){const xd=[10,13,15];Yl=xd[He.id?He.id%xd.length:0]}else Hs<=10&&(Yl=3);I.setFacadeOptions(Yl,!0),za=(Hs<15?1.3:1.61803)*Yl/L}else za=Os/L;Ll=Hs/L,za=Math.min(za,Ll),ba=$t.layout.get("building-facade-unit-width").evaluate(He,{},w)/L,bi=(Ll-za)/ei,I.setFauxFacadeOptions(!0,!0,ba);const ru=$t.layout.get("building-facade-window").evaluate(He,{},w);va=ru[0],xi=ru[1],Wi=Math.floor(65535*Math.min(1,za/Lr)),Ci=Math.floor(65535*Math.min(1,Ll/Lr)),So=Math.floor(255*va)<<8|Math.floor(255*xi),Sl=Math.floor(65535*Math.min(1,ba/Lr)),Dd=Math.floor(65535*Math.min(1,bi/Lr))}const Cl=Array(Ht.length),Wl={x:1/0,y:1/0},Nc={x:-1/0,y:-1/0},Kl={x:0,y:0};let sh=0;for(let ei=0;ei0){const Yl=[],xd=Array(ru.length+1);xd[0]=0;for(let Qg=0;QgLr||Wl.y<0||Nc.y>Lr)&&this.featuresOnBorder.push({featureId:He.id,footprintIndex:this.footprints.length});{const ei=UM(uj,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+ei.length),this.footprintsIndices.uint16.set(ei,i6),this.buildingIds.add(wt??He.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,Zg.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,Zg.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,Xg.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,Xg.y);const ru={footprintVertexOffset:dj,footprintVertexLength:this.footprintsVertices.length-dj,footprintIndexOffset:i6,footprintIndexLength:this.footprintsIndices.length-i6,min:Zg,max:Xg,hiddenFlags:0,indicesOffset:NU,indicesLength:F1e,bloomIndicesOffset:rh,bloomIndicesLength:Dl,groundEffectVertexOffset:dC,groundEffectVertexLength:o6,hasFauxFacade:xn,height:a6,promoteId:ot,feature:Gt,parts:tu,buildingBloom:Hm},Yl=this.footprints.length;He.id!==void 0&&this.featureFootprintLookup.set(He.id,Yl),ge(wt,Yl),this.footprints.push(ru)}this.programConfigurations.populatePaintArrays(Ha.layoutVertexArray.length,He,st,{},p.availableImages,w,p.brightness),this.groundEffect.addPaintPropertiesData(He,st,{},p.availableImages,w,p.brightness),p.featureIndex.insert(He,Ot,st,mt,this.index,em)}re.forEach(({buildingId:He,footprintIndex:ot})=>{oe.has(He)&&(this.footprints[ot].hiddenFlags|=4)});const Fe=new Set;this.buildingIds.forEach((He,ot,st)=>{oe.has(He)||Fe.add(He)}),this.buildingIds=Fe,this.groundEffect.prepareBorderSegments()}update(h,p,w,T,I,L,$){this.programConfigurations.updatePaintArrays(h,p,I,w,T,L,$),this.groundEffect.update(h,p,I,w,T,L,$),this.evaluate(this.layers[0],h),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(h){const p=w=>{w.layoutVertexBuffer=h.createVertexBuffer(w.layoutVertexArray,zLe.members),w.layoutNormalBuffer=h.createVertexBuffer(w.layoutNormalArray,r2t.members),w.layoutCentroidBuffer=h.createVertexBuffer(w.layoutCentroidArray,n2t.members),w.layoutFloodLightDataBuffer=h.createVertexBuffer(w.layoutFloodLightDataArray,c2t.members),w.layoutFacadeDataArray&&w.layoutFacadeDataArray.length&&(w.layoutFacadeDataBuffer=h.createVertexBuffer(w.layoutFacadeDataArray,i2t.members)),w.layoutFacadeVerticalRangeArray&&w.layoutFacadeVerticalRangeArray.length&&(w.layoutFacadeVerticalRangeBuffer=h.createVertexBuffer(w.layoutFacadeVerticalRangeArray,o2t.members)),w.entranceBloom.layoutVertexArray.length&&(w.entranceBloom.layoutVertexBuffer=h.createVertexBuffer(w.entranceBloom.layoutVertexArray,zLe.members),w.entranceBloom.layoutAttenuationBuffer=h.createVertexBuffer(w.entranceBloom.layoutAttenuationArray,l2t.members)),this.uploadUpdatedColorBuffer(h),this.uploadUpdatedIndexBuffer(h)};this.uploaded||(p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.groundEffect.upload(h)),this.groundEffect.uploadPaintProperties(h),this.programConfigurations.upload(h),this.uploaded=!0}destroy(){const h=p=>{p.layoutVertexBuffer&&(p.layoutVertexBuffer.destroy(),p.layoutNormalBuffer.destroy(),p.layoutColorBuffer.destroy(),p.segmentsBucket.destroy(),p.indexBuffer&&p.indexBuffer.destroy(),p.entranceBloom.layoutVertexBuffer&&(p.entranceBloom.layoutVertexBuffer.destroy(),p.entranceBloom.layoutColorBuffer.destroy(),p.entranceBloom.layoutAttenuationBuffer.destroy(),p.entranceBloom.indexBuffer.destroy(),p.entranceBloom.segmentsBucket.destroy()))};h(this.buildingWithoutFacade),h(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(h,p,w=!0){let T=!1;const I=w?p:0,L=0|(w?-1:~p);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const $ of h){const V=this.footprints[$],X=V.hiddenFlags&L|I;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(h){if(this.groundEffect.uploadHiddenByLandmark(h),this.indexArrayForConflationUploaded)return;const p=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))};p(this.buildingWithoutFacade),p(this.buildingWithFacade);for(const T of this.footprints){const I=T.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,L=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=h.createIndexBuffer(T.indexArrayForConflation,!0),T.entranceBloom.indexBuffer?T.entranceBloom.indexBuffer.updateData(T.entranceBloom.indexArrayForConflation):T.entranceBloom.indexBuffer=h.createIndexBuffer(T.entranceBloom.indexArrayForConflation,!0))};w(this.buildingWithoutFacade),w(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(h){const p=w=>{w.layoutColorBuffer?w.layoutColorBuffer.updateData(w.layoutColorArray):w.layoutColorBuffer=h.createVertexBuffer(w.layoutColorArray,BLe.members,!0),w.layoutFacadePaintArray&&(w.layoutFacadePaintBuffer?w.layoutFacadePaintBuffer.updateData(w.layoutFacadePaintArray):w.layoutFacadePaintBuffer=h.createVertexBuffer(w.layoutFacadePaintArray,a2t.members,!0)),w.entranceBloom.layoutColorBuffer?w.entranceBloom.layoutColorBuffer.updateData(w.entranceBloom.layoutColorArray):w.entranceBloom.layoutColorBuffer=h.createVertexBuffer(w.entranceBloom.layoutColorArray,BLe.members,!0)};p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(h,p){const w=h.paint.get("building-ambient-occlusion-intensity");for(const T of this.footprints){if(4&T.hiddenFlags)continue;const I=p[T.promoteId],L=T.feature;L.properties["building-part"]="roof";const $=h.paint.get("building-color").evaluate(L,I,this.canonical).toPremultipliedRenderColor(this.lut),V=h.paint.get("building-emissive-strength").evaluate(L,I,this.canonical);L.properties["building-part"]="wall";const X=h.paint.get("building-color").evaluate(L,I,this.canonical).toPremultipliedRenderColor(this.lut),re=h.paint.get("building-emissive-strength").evaluate(L,I,this.canonical);L.properties["building-part"]="window";const oe=h.paint.get("building-color").evaluate(L,I,this.canonical).toPremultipliedRenderColor(this.lut),le=h.paint.get("building-emissive-strength").evaluate(L,I,this.canonical);L.properties["building-part"]="door";const ge=h.paint.get("building-color").evaluate(L,I,this.canonical).toPremultipliedRenderColor(this.lut),_e=h.paint.get("building-emissive-strength").evaluate(L,I,this.canonical),Te=T.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const He of T.parts){let ot,st=$;He.part===1?(st=$,ot=V):He.part===0?(st=X,ot=re):He.part===2?(st=oe,ot=le):He.part===3&&(st=ge,ot=_e),ot=Ke(ot,0,1);for(let mt=0;mtL.max.x||V.max.xL.max.y||V.max.y$.max.x||$.min.x>h||p>$.max.y||$.min.y>p||$.height<=w||h2t(L,this.footprintsVertices.float32.subarray(2*$.footprintVertexOffset,2*($.footprintVertexOffset+$.footprintVertexLength)),this.footprintsIndices.uint16.subarray($.footprintIndexOffset,$.footprintIndexOffset+$.footprintIndexLength))&&(w=$.height,this.footprintLookup[I]=$,T=$.hiddenFlags!==0);if(w!==Number.NEGATIVE_INFINITY)return{height:w,hidden:T};this.footprintLookup[I]=void 0}}function h2t(v,h,p){for(let w=0;w1&&(V=h[++$]);const re=Math.abs(X-V.left),oe=Math.abs(X-V.right),le=Math.min(re,oe);let ge;const _e=I/w*(T+1);if(V.isDash){const Te=T-Math.abs(_e);ge=Math.sqrt(le*le+Te*Te)}else ge=T-Math.sqrt(le*le+_e*_e);this.image.data[L+X]=Math.max(0,Math.min(255,ge+128))}}}addRegularDash(h,p){for(let V=h.length-1;V>=0;--V){const X=h[V],re=h[V+1];X.zeroLength?h.splice(V,1):re&&re.isDash===X.isDash&&(re.left=X.left,h.splice(V,1))}const w=h[0],T=h[h.length-1];w.isDash===T.isDash&&(w.left=T.left-this.width,T.right=w.right+this.width);const I=this.width*this.nextRow;let L=0,$=h[L];for(let V=0;V1&&($=h[++L]);const X=Math.abs(V-$.left),re=Math.abs(V-$.right),oe=Math.min(X,re);this.image.data[I+V]=Math.max(0,Math.min(255,($.isDash?oe:-oe)+p+128))}}addDash(h,p){const w=this.getKey(h,p);if(this.positions[w])return this.positions[w];const T=p==="round",I=T?7:0,L=2*I+1;if(this.nextRow+L>this.height)return Kr("LineAtlas out of space"),null;h.length===0&&h.push(1);let $=0;for(let oe=0;oep.fqid),this.index=h.index,this.projection=h.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(p=>{this.gradients[p.id]={}}),this.layoutVertexArray=new U4,this.layoutVertexArray2=new Hx,this.patternVertexArray=new Hx,this.indexArray=new Gl,this.programConfigurations=new Be(h.layers,{zoom:h.zoom,lut:h.lut}),this.segments=new jo,this.maxLineLength=0,this.zOffsetVertexArray=new Hx,this.elevationGroundScaleVertexArray=new eo,this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.id),this.tessellationStep=h.tessellationStep?h.tessellationStep:128,this.worldview=h.worldview,this.hasAppearances=null}updateFootprints(h,p){}updateAppearances(h,p,w,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(h,p,w,T){this.hasPattern=gve("line",this.layers,this.pixelRatio,p);const I=this.layers[0].layout.get("line-sort-key");this.tileToMeter=nr(w);const L=this.layers[0].layout.get("line-elevation-reference");if(L==="hd-road-markup")this.elevationType="road";else{const le=this.layers[0].layout.get("line-z-offset"),ge=le.isConstant()&&!le.constantOr(0);this.elevationType=L!=="sea"&&L!=="ground"&&ge?"none":"offset",this.elevationType==="offset"&&L==="none"&&Kr(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=L==="sea"}const $=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&$!==void 0;const V=[];for(const{feature:le,id:ge,index:_e,sourceLayerIndex:Te}of h){const Fe=this.layers[0]._featureFilter.needGeometry,He=Fa(le,Fe);if(!this.layers[0]._featureFilter.filter(new ja(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),He,w))continue;const ot=I?I.evaluate(He,{},w):void 0,st={id:ge,properties:le.properties,type:le.type,sourceLayerIndex:Te,index:_e,geometry:Fe?He.geometry:zn(le,w,T),patterns:{},sortKey:ot};V.push(st)}I&&V.sort((le,ge)=>le.sortKey-ge.sortKey);const{lineAtlas:X,featureIndex:re}=p,oe=this.addConstantDashes(X);for(const le of V){const{geometry:ge,index:_e,sourceLayerIndex:Te}=le;if(oe&&this.addFeatureDashes(le,X),this.hasPattern){const Fe=yve("line",this.layers,le,this.zoom,this.pixelRatio,p);this.patternFeatures.push(Fe)}else this.addFeature(le,ge,_e,w,X.positions,p.availableImages,p.brightness,p.elevationFeatures);re.insert(h[_e].feature,ge,_e,Te,this.index)}}addConstantDashes(h){let p=!1;for(const w of this.layers){const T=w.paint.get("line-dasharray").value,I=w.layout.get("line-cap").value;if(T.kind!=="constant"||I.kind!=="constant")p=!0;else{const L=I.value,$=T.value;if(!$)continue;h.addDash($,L)}}return p}addFeatureDashes(h,p){const w=this.zoom;for(const T of this.layers){const I=T.paint.get("line-dasharray").value,L=T.layout.get("line-cap").value;if(I.kind==="constant"&&L.kind==="constant")continue;let $,V;if(I.kind==="constant"){if($=I.value,!$)continue}else $=I.evaluate({zoom:w},h);V=L.kind==="constant"?L.value:L.evaluate({zoom:w},h),p.addDash($,V),h.patterns[T.id]=[p.getKey($,V)]}}update(h,p,w,T,I,L,$,V,X){this.programConfigurations.updatePaintArrays(h,p,I,w,T,L,$,X)}addFeatures(h,p,w,T,I,L){for(const $ of this.patternFeatures)this.addFeature($,$.geometry,$.index,p,w,T,L,h.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(h){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=h.createVertexBuffer(this.layoutVertexArray2,v2t)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=h.createVertexBuffer(this.patternVertexArray,_2t)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=h.createVertexBuffer(this.zOffsetVertexArray,p2t.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=h.createVertexBuffer(this.elevationGroundScaleVertexArray,x2t.members,!0)),this.layoutVertexBuffer=h.createVertexBuffer(this.layoutVertexArray,g2t),this.indexBuffer=h.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(h),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(h,p){let w,T;if(p&&p>0?(w=`mapbox_clip_start_${p}`,T=`mapbox_clip_end_${p}`):(w="mapbox_clip_start",T="mapbox_clip_end"),h.properties&&h.properties.hasOwnProperty(w)&&h.properties.hasOwnProperty(T))return{start:+h.properties[w],end:+h.properties[T]}}addFeature(h,p,w,T,I,L,$,V){const X=this.layers[0].layout,re=X.get("line-join").evaluate(h,{}),oe=X.get("line-cap").evaluate(h,{}),le=X.get("line-miter-limit"),ge=X.get("line-round-limit");this.lineClips=this.lineFeatureClips(h),this.lineFeature=h;const _e=!(!h.properties||!h.properties.hasOwnProperty("mapbox_line_metrics"))&&h.properties.mapbox_line_metrics;this.zOffsetValue=X.get("line-z-offset").value;const Te=this.layers[0].paint.get("line-width").value;if(Te.kind!=="constant"&&Te.isLineProgressConstant===!1&&(this.variableWidthValue=Te),this.isSeaLevelReference){const Fe=X.get("line-elevation-ground-scale").value;Fe.kind==="constant"&&Fe.value===0||(this.elevationGroundScaleValue=Fe)}if(this.elevationType==="road"){const Fe=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(h,p,T,V,re,oe,le,ge)){const[He,ot]=this.clipRuntimeLinesToTile(p,1);for(let st=0;st0?bt.parentIndex:null)}this.fillNonElevatedRoadSegment(Fe)}}else for(let Fe=0;Fe0?Fe:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,h,w,I,L,T,$,void 0,this.worldview)}computeSegNextDir(h,p){return h.nextPoint.sub(p.at(-2)).unit()}computeSegPrevDir(h,p){return p[1].sub(h.prevPoint).unit()}clipLinesToTile(h,p){return B$(h,-p,-p,Lr+p,Lr+p)}clipRuntimeLinesToTile(h,p){const w=[];return[B$(h,-p,-p,Lr+p,Lr+p,w),w]}addElevatedRoadFeature(h,p,w,T,I,L,$,V){const X=[],re=To.getElevationFeature(h,T);if(re){const oe=this.clipLinesToTile(p,1),le=this.prepareElevatedLines(oe,re,w);for(const ge of le)X.push({geometry:ge,elevation:re,elevationTileID:w,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(X.length===0)return!1;for(const oe of X){const le=this.layoutVertexArray.length;this.addLine(oe.geometry,h,w,I,L,$,V);const ge=new Po(w,oe.elevationTileID);if(oe.elevation)for(let _e=le;_e>1,this.layoutVertexArray.int16[6*_e+1]>>1),Fe=ge.pointElevation(Te,oe.elevation,.05);this.updateHeightRange(Fe),this.zOffsetVertexArray.emplaceBack(Fe,0,0)}else this.fillNonElevatedRoadSegment(le)}return!0}prepareElevatedLines(h,p,w){if(p.constantHeight!=null)return h;const T=[],I=1/nr(w);for(const L of h)Ljt(L,new ex(p,I),0,T);return T}fillNonElevatedRoadSegment(h){for(let p=h;p0,le=V&&V.progress.max<1;if(this.lineClips){let Ht={min:this.lineClips.start,max:this.lineClips.end},Bt=1;if(V){const Os=this.lineClips.end-this.lineClips.start;Ht=function(Hs,Qs,Gs){return{min:Gi(Hs.min,Qs,Gs),max:Gi(Hs.max,Qs,Gs)}}(V.progress,{min:0,max:1},Ht),Os>0&&(Bt=(Ht.max-Ht.min)/Os)}const $t=+p.properties.mapbox_clip_feature_len,Es=+p.properties.mapbox_clip_seg_len;if(Number.isNaN($t)||Number.isNaN(Es)){for(let Hs=0;Hs=2&&h[_e-1].equals(h[_e-2]);)_e--;let Te=0;for(;Te<_e-1&&h[Te].equals(h[Te+1]);)Te++;if(_e<(ge?3:2))return;T==="bevel"&&(L=1.05);const Fe=this.segments.prepareSegment(10*_e,this.layoutVertexArray,this.indexArray);let He,ot,st,mt,bt,wt,Gt,Ot;V&&V.prevDir&&(wt=V.prevDir.perp()),V&&V.nextDir&&(Gt=V.nextDir.perp()),this.e1=this.e2=-1,ge&&(He=h[_e-2],bt=h[Te].sub(He)._unit()._perp());for(let Ht=Te;Ht<_e;Ht++){if(st=Ht===_e-1?ge?h[Te+1]:void 0:h[Ht+1],st&&h[Ht].equals(st))continue;bt&&(mt=bt),He&&(ot=He),He=h[Ht],Ot=this.evaluateLineProgressFeatures(ot?ot.dist(He):0),bt=st?st.sub(He)._unit()._perp():mt,mt=mt||bt;const Bt=ot&&st;let $t=Bt?T:ge||re?"butt":I;const Es=mt.x*bt.x+mt.y*bt.y;if(re){const tr=function(mr){if(mr.patternJoinNone){const wr=mr.segmentPoints.length/2,tn=mr.lineSoFar-mr.segmentStart;for(let Mr=0;Mr0,Zs=this.overscaling<=16?122880/(512*this.overscaling):0;if(Bt&&$t==="round"){if(Qs<$)$t="miter";else if(Qs<=2){const tr=Yve(He,-10,8202);$t=this.elevationType==="offset"&&(tr||this.hasCrossSlope)?"miter":"fakeround"}}if($t==="miter"&&Qs>L&&($t="bevel"),$t==="bevel"&&(Qs>2&&($t="flipbevel"),Qs2*Zs){const wr=He.sub(He.sub(ot)._mult(Zs/tr)._round());this.updateDistance(ot,wr),this.addCurrentVertex(wr,mt,0,0,Fe,Ot),ot=wr}this.updateDistance(ot,He),Os._mult(Qs),this.addCurrentVertex(He,Os,0,0,Fe,Ot);const mr=He.dist(st);if(mr>2*Zs){const wr=He.add(st.sub(He)._mult(Zs/mr)._round());this.updateDistance(He,wr),this.addCurrentVertex(wr,bt,0,0,Fe,Ot),He=wr}}else Os._mult(Qs),this.addCurrentVertex(He,Os,0,0,Fe,Ot);else if($t==="flipbevel"){if(Qs>100)Os=bt.mult(-1);else{const tr=Qs*mt.add(bt).mag()/mt.sub(bt).mag();Os._perp()._mult(tr*(Ss?-1:1))}this.addCurrentVertex(He,Os,0,0,Fe,Ot),this.addCurrentVertex(He,Os.mult(-1),0,0,Fe,Ot)}else if($t==="bevel"||$t==="fakeround"){const tr=He.dist(ot);let mr=1;if(this.elevationType==="offset"&&$t==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&Ot!=null&&ot&&st){const Xr=4*Zs;tr1){this.lineSoFar=h.w;const Te=(p.x-h.x)/oe,Fe=(p.y-h.y)/oe,He=(p.z-h.z)/oe,ot=(p.w-h.w)/oe,st=p.x-h.x,mt=p.y-h.y,bt=Math.sqrt(st*st+mt*mt);if(bt===0)return;const wt=-mt/bt,Gt=st/bt,Ot=wt,Ht=Gt,Bt=-wt,$t=-Gt;for(let Es=1;Es=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,re),V.primitiveLength++),L?this.e2=re:this.e1=re,X!=null&&this.zOffsetVertexArray.emplaceBack(X.zOffset,X.variableWidth,X.variableWidth),this.elevationGroundScaleValue){const oe=X?X.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(oe)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(h,p){this.prevDistance=this.distance,this.distance+=h.dist(p),this.updateScaledDistance()}}function Yve(v,h,p){return v.xp||v.yp}let GLe,WLe;function KLe(v,h,p){return h*(Lr/(v.tileSize*Math.pow(2,p-v.tileID.overscaledZ)))}Wr(Z$,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const YLe=(v,h,p)=>(1-p)*v+p*h;function ZLe(v,h){return 1/KLe(v,1,h.tileZoom)}function XLe(v,h,p,w){return v.translatePosMatrix(w||h.tileID.projMatrix,h,p.paint.get("line-translate"),p.paint.get("line-translate-anchor"))}const QLe=v=>{const h=[];JLe(v)&&h.push("RENDER_LINE_DASH"),v.paint.get("line-gradient")&&h.push("RENDER_LINE_GRADIENT"),v.paint.get("line-blend-mode")==="multiply"&&h.push("LINE_BLEND_MULTIPLY");const p=v.paint.get("line-trim-offset");p[0]===0&&p[1]===0||h.push("RENDER_LINE_TRIM_OFFSET"),v.paint.get("line-border-width").constantOr(1)!==0&&h.push("RENDER_LINE_BORDER");const w=v.layout.get("line-join").constantOr("miter")==="none",T=!!v.paint.get("line-pattern").constantOr(1);return w&&T&&h.push("LINE_JOIN_NONE"),h};function JLe(v){const h=v.paint.get("line-dasharray").value;return h.kind!=="constant"||h.value}let Zve;const e8e=()=>Zve||(Zve={layout:GLe||(GLe=new Io({"line-cap":new gr(as.layout_line["line-cap"]),"line-join":new gr(as.layout_line["line-join"]),"line-miter-limit":new yr(as.layout_line["line-miter-limit"]),"line-round-limit":new yr(as.layout_line["line-round-limit"]),"line-sort-key":new gr(as.layout_line["line-sort-key"]),"line-z-offset":new gr(as.layout_line["line-z-offset"]),"line-elevation-reference":new yr(as.layout_line["line-elevation-reference"]),"line-cross-slope":new yr(as.layout_line["line-cross-slope"]),visibility:new yr(as.layout_line.visibility),"line-width-unit":new yr(as.layout_line["line-width-unit"]),"line-elevation-ground-scale":new gr(as.layout_line["line-elevation-ground-scale"])})),paint:WLe||(WLe=new Io({"line-opacity":new gr(as.paint_line["line-opacity"]),"line-color":new gr(as.paint_line["line-color"]),"line-translate":new yr(as.paint_line["line-translate"]),"line-translate-anchor":new yr(as.paint_line["line-translate-anchor"]),"line-width":new gr(as.paint_line["line-width"]),"line-gap-width":new gr(as.paint_line["line-gap-width"]),"line-offset":new gr(as.paint_line["line-offset"]),"line-blur":new gr(as.paint_line["line-blur"]),"line-dasharray":new gr(as.paint_line["line-dasharray"]),"line-pattern":new gr(as.paint_line["line-pattern"]),"line-pattern-cross-fade":new yr(as.paint_line["line-pattern-cross-fade"]),"line-gradient":new Sf(as.paint_line["line-gradient"]),"line-trim-offset":new yr(as.paint_line["line-trim-offset"]),"line-trim-fade-range":new yr(as.paint_line["line-trim-fade-range"]),"line-trim-color":new yr(as.paint_line["line-trim-color"]),"line-emissive-strength":new gr(as.paint_line["line-emissive-strength"]),"line-border-width":new gr(as.paint_line["line-border-width"]),"line-border-color":new gr(as.paint_line["line-border-color"]),"line-occlusion-opacity":new yr(as.paint_line["line-occlusion-opacity"]),"line-blend-mode":new yr(as.paint_line["line-blend-mode"]),"line-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"})}))},Zve);class k2t extends gr{possiblyEvaluate(h,p){return p=new ja(Math.floor(p.zoom),{now:p.now,fadeDuration:p.fadeDuration,transition:p.transition,worldview:p.worldview}),super.possiblyEvaluate(h,p)}evaluate(h,p,w,T){return p=Object.assign({},p,{zoom:Math.floor(p.zoom)}),super.evaluate(h,p,w,T)}}let tR;function t8e(v,h){return h>0?h+2*v:v}const S2t=rr([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),C2t=rr([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),T2t=rr([{name:"a_projected_pos",components:4,type:"Float32"}],4);rr([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const E2t=rr([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),A2t=rr([{name:"a_feature_index",components:1,type:"Float32"}],4),M2t=rr([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),I2t=rr([{name:"a_texb",components:2,type:"Uint16"}]),P2t=rr([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),L2t=rr([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);rr([{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 s8e=rr([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),D2t=rr([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);rr([{name:"triangle",components:3,type:"Uint16"}]),rr([{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"}]),rr([{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"}]),rr([{type:"Float32",name:"offsetX"}]),rr([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const Xve=class Oue{constructor(h=null,p=0,w=4096){this.batchIndex=p,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=h||null,this.propsDwords=w,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(Oue.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let T=0;Th.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${h.maxUniformBlockSize}`);if(this.headerBuffer=p.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(p.bindBuffer(p.UNIFORM_BUFFER,this.headerBuffer),p.bufferData(p.UNIFORM_BUFFER,Oue.HEADER_BYTES,p.DYNAMIC_DRAW),this.propertiesBuffer=p.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(p.bindBuffer(p.UNIFORM_BUFFER,this.propertiesBuffer),p.bufferData(p.UNIFORM_BUFFER,this.totalBytes,p.DYNAMIC_DRAW),this.blockIndicesBuffer=p.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");p.bindBuffer(p.UNIFORM_BUFFER,this.blockIndicesBuffer),p.bufferData(p.UNIFORM_BUFFER,this.totalBytes,p.DYNAMIC_DRAW),p.bindBuffer(p.UNIFORM_BUFFER,null)}writeHeader(h){const p=this.headerData;p[0]=h.dataDrivenMask,p[1]=h.zoomDependentMask,p[2]=h.dataDrivenBlockSizeVec4,p[3]=h.offsets[0],p[4]=h.offsets[1],p[5]=h.offsets[2],p[6]=h.offsets[3],p[7]=h.offsets[4],p[8]=h.offsets[5],p[9]=h.offsets[6],p[10]=h.offsets[7],p[11]=h.offsets[8]}writeDataDrivenBlock(h,p,w){const T=4*w.dataDrivenBlockSizeVec4;if(T===0)return;const I=p*T;if(I+T>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${p} exceeds propertiesData capacity`);for(let L=0;L<9;L++)w.dataDrivenMask&1<{if(!$)return;const X=w.getUniformBlockIndex(p,L);X!==w.INVALID_INDEX&&(w.uniformBlockBinding(p,X,V),w.bindBufferBase(w.UNIFORM_BUFFER,V,$))},I=3*this.batchIndex;T("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,I),T("SymbolPaintPropertiesUniform",this.propertiesBuffer,I+1),T("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,I+2)}destroy(){if(this.context){const h=this.context.gl;this.headerBuffer&&(h.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(h.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(h.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};Xve.HEADER_DWORDS=12,Xve.HEADER_BYTES=48;let Qve=Xve;function Jve(v,h,p,w){return[FM(255*v,255*h),FM(255*p,255*w)]}function r8e(v,h,p,w,T,I,L,$){return!!v&&(v.kind==="constant"?v.value==="none":v.kind==="composite"||v.kind==="source"?v.evaluate({zoom:0,brightness:I,worldview:$},h,p,T,w,L)==="none":typeof v=="string"&&v==="none")}Wr(Qve,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class e1e{constructor(h,p,w,T,I="",L,$){this.layer=h,this.zoom=p,this.lut=w,this.isText=T,this.propDefs=this._getPropDefs(),this.worldview=I,this.maxUniformBufferBindings=L||24,this.uboSizeDwords=$||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(h,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 h=this.isText?"text":"icon";return[{name:`${h}-color`,useThemeName:`${h}-color-use-theme`,isColor:!0},{name:`${h}-halo-color`,useThemeName:`${h}-halo-color-use-theme`,isColor:!0},{name:`${h}-opacity`,useThemeName:null,isColor:!1},{name:`${h}-halo-width`,useThemeName:null,isColor:!1},{name:`${h}-halo-blur`,useThemeName:null,isColor:!1},{name:`${h}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${h}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${h}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const h=this.layer.paint,p=this.propDefs;let w=0,T=0,I=0,L=0;const $=[0,0,0,0,0,0,0,0,0];for(let V=0;V<9;V++){const{name:X,isColor:re,isVec2:oe}=p[V],le=h.get(X),ge=!(!le||typeof le.isConstant!="function"||le.isConstant()),_e=this._appearancesHavePaintProperties(X),Te=ge||_e,Fe=!(!le||!le.value||le.value.kind!=="composite"),He=this.layer._transitionablePaint._values[X],ot=!Te&&(He&&He.value&&He.value.expression&&He.value.expression.kind)==="camera";Te?(w|=1<p.hasPaintProperty(h):this.isText?p=>p.hasTextPaintProperties():p=>p.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(h,p){const w=h.paint,T=p?"text":"icon",I=[`${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 L of I){const $=w.get(L);if($&&typeof $=="object"&&"isConstant"in $&&!$.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(h,p){if(p.dataDrivenMask===0)return"";const w=[];for(let T=0;T<9;T++){if(!(p.dataDrivenMask&1<=_e){Kr(`Too many symbol features: batch ${le} requires binding points up to ${3*le+2}, device limit ${_e}. Some features will render incorrectly.`);const Fe={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:p,featureId:V};return this.allFeatures.push(Fe),V!=null&&(this.featureVertexRangesFromId.has(V)||this.featureVertexRangesFromId.set(V,[]),this.featureVertexRangesFromId.get(V).push(Fe)),0}this.ubos[le]||(this.ubos[le]=new Qve($,le,this.uboSizeDwords),this.ubos[le].writeHeader(X)),this.ubos[le].writeDataDrivenBlock(re,ge,X);const Te={batchIndex:le,localFeatureIndex:ge,vtFeatureIndex:p,featureId:V};return this.allFeatures.push(Te),V!=null&&(this.featureVertexRangesFromId.has(V)||this.featureVertexRangesFromId.set(V,[]),this.featureVertexRangesFromId.get(V).push(Te)),ge}updateFeatures(h,p,w,T,I,L,$){if(this.layer=p,this.cachedConstantUniforms=null,!this.cachedHeader)return;const V=this.cachedHeader;for(const X of h){const re=this.featureVertexRangesFromId.get(X);if(!re)continue;const oe=L[X]||{};for(const le of re){if(!w)continue;const ge=w.feature(le.vtFeatureIndex);if(!ge)continue;const _e={type:ge.type,id:X,properties:ge.properties||{},geometry:[]},Te=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(le.vtFeatureIndex):void 0,Fe=this.evaluateAllProperties(_e,oe,T,I,$,void 0,Te);this.ubos[le.batchIndex]&&this.ubos[le.batchIndex].writeDataDrivenBlock(Fe,le.localFeatureIndex,V)}}}updateDynamicExpressions(h,p,w,T,I,L){if(this.layer=h,this.cachedConstantUniforms=null,!this.cachedHeader)return;const $=this.cachedHeader;for(const V of this.allFeatures){if(!p)continue;const X=p.feature(V.vtFeatureIndex);if(!X)continue;const re=V.featureId!=null&&I[V.featureId]||{},oe={type:X.type,id:V.featureId,properties:X.properties||{},geometry:[]},le=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(V.vtFeatureIndex):void 0,ge=this.evaluateAllProperties(oe,re,w,T,L,void 0,le);this.ubos[V.batchIndex]&&this.ubos[V.batchIndex].writeDataDrivenBlock(ge,V.localFeatureIndex,$)}}updateFeaturePaintForAppearance(h,p,w,T,I,L,$){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(h,$||null),!this.cachedHeader))return!1;const V=this.cachedHeader;if(V.dataDrivenMask===0)return!1;let X=!1;for(const re of this.allFeatures){if(re.vtFeatureIndex!==h)continue;const oe=this.evaluateAllProperties(p,w,T,I,L,void 0,$);this.ubos[re.batchIndex]&&(this.ubos[re.batchIndex].writeDataDrivenBlock(oe,re.localFeatureIndex,V),X=!0)}return X}getConstantUniformValues(h,p){const w=this.cachedHeader,T=!(!w||!w.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===p&&(!T||this.cachedConstantRenderZoom===h))return this.cachedConstantUniforms;const I=this.layer.paint,L=this.propDefs,$=T?new ja(h,{brightness:p,worldview:this.worldview}):null,V={type:1,id:void 0,properties:{},geometry:[]},X=le=>{const ge=L[le],_e=I.get(ge.name);if(!_e)return[0,0,0,1];const Te=ge.useThemeName?I.get(ge.useThemeName):void 0,Fe=r8e(Te&&typeof Te!="string"?Te.value:void 0,V,{},[],void 0,p,void 0,this.worldview)?null:this.lut;let He;He=w&&w.cameraMask&1<{const _e=I.get(L[le].name);if(!_e)return ge;if(w&&w.cameraMask&1<{w.text=function(T,I,L){const $=I.layout.get("text-transform").evaluate(L,{});return $==="uppercase"?T=T.toLocaleUpperCase():$==="lowercase"&&(T=T.toLocaleLowerCase()),Jh.applyArabicShaping&&(T=Jh.applyArabicShaping(T)),T}(w.text,h,p)}),v}const sR={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function O2t(v){return v==="︶"||v==="﹈"||v==="︸"||v==="﹄"||v==="﹂"||v==="︾"||v==="︼"||v==="︺"||v==="︘"||v==="﹀"||v==="︐"||v==="︓"||v==="︔"||v==="`"||v===" ̄"||v==="︑"||v==="︒"}function F2t(v){return v==="︵"||v==="﹇"||v==="︷"||v==="﹃"||v==="﹁"||v==="︽"||v==="︻"||v==="︹"||v==="︗"||v==="︿"}const t1e=4294967296,n8e=1/t1e,a8e=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let X$=class{constructor(v=new Uint8Array(16)){this.buf=ArrayBuffer.isView(v)?v:new Uint8Array(v),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(v,h,p=this.length){for(;this.pos>3,I=this.pos;this.type=7&w,v(T,h,this),this.pos===I&&this.skip(w)}return h}readMessage(v,h){return this.readFields(v,h,this.readVarint()+this.pos)}readFixed32(){const v=this.dataView.getUint32(this.pos,!0);return this.pos+=4,v}readSFixed32(){const v=this.dataView.getInt32(this.pos,!0);return this.pos+=4,v}readFixed64(){const v=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*t1e;return this.pos+=8,v}readSFixed64(){const v=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*t1e;return this.pos+=8,v}readFloat(){const v=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,v}readDouble(){const v=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,v}readVarint(v){const h=this.buf;let p,w;return w=h[this.pos++],p=127&w,w<128?p:(w=h[this.pos++],p|=(127&w)<<7,w<128?p:(w=h[this.pos++],p|=(127&w)<<14,w<128?p:(w=h[this.pos++],p|=(127&w)<<21,w<128?p:(w=h[this.pos],p|=(15&w)<<28,function(T,I,L){const $=L.buf;let V,X;if(X=$[L.pos++],V=(112&X)>>4,X<128||(X=$[L.pos++],V|=(127&X)<<3,X<128)||(X=$[L.pos++],V|=(127&X)<<10,X<128)||(X=$[L.pos++],V|=(127&X)<<17,X<128)||(X=$[L.pos++],V|=(127&X)<<24,X<128)||(X=$[L.pos++],V|=(1&X)<<31,X<128))return KM(T,V,I);throw new Error("Expected varint not more than 10 bytes")}(p,v,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const v=this.readVarint();return v%2==1?(v+1)/-2:v/2}readBoolean(){return!!this.readVarint()}readString(){const v=this.readVarint()+this.pos,h=this.pos;return this.pos=v,v-h>=12&&a8e?a8e.decode(this.buf.subarray(h,v)):function(p,w,T){let I="",L=w;for(;L239?4:$>223?3:$>191?2:1;if(L+le>T)break;le===1?$<128&&(oe=$):le===2?(V=p[L+1],(192&V)==128&&(oe=(31&$)<<6|63&V,oe<=127&&(oe=null))):le===3?(V=p[L+1],X=p[L+2],(192&V)==128&&(192&X)==128&&(oe=(15&$)<<12|(63&V)<<6|63&X,(oe<=2047||oe>=55296&&oe<=57343)&&(oe=null))):le===4&&(V=p[L+1],X=p[L+2],re=p[L+3],(192&V)==128&&(192&X)==128&&(192&re)==128&&(oe=(15&$)<<18|(63&V)<<12|(63&X)<<6|63&re,(oe<=65535||oe>=1114112)&&(oe=null))),oe===null?(oe=65533,le=1):oe>65535&&(oe-=65536,I+=String.fromCharCode(oe>>>10&1023|55296),oe=56320|1023&oe),I+=String.fromCharCode(oe),L+=le}return I}(this.buf,h,v)}readBytes(){const v=this.readVarint()+this.pos,h=this.buf.subarray(this.pos,v);return this.pos=v,h}readPackedVarint(v=[],h){const p=this.readPackedEnd();for(;this.pos127;);else if(h===2)this.pos=this.readVarint()+this.pos;else if(h===5)this.pos+=4;else{if(h!==1)throw new Error(`Unimplemented type: ${h}`);this.pos+=8}}writeTag(v,h){this.writeVarint(v<<3|h)}realloc(v){let h=this.length||16;for(;h268435455||v<0?function(h,p){let w,T;if(h>=0?(w=h%4294967296|0,T=h/4294967296|0):(w=~(-h%4294967296),T=~(-h/4294967296),4294967295^w?w=w+1|0:(w=0,T=T+1|0)),h>=18446744073709552e3||h<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");p.realloc(10),function(I,L,$){$.buf[$.pos++]=127&I|128,I>>>=7,$.buf[$.pos++]=127&I|128,I>>>=7,$.buf[$.pos++]=127&I|128,I>>>=7,$.buf[$.pos++]=127&I|128,$.buf[$.pos]=127&(I>>>=7)}(w,0,p),function(I,L){const $=(7&I)<<4;L.buf[L.pos++]|=$|((I>>>=3)?128:0),I&&(L.buf[L.pos++]=127&I|((I>>>=7)?128:0),I&&(L.buf[L.pos++]=127&I|((I>>>=7)?128:0),I&&(L.buf[L.pos++]=127&I|((I>>>=7)?128:0),I&&(L.buf[L.pos++]=127&I|((I>>>=7)?128:0),I&&(L.buf[L.pos++]=127&I)))))}(T,p)}(v,this):(this.realloc(4),this.buf[this.pos++]=127&v|(v>127?128:0),v<=127||(this.buf[this.pos++]=127&(v>>>=7)|(v>127?128:0),v<=127||(this.buf[this.pos++]=127&(v>>>=7)|(v>127?128:0),v<=127||(this.buf[this.pos++]=v>>>7&127))))}writeSVarint(v){this.writeVarint(v<0?2*-v-1:2*v)}writeBoolean(v){this.writeVarint(+v)}writeString(v){v=String(v),this.realloc(4*v.length),this.pos++;const h=this.pos;this.pos=function(w,T,I){for(let L,$,V=0;V55295&&L<57344){if(!$){L>56319||V+1===T.length?(w[I++]=239,w[I++]=191,w[I++]=189):$=L;continue}if(L<56320){w[I++]=239,w[I++]=191,w[I++]=189,$=L;continue}L=$-55296<<10|L-56320|65536,$=null}else $&&(w[I++]=239,w[I++]=191,w[I++]=189,$=null);L<128?w[I++]=L:(L<2048?w[I++]=L>>6|192:(L<65536?w[I++]=L>>12|224:(w[I++]=L>>18|240,w[I++]=L>>12&63|128),w[I++]=L>>6&63|128),w[I++]=63&L|128)}return I}(this.buf,v,this.pos);const p=this.pos-h;p>=128&&i8e(h,p,this),this.pos=h-1,this.writeVarint(p),this.pos+=p}writeFloat(v){this.realloc(4),this.dataView.setFloat32(this.pos,v,!0),this.pos+=4}writeDouble(v){this.realloc(8),this.dataView.setFloat64(this.pos,v,!0),this.pos+=8}writeBytes(v){const h=v.length;this.writeVarint(h),this.realloc(h);for(let p=0;p=128&&i8e(p,w,this),this.pos=p-1,this.writeVarint(w),this.pos+=w}writeMessage(v,h,p){this.writeTag(v,2),this.writeRawMessage(h,p)}writePackedVarint(v,h){h.length&&this.writeMessage(v,z2t,h)}writePackedSVarint(v,h){h.length&&this.writeMessage(v,B2t,h)}writePackedBoolean(v,h){h.length&&this.writeMessage(v,q2t,h)}writePackedFloat(v,h){h.length&&this.writeMessage(v,$2t,h)}writePackedDouble(v,h){h.length&&this.writeMessage(v,U2t,h)}writePackedFixed32(v,h){h.length&&this.writeMessage(v,V2t,h)}writePackedSFixed32(v,h){h.length&&this.writeMessage(v,H2t,h)}writePackedFixed64(v,h){h.length&&this.writeMessage(v,G2t,h)}writePackedSFixed64(v,h){h.length&&this.writeMessage(v,W2t,h)}writeBytesField(v,h){this.writeTag(v,2),this.writeBytes(h)}writeFixed32Field(v,h){this.writeTag(v,5),this.writeFixed32(h)}writeSFixed32Field(v,h){this.writeTag(v,5),this.writeSFixed32(h)}writeFixed64Field(v,h){this.writeTag(v,1),this.writeFixed64(h)}writeSFixed64Field(v,h){this.writeTag(v,1),this.writeSFixed64(h)}writeVarintField(v,h){this.writeTag(v,0),this.writeVarint(h)}writeSVarintField(v,h){this.writeTag(v,0),this.writeSVarint(h)}writeStringField(v,h){this.writeTag(v,2),this.writeString(h)}writeFloatField(v,h){this.writeTag(v,5),this.writeFloat(h)}writeDoubleField(v,h){this.writeTag(v,1),this.writeDouble(h)}writeBooleanField(v,h){this.writeVarintField(v,+h)}};function KM(v,h,p){return p?4294967296*h+(v>>>0):4294967296*(h>>>0)+(v>>>0)}function i8e(v,h,p){const w=h<=16383?1:h<=2097151?2:h<=268435455?3:Math.floor(Math.log(h)/(7*Math.LN2));p.realloc(w);for(let T=p.pos-1;T>=v;T--)p.buf[T+w]=p.buf[T]}function z2t(v,h){for(let p=0;p=0&&w>=h&&Q$[this.text.charCodeAt(w)];w--)p--;this.text=this.text.substring(h,p),this.sectionIndex=this.sectionIndex.slice(h,p)}substring(h,p){const w=new YM;return w.text=this.text.substring(h,p),w.sectionIndex=this.sectionIndex.slice(h,p),w.sections=this.sections,w}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((h,p)=>Math.max(h,this.sections[p].scale),0)}addTextSection(h,p){this.text+=h.text,this.sections.push(rR.forText(h.scale,h.fontStack||p));const w=this.sections.length-1;for(let T=0;T=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function s1e(v,h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te=1,Fe=1){const He=YM.fromFeature(v,T,Te,Fe);oe===nx.vertical&&He.verticalizePunctuation(le);let ot=[];const st=function(Ot,Ht,Bt,$t,Es,Os,Hs=1){if(!Ot)return[];const Qs=[],Gs=function(Zs,tr,mr,wr,tn,Mr,Tr=1){let jr=0;for(let Xr=0;Xr=0;let Ss=0;for(let Zs=0;Zs0&&em>za&&(za=em)}else{const tu=Bt[Sl.fontStack];if(!tu)continue;tu[Cl]&&(Kl=tu[Cl]);const Hm=Ht[Sl.fontStack];if(!Hm)continue;const rh=Hm.glyphs[Cl];if(!rh)continue;if(Nc=rh.metrics,Rd=Cl!==8203?Ld:0,Tr){const Dl=Hm.ascender!==void 0?Math.abs(Hm.ascender):0,em=Hm.descender!==void 0?Math.abs(Hm.descender):0,su=(Dl+em)*Wl;Ll-p/2;){if(L--,L<0)return!1;$-=v[L].dist(I),I=v[L]}$+=v[L].dist(v[L+1]),L++;const V=[];let X=0;for(;$

w;)X-=V.shift().angleDelta;if(X>T)return!1;L++,$+=re.dist(oe)}return!0}function x8e(v){let h=0;for(let p=0;pX){const _e=(X-V)/ge,Te=An(oe.x,le.x,_e),Fe=An(oe.y,le.y,_e),He=new cj(Te,Fe,0,le.angleTo(oe),re);return!L||p8e(v,He,$,L,h)?He:void 0}V+=ge}}function eNt(v,h,p,w,T,I,L,$,V){const X=g8e(w,I,L),re=y8e(w,T),oe=re*L,le=v[0].x===0||v[0].x===V||v[0].y===0||v[0].y===V;return h-oe=0&&mt=0&&bt=0&&le+X<=re){const wt=new cj(mt,bt,0,ot,_e);w&&!p8e(v,wt,I,w,T)||ge.push(wt)}}oe+=He}return $||ge.length||L||(ge=v8e(v,oe/2,p,w,T,I,L,!0,V)),ge}function b8e(v){let h=0,p=0;for(const L of v)h+=L.w*L.h,p=Math.max(p,L.w);v.sort((L,$)=>$.h-L.h);const w=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(h/.95)),p),h:1/0}];let T=0,I=0;for(const L of v)for(let $=w.length-1;$>=0;$--){const V=w[$];if(!(L.w>V.w||L.h>V.h)){if(L.x=V.x,L.y=V.y,I=Math.max(I,L.y+L.h),T=Math.max(T,L.x+L.w),L.w===V.w&&L.h===V.h){const X=w.pop();X&&$h.id?1:v.versionh.version?1:v.sxh.sx?1:v.syh.sy?1:0}function o1e(v){let h=0;for(let p=0;p0,_8e(h,w,this.iconDescriptors,I),_8e(p,w,this.patternDescriptors,I),this.iconDescriptors.sort(eU),this.patternDescriptors.sort(eU);let L=0;const $=T?T.data:"";$&&(L=Vv(L,o1e($))),L=Vv(L,1);for(const V of this.iconDescriptors)L=Vv(L,o1e(V.id)),L=Vv(L,V.version),L=Vv(L,V.sx),L=Vv(L,V.sy);L=Vv(L,1);for(const V of this.patternDescriptors)L=Vv(L,o1e(V.id)),L=Vv(L,V.version),L=Vv(L,V.sx),L=Vv(L,V.sy);this.hash=L}subsetOf(h){return this.isSubsetArray(this.iconDescriptors,h.iconDescriptors,eU)&&this.isSubsetArray(this.patternDescriptors,h.patternDescriptors,eU)}isSubsetArray(h,p,w){let T=0,I=0;if(h.length>p.length)return!1;for(;T{const L=T.variant.id.toString().localeCompare(I.variant.id.toString());return L!==0?L:T.variant.sx!==I.variant.sx?T.variant.sx-I.variant.sx:T.variant.sy!==I.variant.sy?T.variant.sy-I.variant.sy:0});const w=new Map;for(const T of p)w.set(T.key,T.value);return w}class w8e{constructor(h){this.sourceAtlasHash=h}}class j8e{constructor(h,p,w,T){const I=new Map,L=new Map;this.haveRenderCallbacks=[];const $=[],V=T!==void 0,X=V?new Map:void 0,re=V?d1e(h,X):h,oe=V?d1e(p,X):p;this.addImages(re,I,1,$),this.addImages(oe,L,2,$);const{w:le,h:ge}=b8e($),_e=new Ch({width:le||1,height:ge||1});for(const[Te,Fe]of re.entries()){const He=I.get(Te).paddedRect;Ch.copy(Fe.data,_e,{x:0,y:0},{x:He.x+1,y:He.y+1},Fe.data,null,Fe.sdf)}for(const[Te,Fe]of oe.entries()){const He=L.get(Te),ot=He.paddedRect;let st=He.padding;const mt=ot.x+st,bt=ot.y+st,wt=Fe.data.width,Gt=Fe.data.height;st=st>1?st-1:st,Ch.copy(Fe.data,_e,{x:0,y:0},{x:mt,y:bt},Fe.data,w),Ch.copy(Fe.data,_e,{x:0,y:Gt-st},{x:mt,y:bt-st},{width:wt,height:st},w),Ch.copy(Fe.data,_e,{x:0,y:0},{x:mt,y:bt+Gt},{width:wt,height:st},w),Ch.copy(Fe.data,_e,{x:wt-st,y:0},{x:mt-st,y:bt},{width:st,height:Gt},w),Ch.copy(Fe.data,_e,{x:0,y:0},{x:mt+wt,y:bt},{width:st,height:Gt},w),Ch.copy(Fe.data,_e,{x:wt-st,y:Gt-st},{x:mt-st,y:bt-st},{width:st,height:st},w),Ch.copy(Fe.data,_e,{x:0,y:Gt-st},{x:mt+wt,y:bt-st},{width:st,height:st},w),Ch.copy(Fe.data,_e,{x:0,y:0},{x:mt+wt,y:bt+Gt},{width:st,height:st},w),Ch.copy(Fe.data,_e,{x:wt-st,y:0},{x:mt-st,y:bt+Gt},{width:st,height:st},w)}this.lut=w,this.image=_e,this.iconPositions=I,this.patternPositions=L,V&&(this.contentDescriptor=new l1e(re,oe,T,w,X))}addImages(h,p,w,T){for(const[I,L]of h.entries()){const{bin:$,imagePosition:V,imageVariant:X}=c1e(I,L,w);p.set(I,V),T.push($),L.hasRenderCallback&&this.haveRenderCallbacks.push(X.id)}}patchUpdatedImages(h,p,w,T){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(I=>h.hasImage(I,w)),h.dispatchRenderCallbacks(this.haveRenderCallbacks,w);for(const I of h.getUpdatedImages(w)){for(const L of this.iconPositions.keys()){const $=Rm.parse(L);if(It.isEqual($.id,I)){const V=h.getImage(I,w);this.patchUpdatedImage(this.iconPositions.get(L),V,p,null)}}for(const L of this.patternPositions.keys()){const $=Rm.parse(L);if(It.isEqual($.id,I)){const V=h.getImage(I,w);this.patchUpdatedImage(this.patternPositions.get(L),V,p,T||this.lut)}}}}patchUpdatedImage(h,p,w,T=null){if(!h||!p||h.version===p.version)return;h.version=p.version;const[I,L]=h.tl,$=h.sdf;if(this.lut||$){const V={width:p.data.width,height:p.data.height},X=new Ch(V);Ch.copy(p.data,X,{x:0,y:0},{x:0,y:0},V,T,$),w.update(X,{position:{x:I,y:L},recreateWhenResize:!1})}else w.update(p.data,{position:{x:I,y:L},recreateWhenResize:!1})}}Wr(nR,"ImagePosition"),Wr(j8e,"ImageAtlas",{omit:["lut"]}),Wr(w8e,"ImageAtlasReference");class aR{constructor(h){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!h||h.useServerFontComposition===void 0||h.useServerFontComposition}loadGlyphRange(h,p,w,T,I){if(this.useServerFontComposition)return void aR.loadGlyphRange(h,p,w,T,I);const L=h.split(",").map($=>$.trim()).filter($=>$.length>0);L.length!==0?L.length!==1?this._loadMultipleFonts(L,p,w,T,I):this._loadFont(L[0],p,w,T,I):I(new Error("Empty fontstack"))}_loadMultipleFonts(h,p,w,T,I){const L=h.map(()=>null),$={completed:0,firstError:null,callbackCalled:!1},V=(X,re,oe)=>{if(!$.callbackCalled&&(re&&!$.firstError&&($.firstError=re),oe&&(L[X]=oe),$.completed++,$.completed===h.length)){$.callbackCalled=!0;const le=L.filter(_e=>_e!==null);if(le.length===0)return void I($.firstError||new Error("All fonts failed to load"));const ge=this._composeGlyphs(le);I(null,ge)}};for(let X=0;X{V(X,re,oe)})}_loadFont(h,p,w,T,I){const L=`${h}:${p}`;if(this.cachedRanges.has(L)){const V=this.cachedRanges.get(L);return void Cd.frame(()=>I(null,V))}const $=this.pendingRequests.get(L);$?$.push(I):(this.pendingRequests.set(L,[I]),aR.loadGlyphRange(h,p,w,T,(V,X)=>{V||this.cachedRanges.set(L,X||null);const re=this.pendingRequests.get(L);if(this.pendingRequests.delete(L),re)for(const oe of re)oe(V,X)}))}_composeGlyphs(h){const p={};let w,T;for(const I of h)if(w===void 0&&I.ascender!==void 0&&(w=I.ascender),T===void 0&&I.descender!==void 0&&(T=I.descender),I.glyphs)for(const L in I.glyphs)p[L]===void 0&&(p[L]=I.glyphs[L]);return{glyphs:p,ascender:w,descender:T}}}aR.loadGlyphRange=function(v,h,p,w,T){const I=256*h,L=I+255,$=w.transformRequest(w.normalizeGlyphsURL(p).replace("{fontstack}",v).replace("{range}",`${I}-${L}`),Lg.Glyphs);X0($,(V,X)=>{if(V)T(V);else if(X){const re={},oe=function(le){return new X$(le).readFields(K2t,{})}(X);for(const le of oe.glyphs)re[le.id]=le;T(null,{glyphs:re,ascender:oe.ascender,descender:oe.descender})}})};const iR=1e20;function N8e(v,h,p,w,T,I,L,$,V){for(let X=h;X-1);V++,I[V]=$,L[V]=X,L[V+1]=iR}for(let $=0,V=0;${if(L){T.ascender=L.ascender,T.descender=L.descender;for(const $ in L.glyphs)this._doesCharSupportLocalGlyph(+$)||(T.glyphs[+$]=L.glyphs[+$]);T.ranges[p]=!0}for(const $ of T.requests[p]||[])$(I,L);delete T.requests[p]}))}getGlyphs(h,p){const w=[],T=this.url||Qn.GLYPHS_URL;for(const I in h)for(const L of h[I])w.push({stack:I,id:L});Ft(w,({stack:I,id:L},$)=>{let V=this.entries[I];V||(V=this.entries[I]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let X=V.glyphs[L];if(X!==void 0)return void $(null,{stack:I,id:L,glyph:X});if(X=this._tinySDF(V,I,L),X)return V.glyphs[L]=X,void $(null,{stack:I,id:L,glyph:X});const re=Math.floor(L/256);if(256*re>65535)return Kr("glyphs > 65535 not supported"),void $(null,{stack:I,id:L,glyph:X});if(V.ranges[re])return void $(null,{stack:I,id:L,glyph:X});let oe=V.requests[re];oe||(oe=V.requests[re]=[],this.glyphLoader.loadGlyphRange(I,re,T,this.requestManager,(le,ge)=>{if(ge){V.ascender=ge.ascender,V.descender=ge.descender;for(const _e in ge.glyphs)this._doesCharSupportLocalGlyph(+_e)||(V.glyphs[+_e]=ge.glyphs[+_e]);V.ranges[re]=!0}for(const _e of oe)_e(le,ge);delete V.requests[re]})),oe.push((le,ge)=>{le?$(le):ge&&$(null,{stack:I,id:L,glyph:ge.glyphs[L]||null})})},(I,L)=>{if(I)p(I);else if(L){const $={};for(const{stack:V,id:X,glyph:re}of L)$[V]===void 0&&($[V]={}),$[V].glyphs===void 0&&($[V].glyphs={}),$[V].glyphs[X]=re&&{id:re.id,bitmap:re.bitmap.clone(),metrics:re.metrics},$[V].ascender=this.entries[V].ascender,$[V].descender=this.entries[V].descender;p(null,$)}})}_doesCharSupportLocalGlyph(h){return this.localGlyphMode!==u1e.none&&(this.localGlyphMode===u1e.all?!!this.localFontFamily:!!this.localFontFamily&&(Qp(h)||vb(h)||Ov(h)||Xp(h)||dy(h)||Gw(h)||(p=h)>=131072&&p<=173791||(w=>w>=66736&&w<=66815)(h)));var p}_tinySDF(h,p,w){const T=this.localFontFamily;if(!T||!this._doesCharSupportLocalGlyph(w))return;let I=h.tinySDF;if(!I){let Fe="400";/bold/i.test(p)?Fe="900":/medium/i.test(p)?Fe="500":/light/i.test(p)&&(Fe="200"),I=h.tinySDF=new tU.TinySDF({fontFamily:T,fontWeight:Fe,fontSize:48,buffer:6,radius:16}),I.fontWeight=Fe}const L=I.fontWeight;if(this.localGlyphs[L][w])return this.localGlyphs[L][w];const $=String.fromCodePoint(w),{data:V,width:X,height:re,glyphWidth:oe,glyphHeight:le,glyphLeft:ge,glyphTop:_e,glyphAdvance:Te}=I.draw($);return this.localGlyphs[L][w]={id:w,bitmap:new jN({width:X,height:re},V),metrics:{width:oe/2,height:le/2,left:ge/2,top:_e/2-27,advance:Te/2,localGlyph:!0}}}}function S8e(v,h){return v+h[1]-h[0]}function h1e(v,h,p,w,T=1){const I=[],L=v.imagePrimary,$=L.pixelRatio,V=L.paddedRect.w-2,X=L.paddedRect.h-2,re=(v.right-v.left)*T,oe=(v.bottom-v.top)*T,le=L.stretchX||[[0,V]],ge=L.stretchY||[[0,X]],_e=le.reduce(S8e,0),Te=ge.reduce(S8e,0),Fe=V-_e,He=X-Te;let ot=0,st=_e,mt=0,bt=Te,wt=0,Gt=Fe,Ot=0,Ht=He;if(L.content&&w){const $t=L.content;ot=sU(le,0,$t[0]),mt=sU(ge,0,$t[1]),st=sU(le,$t[0],$t[2]),bt=sU(ge,$t[1],$t[3]),wt=$t[0]-ot,Ot=$t[1]-mt,Gt=$t[2]-$t[0]-st,Ht=$t[3]-$t[1]-bt}const Bt=($t,Es,Os,Hs)=>{const Qs=rU($t.stretch-ot,st,re,v.left*T),Gs=nU($t.fixed-wt,Gt,$t.stretch,_e),hr=rU(Es.stretch-mt,bt,oe,v.top*T),Ss=nU(Es.fixed-Ot,Ht,Es.stretch,Te),Zs=rU(Os.stretch-ot,st,re,v.left*T),tr=nU(Os.fixed-wt,Gt,Os.stretch,_e),mr=rU(Hs.stretch-mt,bt,oe,v.top*T),wr=nU(Hs.fixed-Ot,Ht,Hs.stretch,Te),tn=new gs(Qs,hr),Mr=new gs(Zs,hr),Tr=new gs(Zs,mr),jr=new gs(Qs,mr),Xr=new gs(Gs/$,Ss/$),ln=new gs(tr/$,wr/$),On=h*Math.PI/180;if(On){const za=Math.sin(On),Ll=Math.cos(On),Wi=[Ll,-za,za,Ll];tn._matMult(Wi),Mr._matMult(Wi),jr._matMult(Wi),Tr._matMult(Wi)}const xn=$t.stretch+$t.fixed,va=Os.stretch+Os.fixed,xi=Es.stretch+Es.fixed,ba=Hs.stretch+Hs.fixed,bi=v.imageSecondary;return{tl:tn,tr:Mr,bl:jr,br:Tr,texPrimary:{x:L.paddedRect.x+1+xn,y:L.paddedRect.y+1+xi,w:va-xn,h:ba-xi},texSecondary:bi?{x:bi.paddedRect.x+1+xn,y:bi.paddedRect.y+1+xi,w:va-xn,h:ba-xi}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Xr,pixelOffsetBR:ln,minFontScaleX:Gt/$/re,minFontScaleY:Ht/$/oe,isSDF:p}};if(L.stretchX||L.stretchY){const $t=C8e(le,Fe,_e),Es=C8e(ge,He,Te);for(let Os=0;Os<$t.length-1;Os++){const Hs=$t[Os],Qs=$t[Os+1];for(let Gs=0;Gs0?[ot,-st]:mt<0?[-ot,st]:ot===0?[st,ot]:[st,-ot]}(p);let ge=Math.abs(h.top-h.bottom);for(const He of h.positionedLines)ge-=He.lineOffset;const _e=h.positionedLines.length,Te=ge/_e;let Fe=h.top-p[1];for(let He=0;He<_e;++He){const ot=h.positionedLines[He];Fe=sNt(h,Te,Fe,He);for(const st of ot.positionedGlyphs){if(!st.rect)continue;const mt=st.rect||{};let bt=4,wt=!0,Gt=1,Ot=0;if(st.image){const Tr=L.get(st.image.toString());if(!Tr)continue;if(Tr.sdf){Kr("SDF images are not supported in formatted text and will be ignored.");continue}wt=!1,Gt=Tr.pixelRatio,bt=1/Gt,Tr.usvg||(Gt/=X)}const Ht=(T||$)&&st.vertical,Bt=st.metrics.advance*st.scale/2,$t=st.metrics,Es=st.rect;if(Es===null)continue;$&&h.verticalizable&&(Ot=st.image?Bt-st.metrics.width*st.scale/2:0);const Os=T?[st.x+Bt,st.y]:[0,0];let Hs=[0,0],Qs=[0,0],Gs=!1;T||(Ht?(Qs=[st.x+Bt+le[0],st.y+le[1]-Ot],Gs=!0):Hs=[st.x+Bt+p[0],st.y+p[1]-Ot]);const hr=Es.w*st.scale/(Gt*(st.localGlyph?2:1)),Ss=Es.h*st.scale/(Gt*(st.localGlyph?2:1));let Zs,tr,mr,wr;if(Ht){const Tr=st.y-Fe,jr=new gs(-Bt,Bt-Tr),Xr=-Math.PI/2,ln=new gs(...Qs);Zs=new gs(-Bt+Hs[0],Hs[1]),Zs._rotateAround(Xr,jr)._add(ln),Zs.x+=-Tr+Bt,Zs.y-=($t.left-bt)*st.scale;const On=st.image?$t.advance*st.scale:Ld*st.scale,xn=String.fromCodePoint(st.glyph);O2t(xn)?Zs.x+=(1-bt)*st.scale:F2t(xn)?Zs.x+=On-$t.height*st.scale+(-bt-1)*st.scale:Zs.x+=st.image||$t.width+2*bt===Es.w&&$t.height+2*bt===Es.h?(On-Ss)/2:(On-($t.height+2*bt)*st.scale)/2,tr=new gs(Zs.x,Zs.y-hr),mr=new gs(Zs.x+Ss,Zs.y),wr=new gs(Zs.x+Ss,Zs.y-hr)}else{const Tr=($t.left-bt)*st.scale-Bt+Hs[0],jr=(-$t.top-bt)*st.scale+Hs[1],Xr=Tr+hr,ln=jr+Ss;Zs=new gs(Tr,jr),tr=new gs(Xr,jr),mr=new gs(Tr,ln),wr=new gs(Xr,ln)}if(oe){let Tr;Tr=T?new gs(0,0):Gs?new gs(le[0],le[1]):new gs(p[0],p[1]),Zs._rotateAround(oe,Tr),tr._rotateAround(oe,Tr),mr._rotateAround(oe,Tr),wr._rotateAround(oe,Tr)}const tn=new gs(0,0),Mr=new gs(0,0);re.push({tl:Zs,tr,bl:mr,br:wr,texPrimary:mt,texSecondary:void 0,writingMode:h.writingMode,glyphOffset:Os,sectionIndex:st.sectionIndex,isSDF:wt,pixelOffsetTL:tn,pixelOffsetBR:Mr,minFontScaleX:0,minFontScaleY:0})}}return re}function rNt(v,h=1,p=!1){let w=1/0,T=1/0,I=-1/0,L=-1/0;const $=v[0];for(let ge=0;ge<$.length;ge++){const _e=$[ge];(!ge||_e.xI)&&(I=_e.x),(!ge||_e.y>L)&&(L=_e.y)}const V=Math.min(I-w,L-T);let X=V/2;const re=new Og([],nNt);if(V===0)return new gs(w,T);for(let ge=w;geoe.d||!oe.d)&&(oe=ge,p&&console.log("found best %d after %d probes",Math.round(1e4*ge.d)/1e4,le)),ge.max-oe.d<=h||(X=ge.h/2,re.push(new XM(ge.p.x-X,ge.p.y-X,X,v)),re.push(new XM(ge.p.x+X,ge.p.y-X,X,v)),re.push(new XM(ge.p.x-X,ge.p.y+X,X,v)),re.push(new XM(ge.p.x+X,ge.p.y+X,X,v)),le+=4)}return p&&(console.log(`num probes: ${le}`),console.log(`best distance: ${oe.d}`)),oe.p}function nNt(v,h){return h.max-v.max}tU.TinySDF=class{constructor({fontSize:v=24,buffer:h=3,radius:p=8,cutoff:w=.25,fontFamily:T="sans-serif",fontWeight:I="normal",fontStyle:L="normal",lang:$=null}={}){this.buffer=h,this.cutoff=w,this.radius=p,this.lang=$;const V=this.size=v+4*h,X=this._createCanvas(V),re=this.ctx=X.getContext("2d",{willReadFrequently:!0});re.font=`${L} ${I} ${v}px ${T}`,re.textBaseline="alphabetic",re.textAlign="left",re.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(v){const h=document.createElement("canvas");return h.width=h.height=v,h}draw(v){const{width:h,actualBoundingBoxAscent:p,actualBoundingBoxDescent:w,actualBoundingBoxLeft:T,actualBoundingBoxRight:I}=this.ctx.measureText(v),L=Math.ceil(p),$=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(I-T))),V=Math.min(this.size-this.buffer,L+Math.ceil(w)),X=$+2*this.buffer,re=V+2*this.buffer,oe=Math.max(X*re,0),le=new Uint8ClampedArray(oe),ge={data:le,width:X,height:re,glyphWidth:$,glyphHeight:V,glyphTop:L,glyphLeft:0,glyphAdvance:h};if($===0||V===0)return ge;const{ctx:_e,buffer:Te,gridInner:Fe,gridOuter:He}=this;this.lang&&(_e.lang=this.lang),_e.clearRect(Te,Te,$,V),_e.fillText(v,Te,Te+L);const ot=_e.getImageData(Te,Te,$,V);He.fill(iR,0,oe),Fe.fill(0,0,oe);for(let st=0;st0?Gt*Gt:0,Fe[wt]=Gt<0?Gt*Gt:0}}N8e(He,0,0,X,re,X,this.f,this.v,this.z),N8e(Fe,Te,Te,$,V,X,this.f,this.v,this.z);for(let st=0;stI.y!=Te.y>I.y&&I.x<(Te.x-_e.x)*(I.y-_e.y)/(Te.y-_e.y)+_e.x&&($=!$),V=Math.min(V,py(I,_e,Te))}}return($?1:-1)*Math.sqrt(V)}(this.p,T),this.max=this.d+this.h*Math.SQRT2}}const aNt=Object.keys,m1e=Number.POSITIVE_INFINITY,iNt=Math.sqrt(2);function CN(v,h,p,w,T,I){const L=n1e(v)&&v.collisionPadding?v.collisionPadding:[0,0,0,0],$={top:v.top-L[1],bottom:v.bottom+L[3],left:v.left-L[0],right:v.right+L[2],scaled:!1};return w!==void 0&&function(V,X){V.top*=X,V.bottom*=X,V.left*=X,V.right*=X,V.scaled=!0}($,w),I&&($.left+=I[0],$.right+=I[0],$.top+=I[1],$.bottom+=I[1]),p&&function(V,X,re){if(!X)return;const oe=ps(X),le=new gs(re?re[0]:0,re?re[1]:0),ge=new gs(V.left,V.top),_e=new gs(V.right,V.top),Te=new gs(V.left,V.bottom),Fe=new gs(V.right,V.bottom);ge._rotateAround(oe,le),_e._rotateAround(oe,le),Te._rotateAround(oe,le),Fe._rotateAround(oe,le),V.left=Math.min(ge.x,_e.x,Te.x,Fe.x),V.right=Math.max(ge.x,_e.x,Te.x,Fe.x),V.top=Math.min(ge.y,_e.y,Te.y,Fe.y),V.bottom=Math.max(ge.y,_e.y,Te.y,Fe.y)}($,p,T),h?{top:Math.min(h.top,$.top),bottom:Math.max(h.bottom,$.bottom),left:Math.min(h.left,$.left),right:Math.max(h.right,$.right),scaled:h.scaled||$.scaled}:$}function A8e(v,[h,p]){let w=0,T=0;if(p===m1e){h<0&&(h=0);const I=h/iNt;switch(v){case"top-right":case"top-left":T=I-7;break;case"bottom-right":case"bottom-left":T=7-I;break;case"bottom":T=7-h;break;case"top":T=h-7}switch(v){case"top-right":case"bottom-right":w=-I;break;case"top-left":case"bottom-left":w=I;break;case"left":w=h;break;case"right":w=-h}}else{switch(h=Math.abs(h),p=Math.abs(p),v){case"top-right":case"top-left":case"top":T=p-7;break;case"bottom-right":case"bottom-left":case"bottom":T=7-p}switch(v){case"top-right":case"bottom-right":case"right":w=-h;break;case"top-left":case"bottom-left":case"left":w=h}}return[w,T]}function oNt(v,h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e){const Te=v.layers[0],Fe=Te.appearances;if(Fe.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const He={iconBBox:null,iconVerticalBBox:null},ot={textBBox:null,textVerticalBBox:null},{baseIconRotate:st,baseTextRotate:mt,iconScaleFactor:bt}=function(Gt,Ot,Ht){const Bt=Gt.get("icon-rotate").evaluate(Ot,{},Ht),$t=Gt.get("text-rotate").evaluate(Ot,{},Ht),[Es,Os]=Gt.get("icon-size-scale-range");return{baseIconRotate:Bt,baseTextRotate:$t,iconScaleFactor:Ke(1,Es,Os)}}(w,T,I);h&&(He.iconBBox=CN(h,He.iconBBox,st),p)&&(He.iconVerticalBBox=CN(p,He.iconVerticalBBox,st+90));const wt=iU(oe.horizontal);wt&&(ot.textBBox=CN(wt,ot.textBBox,mt,1,ge)),oe.vertical&&(ot.textVerticalBBox=CN(oe.vertical,ot.textVerticalBBox,mt+90,1,ge));for(const Gt of Fe)Gt.hasIconLayoutProperties()&&lNt(He,v,Te,Gt,T,I,$,st,L,V,h,X,bt,re,_e),Gt.hasTextLayoutProperties()&&cNt(ot,Te,Gt,T,I,ge,mt,le,wt,oe.vertical);return{iconBBox:He.iconBBox,iconVerticalBBox:He.iconVerticalBBox,textBBox:ot.textBBox,textVerticalBBox:ot.textVerticalBBox}}function lNt(v,h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e){const{appearanceIconOffset:Te,appearanceIconRotate:Fe,appearanceIconSize:He}=M8e(w,p,T,I,L,$,V,X.iconScaleFactor);let ot=null,st=null,mt=null;w.hasLayoutProperty("icon-image")?mt=function(wt,Gt,Ot,Ht,Bt,$t,Es,Os){let Hs=null;const Qs=Gt.getAppearanceValueAndResolveTokens(Ot,"icon-image",Ht,Bt,Os);if(Qs){const Gs=wt.getResolvedImageFromTokens(Qs),hr=Ot.hasLayoutProperty("icon-size")?Ot.getUnevaluatedLayoutProperty("icon-size"):Gt._unevaluatedLayout._values["icon-size"],Ss=oR(Gs,nC(wt.zoom,hr,wt.worldview,Os),hr,Bt,wt.zoom,Ht,wt.pixelRatio,Es,wt.worldview,Os);Hs=$t.get(Ss.iconPrimary.toString())}return Hs}(h,p,w,T,I,oe,le,_e):re&&(mt=re.imagePrimary),mt&&(ot=J$(mt,null,Te,ge),h.allowVerticalPlacement&&(st=J$(mt,null,Te,ge)));const bt=V>0?He/V:1;ot&&(v.iconBBox=CN(ot,v.iconBBox,Fe,bt!==1?bt:void 0)),st&&(v.iconVerticalBBox=CN(st,v.iconVerticalBBox,Fe+90,bt!==1?bt:void 0))}function M8e(v,h,p,w,T,I,L,$){const V=v.hasLayoutProperty("icon-offset")?h.getAppearanceValueAndResolveTokens(v,"icon-offset",p,w,[]):null,X=V&&Array.isArray(V)?V:T,re=v.hasLayoutProperty("icon-rotate")?h.getAppearanceValueAndResolveTokens(v,"icon-rotate",p,w,[]):null,oe=typeof re=="number"?re:I,le=v.hasLayoutProperty("icon-size")?h.getAppearanceValueAndResolveTokens(v,"icon-size",p,w,[]):null;return{appearanceIconOffset:X,appearanceIconRotate:oe,appearanceIconSize:typeof le=="number"?le*$:L}}function cNt(v,h,p,w,T,I,L,$,V,X){const{appearanceTextOffset:re,appearanceTextRotate:oe,appearanceTextSize:le}=I8e(p,h,w,T,I,L,$),ge=le/$,_e=[(re[0]-I[0])*ge,(re[1]-I[1])*ge],Te=_e[0]!==0||_e[1]!==0;V&&(v.textBBox=CN(V,v.textBBox,oe,ge,re,Te?_e:void 0)),X&&(v.textVerticalBBox=CN(X,v.textVerticalBBox,oe+90,ge,re,Te?_e:void 0))}function I8e(v,h,p,w,T,I,L){const $=v.hasLayoutProperty("text-offset")?h.getAppearanceValueAndResolveTokens(v,"text-offset",p,w,[]):null,V=$&&Array.isArray($)?[$[0]*Ld,$[1]*Ld]:T,X=v.hasLayoutProperty("text-rotate")?h.getAppearanceValueAndResolveTokens(v,"text-rotate",p,w,[]):null,re=typeof X=="number"?X:I,oe=v.hasLayoutProperty("text-size")?h.getAppearanceValueAndResolveTokens(v,"text-size",p,w,[]):null;return{appearanceTextOffset:V,appearanceTextRotate:re,appearanceTextSize:typeof oe=="number"?oe:L}}function aU(v,h,p,w,T,I,L,$,V){if(!h||!h.usvg)return;const X=f8e(w),re=f8e(T),oe=I!=="both"&&I!=="width"||!h8e(w)?1:re.width/X.width,le=I!=="both"&&I!=="height"||!m8e(w)?1:re.height/X.height;p.scaleSelf(oe,le);const ge=p.toString();L.set(ge,p),$.set(ge,h);const{imagePosition:_e}=c1e(ge,h,1);V.set(ge,_e)}function P8e(v,h,p,w,T,I,L,$,V,X){if(!v)return;const re=function(oe,le,ge,_e,Te,Fe,He){if(oe.kind==="camera")return oe.maxSize;if(oe.kind==="composite"){const ot=le.possiblyEvaluate(new ja(oe.maxZoom,{worldview:Fe}),ge,He).evaluate(Te,{},ge,He),st=le.possiblyEvaluate(new ja(oe.minZoom,{worldview:Fe}),ge,He).evaluate(Te,{},ge,He);return Math.max(ot,st)}return le.possiblyEvaluate(new ja(_e,{worldview:Fe}),ge,He).evaluate(Te,{},ge,He)}(h,p,w,T,I,V,X);return v.scaleSelf(re*$*L)}function oR(v,h,p,w,T,I,L,$,V,X){return{iconPrimary:P8e(v.getPrimary(),h,p,w,T,I,L,$,V,X),iconSecondary:P8e(v.getSecondary(),h,p,w,T,I,L,$,V,X)}}function dNt(v,h,p){if(!h)return;const w=p.get(v.toString()),T=p.get(h.toString());w&&T&&(w.paddedRect.w===T.paddedRect.w&&w.paddedRect.h===T.paddedRect.h||Kr(`Mismatch in icon variant sizes: ${v.toString()} and ${h.toString()}`),w.usvg!==T.usvg&&Kr(`Mismatch in icon variant image types: ${v.id} and ${h.id}`))}function L8e(v,h,p,w){if(!v)return;const T=h.get(p.toString());if(T&&(v.imagePrimary=T),w){const I=h.get(w.toString());v.imageSecondary=I}}function uNt(v,h){for(const p in v.horizontal)D8e(v.horizontal[p],h);D8e(v.vertical,h)}function D8e(v,h){if(v){for(const p of v.positionedLines)for(const w of p.positionedGlyphs)if(w.image!==null){const T=w.image.toString();w.rect=h.get(T).paddedRect}}}function f1e(v){switch(v){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function hNt(v,h,p,w,T,I,L,$,V){const X=iU(I.horizontal)||I.vertical,re=p.get("icon-text-fit-padding").evaluate(w,{},T);let oe,le=h;return h&&V!=="none"&&(v.allowVerticalPlacement&&I.vertical&&(oe=a1e(h,I.vertical,V,re,$,L)),X&&(le=a1e(h,X,V,re,$,L))),{defaultShapedIcon:le,verticallyShapedIcon:oe}}function R8e(v,h){return v*h/24}function mNt(v,h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot,st,mt,bt,wt,Gt){let Ot=L.textMaxSize.evaluate(h,{},le);Ot===void 0?Ot=$*L.textScaleFactor:Ot*=L.textScaleFactor;const Ht=v.layers[0].layout,Bt=R8e($,L.textScaleFactor),$t=iU(p.horizontal)||p.vertical,Es=v.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),Os=v.getAppearanceFeatureData(h.index);(Fe!=="none"||Es)&&Os&&(Os.textShaping=$t,Os.iconTextFitPadding=Ht.get("icon-text-fit-padding").evaluate(h,{},le),Os.fontScale=Bt,Os.textScaleFactor=L.textScaleFactor);const Hs=ge.name==="globe",Qs=v.tilePixelRatio*Ot/24,Gs=(wr=v.overscaling,v.zoom>18&&wr>2&&(wr>>=1),Math.max(Lr/(512*wr),1)*Ht.get("symbol-spacing")),hr=Ht.get("text-padding")*v.tilePixelRatio,Ss=Ht.get("icon-padding")*v.tilePixelRatio,Zs=ps(Ht.get("text-max-angle")),tr=Ht.get("icon-rotation-alignment")==="map"&&st!=="point",mr=Gs/2;var wr;v.hasAnyIconTextFit===!1&&Fe!=="none"&&(v.hasAnyIconTextFit=!0);const tn=h.properties?+h.properties[Ea]:null,Mr=tn&&v.elevationFeatureIdToIndex?v.elevationFeatureIdToIndex.get(tn):65535,Tr=(jr,Xr,ln)=>{if(Xr.x<0||Xr.x>=Lr||Xr.y<0||Xr.y>=Lr)return;let On=null;if(Hs){const{x:xn,y:va,z:xi}=ge.projectTilePoint(Xr.x,Xr.y,ln);On={anchor:new cj(xn,va,xi,0,void 0),up:ge.upVector(ln,Xr.x,Xr.y)}}(function(xn,va,xi,ba,bi,za,Ll,Wi,Ci,So,Sl,Dd,Cl,Wl,Nc,Kl,sh,Rd,Ha,Vm,sc,tu,Hm,rh,Dl,em,su,NU,a6,Ef,F1e,i6){const dj=xn.addToLineVertexArray(va,ba);let uj,Zg,Xg,dC,o6,ei,ru,Yl=0,xd=0,Qg=0,ax=0,ix=-1,ox=-1;const yy={};let kU=md("");const Kv=xi?xi.anchor:va,l6=NU!=="none";let c6=0,Jc=0;if(Ci._unevaluatedLayout.getValue("text-radial-offset")===void 0){const rc=Ci.layout.get("text-offset").evaluate(sc,{},Dl);c6=rc[0]*Ld,Jc=rc[1]*Ld}else c6=Ci.layout.get("text-radial-offset").evaluate(sc,{},Dl)*Ld,Jc=m1e;if(xn.allowVerticalPlacement&&bi.vertical){const rc=bi.vertical;if(Nc)ei=g1e(rc),Wi&&(ru=g1e(Wi));else{const Gm=Ci.layout.get("text-rotate").evaluate(sc,{},Dl)+90;Xg=oU(So,Kv,va,Sl,Dd,Cl,rc,Wl,Gm,Kl,i6),Wi&&(dC=oU(So,Kv,va,Sl,Dd,Cl,Wi,Rd,Gm,null,F1e))}}if(za){const rc=Ci.layout.get("icon-rotate").evaluate(sc,{},Dl),Gm=h1e(za,rc,Hm,l6,tu.iconScaleFactor),Af=Wi?h1e(Wi,rc,Hm,l6,tu.iconScaleFactor):void 0;Zg=oU(So,Kv,va,Sl,Dd,Cl,za,Rd,rc,null,Ef);const by=function(Yv,wR,d6,Tkt,Ekt,rRe,nRe,Akt,hnr,B1e){const aRe=Yv.layers[0],iRe=aRe.appearances;let u6=wR.length;if(d6&&(u6=Math.max(u6,d6.length)),iRe.length===0)return u6;const[Mkt,Ikt]=Tkt.get("icon-size-scale-range"),Pkt=Ke(1,Mkt,Ikt);for(const EU of iRe)if(EU.hasLayoutProperty("icon-image")){const oRe=aRe.getAppearanceValueAndResolveTokens(EU,"icon-image",rRe,nRe,B1e);if(oRe){const lRe=Yv.getResolvedImageFromTokens(oRe);if(lRe){const cRe=EU.hasLayoutProperty("icon-size")?EU.getUnevaluatedLayoutProperty("icon-size"):Ekt._values["icon-size"],Lkt=oR(lRe,nC(Yv.zoom,cRe,Yv.worldview,B1e),cRe,nRe,Yv.zoom,rRe,Yv.pixelRatio,Pkt,Yv.worldview,B1e),dRe=Akt.get(Lkt.iconPrimary.toString());dRe&&(u6=Math.max(u6,tNt(dRe)))}}}return u6}(xn,Gm,Af,Ci.layout,Ci._unevaluatedLayout,sc,Dl,xn.iconAtlasPositions,0,rh);Yl=4*by;const SU=Ci.layout.get("icon-size").evaluate(sc,{},Dl,rh),CU=tu.compositeIconSizes?tu.compositeIconSizes[0].evaluate(sc,{},Dl,rh):0,z1e=tu.compositeIconSizes?tu.compositeIconSizes[1].evaluate(sc,{},Dl,rh):0,TU=x1e(xn.layerIds[0],xn.iconSizeData,SU,tu.iconScaleFactor,CU,z1e);xn.addSymbols(xn.icon,Gm,TU,Vm,Ha,sc,void 0,xi,va,dj.lineStartIndex,dj.lineLength,-1,rh,Dl,em,su,xn.symbolInstances.length,by),ix=xn.icon.placedSymbolArray.length-1,Af&&(xd=4*by,xn.addSymbols(xn.icon,Af,TU,Vm,Ha,sc,nx.vertical,xi,va,dj.lineStartIndex,dj.lineLength,-1,rh,Dl,em,su,xn.symbolInstances.length,by),ox=xn.icon.placedSymbolArray.length-1)}for(const rc in bi.horizontal){const Gm=rc,Af=bi.horizontal[Gm];uj||(kU=md(Af.text),Nc?o6=g1e(Af):uj=oU(So,Kv,va,Sl,Dd,Cl,Af,Wl,Ci.layout.get("text-rotate").evaluate(sc,{},Dl),Kl,i6));const by=Af.positionedLines.length===1;if(Qg+=O8e(xn,xi,va,Af,Ll,Ci,Nc,sc,Kl,dj,bi.vertical?nx.horizontal:nx.horizontalOnly,by?aNt(bi.horizontal):[Gm],yy,ix,tu,rh,Dl,xn.symbolInstances.length,em),by)break}bi.vertical&&(ax+=O8e(xn,xi,va,bi.vertical,Ll,Ci,Nc,sc,Kl,dj,nx.vertical,["vertical"],yy,ox,tu,rh,Dl,xn.symbolInstances.length,em));let Lc=-1;const gd=(rc,Gm)=>rc?Math.max(rc,Gm):Gm;Lc=gd(o6,Lc),Lc=gd(ei,Lc),Lc=gd(ru,Lc);const vy=Lc>-1?1:0;xn.glyphOffsetArray.length>=65535&&Kr("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),sc.sortKey!==void 0&&xn.addToSortKeyRanges(xn.symbolInstances.length,sc.sortKey),xn.symbolInstances.emplaceBack(va.x,va.y,Kv.x,Kv.y,Kv.z,yy.right>=0?yy.right:-1,yy.center>=0?yy.center:-1,yy.left>=0?yy.left:-1,yy.vertical>=0?yy.vertical:-1,ix,ox,kU,uj!==void 0?uj:xn.collisionBoxArray.length,uj!==void 0?uj+1:xn.collisionBoxArray.length,Xg!==void 0?Xg:xn.collisionBoxArray.length,Xg!==void 0?Xg+1:xn.collisionBoxArray.length,Zg!==void 0?Zg:xn.collisionBoxArray.length,Zg!==void 0?Zg+1:xn.collisionBoxArray.length,dC||xn.collisionBoxArray.length,dC?dC+1:xn.collisionBoxArray.length,Sl,Qg,ax,Yl,xd,vy,0,c6,Jc,Lc,0,l6?1:0,a6)})(v,Xr,On,jr,p,w,I,T,v.layers[0],v.collisionBoxArray,h.index,h.sourceLayerIndex,v.index,hr,ot,X,0,Ss,tr,He,h,L,re,oe,le,_e,Te,Fe,Mr,mt,bt,wt)};if(st==="line")for(const jr of B$(h.geometry,0,0,Lr,Lr)){const Xr=eNt(jr,Gs,Zs,p.vertical||$t,w,24,Qs,v.overscaling,Lr);for(const ln of Xr)$t&&fNt(v,$t.text,mr,ln)||Tr(jr,ln,le)}else if(st==="line-center"){for(const jr of h.geometry)if(jr.length>1){const Xr=J2t(jr,Zs,p.vertical||$t,w,24,Qs);Xr&&Tr(jr,Xr,le)}}else if(h.type==="Polygon")for(const jr of qD(h.geometry,0)){const Xr=rNt(jr,16);Tr(jr[0],new cj(Xr.x,Xr.y,0,0,void 0),le)}else if(h.type==="LineString")for(const jr of h.geometry)Tr(jr,new cj(jr[0].x,jr[0].y,0,0,void 0),le);else if(h.type==="Point")for(const jr of h.geometry)for(const Xr of jr)Tr([Xr],new cj(Xr.x,Xr.y,0,0,void 0),le)}const p1e=255,aC=p1e*lj;function O8e(v,h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot){const st=E8e(0,w,V,I,L,$,T,v.allowVerticalPlacement,void 0,_e.textScaleFactor),mt=I.layout.get("text-size").evaluate($,{},Fe),bt=_e.compositeTextSizes?_e.compositeTextSizes[0].evaluate($,{},Fe):0,wt=_e.compositeTextSizes?_e.compositeTextSizes[1].evaluate($,{},Fe):0,Gt=x1e(v.layerIds[0],v.textSizeData,mt,_e.textScaleFactor,bt,wt);v.addSymbols(v.text,st,Gt,V,L,$,re,h,p,X.lineStartIndex,X.lineLength,ge,Te,Fe,ot,!1,He,st.length);for(const Ot of oe)le[Ot]=v.text.placedSymbolArray.length-1;return 4*st.length}function x1e(v,h,p,w,T,I){const L=h;let $=null;return L.kind==="source"?($=[lj*p*w],$[0]>aC&&Kr(`${v}: Value for "text-size" is >= ${p1e}. Reduce your "text-size".`)):L.kind==="composite"&&($=[lj*T*w,lj*I*w],($[0]>aC||$[1]>aC)&&Kr(`${v}: Value for "text-size" is >= ${p1e}. Reduce your "text-size".`)),$}function iU(v){for(const h in v)return v[h];return null}function oU(v,h,p,w,T,I,L,$,V,X,re){let oe,le,ge,_e;if(oe=re?re.top:L.top,le=re?re.bottom:L.bottom,ge=re?re.left:L.left,_e=re?re.right:L.right,n1e(L)&&L.collisionPadding){const Te=L.collisionPadding;ge-=Te[0],oe-=Te[1],_e+=Te[2],le+=Te[3]}if(V){const Te=new gs(ge,oe),Fe=new gs(_e,oe),He=new gs(ge,le),ot=new gs(_e,le),st=ps(V);let mt=new gs(0,0);X&&(mt=new gs(X[0],X[1])),Te._rotateAround(st,mt),Fe._rotateAround(st,mt),He._rotateAround(st,mt),ot._rotateAround(st,mt),ge=Math.min(Te.x,Fe.x,He.x,ot.x),_e=Math.max(Te.x,Fe.x,He.x,ot.x),oe=Math.min(Te.y,Fe.y,He.y,ot.y),le=Math.max(Te.y,Fe.y,He.y,ot.y)}return v.emplaceBack(h.x,h.y,h.z,p.x,p.y,ge,oe,_e,le,$,w,T,I),v.length-1}function g1e(v){n1e(v)&&v.collisionPadding&&(v.top-=v.collisionPadding[1],v.bottom+=v.collisionPadding[3]);const h=v.bottom-v.top;return h>0?Math.max(10,h):null}function fNt(v,h,p,w){const T=v.compareText;if(h in T){const I=T[h];for(let L=I.length-1;L>=0;L--)if(w.dist(I[L])st&&(mt(wt,Hs,Ot,Ht,Es,Os),mt(Hs,Gt,Es,Os,Bt,$t))}mt(oe,le,w,I,T,I),mt(le,ge,T,I,T,L),mt(ge,_e,T,L,w,L),mt(_e,oe,w,L,w,I),Te-=st,Fe-=st,He+=st,ot+=st;const bt=1/Math.max(He-Te,ot-Fe);return{scale:bt,x:Te*bt,y:Fe*bt,x2:He*bt,y2:ot*bt,projection:h}}function z8e(v,{x:h,y:p},w=0){return new gs(((h-w)*v.scale-v.x)*Lr,(p*v.scale-v.y)*Lr)}const pNt=b(new Float32Array(16));class TN{constructor(h){this.spec=h,this.name=h.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(h,p){return{x:0,y:0,z:0}}unproject(h,p){return new Zt(0,0)}projectTilePoint(h,p,w){return{x:h,y:p,z:0}}locationPoint(h,p,w,T=!0){return h._coordinatePoint(h.locationCoordinate(p,w),T)}pixelsPerMeter(h,p){return hs(1,h)*p}pixelSpaceConversion(h,p,w){return 1}farthestPixelDistance(h){return F8e(h,h.pixelsPerMeter)}pointCoordinate(h,p,w,T){const I=h.horizonLineFromTop(!1),L=new gs(p,Math.max(I,w));return h.rayIntersectionCoordinate(h.pointRayIntersection(L,T))}pointCoordinate3D(h,p,w){const T=new gs(p,w);if(h.elevation)return h.elevation.pointCoordinate(T);{const I=this.pointCoordinate(h,T.x,T.y,0);return[I.x,I.y,I.z]}}isPointAboveHorizon(h,p){if(h.elevation&&h.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(h,p.x,p.y);const w=h.horizonLineFromTop();return p.y0?p<-QM+w&&(p=-QM+w):p>QM-w&&(p=QM-w);const L=I/Math.pow(cU(p),T);let $=L*Math.sin(T*h),V=I-L*Math.cos(T*h);return $=.5*($/Math.PI+.5),V=.5*(V/Math.PI+.5),{x:$,y:this.southernCenter?V:1-V,z:0}}unproject(h,p){h=(2*h-.5)*Math.PI,this.southernCenter&&(p=1-p),p=(2*(1-p)-.5)*Math.PI;const{n:w,f:T}=this,I=T-p,L=Math.sign(I),$=Math.sign(w)*Math.sqrt(h*h+I*I);let V=Math.atan2(h,Math.abs(I))*L;I*w<0&&(V-=Math.PI*Math.sign(h)*L);const X=Ke(Or(V/w)+this.center[0],-180,180),re=Ke(Or(2*Math.atan(Math.pow(T/$,1/w))-QM),-85.051129,qs);return new Zt(X,this.southernCenter?-re:re)}}class B8e extends TN{constructor(h){super(h),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(h,p){return{x:er(h),y:lr(p),z:0}}unproject(h,p){const w=ss(h),T=Ts(p);return new Zt(w,T)}}const $8e=ps(qs);class bNt extends TN{project(h,p){const w=(p=ps(p))*p,T=w*w;return{x:.5*((h=ps(h))*(.8707-.131979*w+T*(T*(.003971*w-.001529*T)-.013791))/Math.PI+.5),y:1-.5*(p*(1.007226+w*(.015085+T*(.028874*w-.044475-.005916*T)))/Math.PI+1),z:0}}unproject(h,p){h=(2*h-.5)*Math.PI;let w=p=(2*(1-p)-1)*Math.PI,T=25,I=0,L=w*w;do{L=w*w;const X=L*L;I=(w*(1.007226+L*(.015085+X*(.028874*L-.044475-.005916*X)))-p)/(1.007226+L*(.045255+X*(.259866*L-.311325-.005916*11*X))),w=Ke(w-I,-$8e,$8e)}while(Math.abs(I)>1e-6&&--T>0);L=w*w;const $=Ke(Or(h/(.8707+L*(L*(L*L*L*(.003971-.001529*L)-.013791)-.131979))),-180,180),V=Or(w);return new Zt($,V)}}const U8e=ps(qs);class _Nt extends TN{project(h,p){p=ps(p),h=ps(h);const w=Math.cos(p),T=2/Math.PI,I=Math.acos(w*Math.cos(h/2)),L=Math.sin(I)/I,$=.5*(h*T+2*w*Math.sin(h/2)/L)||0,V=.5*(p+Math.sin(p)/L)||0;return{x:.5*($/Math.PI+.5),y:1-.5*(V/Math.PI+1),z:0}}unproject(h,p){let w=h=(2*h-.5)*Math.PI,T=p=(2*(1-p)-1)*Math.PI,I=25;const L=1e-6;let $=0,V=0;do{const X=Math.cos(T),re=Math.sin(T),oe=2*re*X,le=re*re,ge=X*X,_e=Math.cos(w/2),Te=Math.sin(w/2),Fe=2*_e*Te,He=Te*Te,ot=1-ge*_e*_e,st=ot?1/ot:0,mt=ot?Math.acos(X*_e)*Math.sqrt(1/ot):0,bt=.5*(2*mt*X*Te+2*w/Math.PI)-h,wt=.5*(mt*re+T)-p,Gt=.5*st*(ge*He+mt*X*_e*le)+1/Math.PI,Ot=st*(Fe*oe/4-mt*re*Te),Ht=.125*st*(oe*Te-mt*re*ge*Fe),Bt=.5*st*(le*_e+mt*He*X)+.5,$t=Ot*Ht-Bt*Gt;$=(wt*Ot-bt*Bt)/$t,V=(bt*Ht-wt*Gt)/$t,w=Ke(w-$,-Math.PI,Math.PI),T=Ke(T-V,-U8e,U8e)}while((Math.abs($)>L||Math.abs(V)>L)&&--I>0);return new Zt(Or(w),Or(T))}}class q8e extends TN{constructor(h){super(h),this.center=h.center||[0,0],this.parallels=h.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(ps(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(h,p){const{scale:w,cosPhi:T}=this;return{x:ps(h)*T*w+.5,y:-Math.sin(ps(p))/T*w+.5,z:0}}unproject(h,p){const{scale:w,cosPhi:T}=this,I=-(p-.5)/w,L=Ke(Or((h-.5)/w)/T,-180,180),$=Math.asin(Ke(I*T,-1,1)),V=Ke(Or($),-85.051129,qs);return new Zt(L,V)}}class wNt extends B8e{constructor(h){super(h),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(h,p,w){const T=RD(h,p,w);return Qe(T,T,OD(Tb(w))),{x:T[0],y:T[1],z:T[2]}}locationPoint(h,p,w){const T=Lt(p.lat,p.lng),I=Ve([],T),L=w?h._centerAltitude+w:h.elevation?h.elevation.getAtPointOrZero(h.locationCoordinate(p),h._centerAltitude):h._centerAltitude;Ee(T,T,I,hs(1,0)*Lr*L);const $=b(new Float64Array(16));return N($,h.pixelMatrix,h.globeMatrix),Qe(T,T,$),new gs(T[0],T[1])}pixelsPerMeter(h,p){return hs(1,0)*p}pixelSpaceConversion(h,p,w){const T=hs(1,h)*p,I=An(hs(1,45)*p,T,w);return this.pixelsPerMeter(h,p)/I}createTileMatrix(h,p,w){const T=uve(Tb(w.canonical));return N(new Float64Array(16),h.globeMatrix,T)}createInversionMatrix(h,p){const{center:w}=h,T=OD(Tb(p));return D(T,T,ps(w.lng)),E(T,T,ps(w.lat)),A(T,T,[h._pixelsPerMercatorPixel,h._pixelsPerMercatorPixel,1]),Float32Array.from(T)}pointCoordinate(h,p,w,T){return aPe(h,p,w,!0)||new on(0,0)}pointCoordinate3D(h,p,w){const T=this.pointCoordinate(h,p,w,0);return[T.x,T.y,T.z]}isPointAboveHorizon(h,p){return!aPe(h,p.x,p.y,!1)}farthestPixelDistance(h){const p=function(T,I){const L=T.cameraToCenterDistance,$=T._centerAltitude*I,V=T._camera,X=T._camera.forward(),re=ue([],xe([],X,-L),[0,0,$]),oe=T.worldSize/(2*Math.PI),le=[0,0,-oe],ge=T.width/T.height,_e=Math.tan(T.fovAboveCenter),Te=xe([],V.up(),_e),Fe=xe([],V.right(),_e*ge),He=Ve([],ue([],ue([],X,Te),Fe)),ot=[];let st;if(new ni(re,He).closestPointOnSphere(le,oe,ot)){const mt=ue([],ot,le),bt=We([],mt,re);st=Math.cos(T.fovAboveCenter)*te(bt)}else{const mt=We([],re,le),bt=We([],le,re);Ve(bt,bt);const wt=te(mt)-oe;st=Math.sqrt(wt*(wt+2*oe));const Gt=Math.acos(st/(oe+wt))-Math.acos(Le(X,bt));st*=Math.cos(Gt)}return 1.01*st}(h,this.pixelsPerMeter(h.center.lat,h.worldSize)),w=aj(h.zoom);if(w>0){const T=F8e(h,hs(1,h.center.lat)*h.worldSize),I=h.worldSize/(2*Math.PI),L=Math.max(h.width,h.height)/h.worldSize*Math.PI;return An(p,T+I*(1-Math.cos(L)),Math.pow(w,10))}return p}upVector(h,p,w){return RD(p,w,h,1)}upVectorScale(h){return{metersToTile:w$(N$(Tb(h)))}}}function V8e(v){const h=v.parallels,p=!!h&&Math.abs(h[0]+h[1])<.01;switch(v.name){case"mercator":return new B8e(v);case"equirectangular":return new yNt(v);case"naturalEarth":return new bNt(v);case"equalEarth":return new gNt(v);case"winkelTripel":return new _Nt(v);case"albers":return p?new q8e(v):new xNt(v);case"lambertConformalConic":return p?new q8e(v):new vNt(v);case"globe":return new wNt(v)}throw new Error(`Invalid projection name: ${v.name}`)}class jNt{constructor(h,p){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=p,this.appearances=h;const w=h.map(T=>function(I){if(!I.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const L=I.condition.expression;return{featureDependent:!ay(L),stateDependent:!iy(L),zoomDependent:!Yh(L,["zoom"]),pitchDependent:!Yh(L,["pitch"]),brightnessDependent:!Yh(L,["brightness","measure-light"]),worldviewDependent:!Yh(L,["worldview"])}}(T));this.anyFeatureDependent=w.some(T=>T.featureDependent),this.anyStateDependent=w.some(T=>T.stateDependent)}update(h,p){const w=this.lastParams,T=!w||w.zoom!==h.zoom||w.pitch!==(h.pitch||0)||w.brightness!==(h.brightness||0)||w.worldview!==h.worldview;this.lastParams={zoom:h.zoom,pitch:h.pitch||0,brightness:h.brightness||0,worldview:h.worldview};const I=p&&this.anyStateDependent;if(!T&&!I&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!I){const L=this.evaluateAllFeatures(h);return L===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=L,{kind:"all-features",appearanceIndex:L})}return{kind:"per-feature"}}evaluateAllFeatures(h){for(let p=0;p{for(let T=0;TL-$),I=new Map;for(const L of T){const $=w.get(L);I.set(L,new jo($))}return p&&(this.cachedBatchIndices=T,this.cachedBatchSegments=I),{batchIndices:T,batchSegments:I}}snapshotSymbolVertexData(h,p){const w=h*e6;return this.layoutVertexArray.uint16.slice(w,w+p*e6)}restoreSymbolVertexData(h,p){this.layoutVertexArray.uint16.set(p,h*e6)}updateSymbolVertexData(h,p,w,T,I,L,$,V,X,re,oe,le,ge){const _e=this.layoutVertexArray.uint16,Te=h*e6;_e[Te]=p,_e[Te+1]=w,_e[Te+2]=T,_e[Te+3]=I,_e[Te+4]=L,_e[Te+5]=$,_e[Te+6]=V,_e[Te+7]=X,_e[Te+8]=re,_e[Te+9]=oe,_e[Te+10]=le,_e[Te+11]=ge}upload(h,p,w,T,I,L){this.isEmpty()||(w&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=h.createVertexBuffer(this.layoutVertexArray,S2t.members,!!L),this.indexBuffer=h.createIndexBuffer(this.indexArray,p),this.dynamicLayoutVertexBuffer=h.createVertexBuffer(this.dynamicLayoutVertexArray,T2t.members,!0),this.opacityVertexBuffer=h.createVertexBuffer(this.opacityVertexArray,kNt,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=h.createVertexBuffer(this.iconTransitioningVertexArray,I2t.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=h.createVertexBuffer(this.globeExtVertexArray,C2t.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||I)&&(this.zOffsetVertexBuffer=h.createVertexBuffer(this.zOffsetVertexArray,E2t.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=h.createVertexBuffer(this.orientationVertexArray,M2t.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=h.createVertexBuffer(this.featureIdArray,A2t.members,!1))),(w||T)&&(this.programConfigurations.upload(h),this.uboBinder&&this.uboBinder.upload(h)))}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())}}Wr(y1e,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class v1e{constructor(h,p,w){this.layoutVertexArray=new h,this.layoutAttributes=p,this.indexArray=new w,this.segments=new jo,this.collisionVertexArray=new H4,this.collisionVertexArrayExt=new $v}upload(h){this.layoutVertexBuffer=h.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=h.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=h.createVertexBuffer(this.collisionVertexArray,P2t.members,!0),this.collisionVertexBufferExt=h.createVertexBuffer(this.collisionVertexArrayExt,L2t.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Wr(v1e,"CollisionBuffers");class Hv{constructor(h){this.collisionBoxArray=h.collisionBoxArray,this.zoom=h.zoom,this.overscaling=h.overscaling,this.layers=h.layers,this.layerIds=this.layers.map(L=>L.fqid),this.index=h.index,this.pixelRatio=h.pixelRatio,this.sourceLayerIndex=h.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=b([]),this.placementViewportMatrix=b([]);const p=this.layers[0]._unevaluatedLayout._values;this.worldview=h.worldview,this.localizable=h.localizable,this.maxUniformBufferBindings=h.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=h.maxUniformBlockSizeDwords,this.disableSymbolUBO=h.disableSymbolUBO,this.textSizeData=nC(this.zoom,p["text-size"],this.worldview,h.availableImages),this.iconSizeData=nC(this.zoom,p["icon-size"],this.worldview,h.availableImages);const w=this.layers[0].layout,T=w.get("symbol-sort-key"),I=w.get("symbol-z-order");this.lut=h.lut,this.canOverlap=w.get("text-allow-overlap")||w.get("icon-allow-overlap")||w.get("text-ignore-placement")||w.get("icon-ignore-placement"),this.sortFeaturesByKey=I!=="viewport-y"&&T.constantOr(1)!==void 0,this.sortFeaturesByY=(I==="viewport-y"||I==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=w.get("text-writing-mode").map(L=>nx[L]),this.stateDependentLayerIds=this.layers.filter(L=>L.isStateDependent()).map(L=>L.id),this.sourceID=h.sourceID,this.projection=h.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(h){const p=this.layers[0].getAppearances();if(!p||p.length===0)return!1;const w=Array.isArray(h)?h:[h];return p.some(T=>w.some(I=>T.hasLayoutProperty(I)))}getAppearanceFeatureData(h){return this.featureAppearanceData.get(h)}createArrays(){this.text=new y1e(new Be(this.layers,{zoom:this.zoom,lut:this.lut},h=>h.startsWith("text")||h.startsWith("symbol"))),this.icon=new y1e(new Be(this.layers,{zoom:this.zoom,lut:this.lut},h=>h.startsWith("icon")||h.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new e1e(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new e1e(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new x$,this.lineVertexArray=new K4,this.symbolInstances=new p$}calculateGlyphDependencies(h,p,w,T,I){for(const L of h){const $=L.codePointAt(0);if($===void 0)break;if(p[$]=!0,T&&I&&$<=65535){const V=sR[L];V&&(p[V.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(h,p,w,T,I,L,$){if(!h.hasLayoutProperty("icon-size"))return $*L;let V=1;const X=h.getUnevaluatedLayoutProperty("icon-size"),re=nC(this.zoom,X,this.worldview,I),oe=ZM(re,p);if(re.kind!=="constant"&&re.kind!=="camera"||(V=oe.uSize),re.kind==="composite"){const{minZoom:le,maxZoom:ge}=re,_e=X.possiblyEvaluate(new ja(le,{worldview:this.worldview}),T),Te=X.possiblyEvaluate(new ja(ge,{worldview:this.worldview}),T),Fe=_e.evaluate(w,{},T,I);V=Fe+(Te.evaluate(w,{},T,I)-Fe)*oe.uSizeT}return re.kind==="source"&&(V=X.possiblyEvaluate(new ja(this.zoom,{worldview:this.worldview}),T).evaluate(w,{},T,I)),V*L}updateFootprints(h,p){}updateReplacement(h,p){if(p.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=p.updateTime;const w=p.getReplacementRegionsForTile(h.toUnwrapped(),!0);return!L$(this.activeReplacements,w)&&(this.activeReplacements=w,!0)}getResolvedImageFromTokens(h){return typeof h=="string"?Ed.build(h):h}populate(h,p,w,T){const I=this.layers[0],L=I.layout,$=this.projection.name==="globe",V=L.get("text-font"),X=L.get("text-field"),re=L.get("icon-image"),[oe,le]=L.get("icon-size-scale-range"),ge=Ke(p.scaleFactor||1,oe,le),[_e,Te]=L.get("text-size-scale-range"),Fe=Ke(p.scaleFactor||1,_e,Te),He=(X.value.kind!=="constant"||X.value.value instanceof Td&&!X.value.value.isEmpty()||X.value.value.toString().length>0)&&(V.value.kind!=="constant"||V.value.value.length>0),ot=re.value.kind!=="constant"||!!re.value.value||Object.keys(re.parameters).length>0,st=this.hasAnyAppearanceLayoutProperty("icon-image"),mt=L.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!He&&!ot&&!st)return;const bt=p.iconDependencies,wt=p.glyphDependencies,Gt=p.availableImages,Ot=new ja(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),Ht=Bt=>{const $t=Bt.id.toString();bt.has($t)?bt.get($t).push(Bt):bt.set($t,[Bt])};for(const Bt of h){const{feature:$t,id:Es,index:Os,sourceLayerIndex:Hs}=Bt,Qs=I._featureFilter.needGeometry,Gs=Fa($t,Qs);if(!I._featureFilter.filter(Ot,Gs,w))continue;if(Qs||(Gs.geometry=zn($t,w,T)),$&&$t.type!==1&&w.z<=5){const Mr=Gs.geometry,Tr=.98078528056,jr=(Xr,ln)=>Le(RD(Xr.x,Xr.y,w,1),RD(ln.x,ln.y,w,1)){if(!Mr.getLayoutProperty("icon-image"))return;const Tr=this.getCombinedIconPrimary(Mr,Zs,Gs,w,Gt,wr,ge);Tr&&Ht(Tr)}),hr){const Mr=V.evaluate(Gs,{},w).join(","),Tr=L.get("text-rotation-alignment")==="map"&&L.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(nx.vertical)>=0;for(const jr of hr.sections)if(jr.image){const Xr=jr.image.getPrimary().scaleSelf(this.pixelRatio*Fe),ln=Xr.id.toString(),On=bt.get(ln)||[];On.push(Xr),bt.set(ln,On)}else{const Xr=kh(hr.toString()),ln=jr.fontStack||Mr,On=wt[ln]=wt[ln]||{};this.calculateGlyphDependencies(jr.text,On,Tr,this.allowVerticalPlacement,Xr)}}}if(L.get("symbol-placement")==="line"&&(this.features=function(Bt){const $t={},Es={},Os=[];let Hs=0;function Qs(Zs){Os.push(Bt[Zs]),Hs++}function Gs(Zs,tr,mr){const wr=Es[Zs];return delete Es[Zs],Es[tr]=wr,Os[wr].geometry[0].pop(),Os[wr].geometry[0]=Os[wr].geometry[0].concat(mr[0]),wr}function hr(Zs,tr,mr){const wr=$t[tr];return delete $t[tr],$t[Zs]=wr,Os[wr].geometry[0].shift(),Os[wr].geometry[0]=mr[0].concat(Os[wr].geometry[0]),wr}function Ss(Zs,tr,mr){const wr=mr?tr[0][tr[0].length-1]:tr[0][0];return`${Zs}:${wr.x}:${wr.y}`}for(let Zs=0;ZsZs.geometry)}(this.features)),L.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",p.elevationFeatures){!this.elevationFeatures&&p.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const Bt of p.elevationFeatures)this.elevationFeatureIdToIndex.set(Bt.id,this.elevationFeatures.length),this.elevationFeatures.push(Bt)}}else L.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Bt,$t)=>Bt.sortKey-$t.sortKey)}getCombinedIconPrimary(h,p,w,T,I,L,$){let V,X;if(h.hasLayoutProperty("icon-image")){const re=p.getAppearanceValueAndResolveTokens(h,"icon-image",w,T,I);V=this.getResolvedImageFromTokens(re)}else{const re=p.getValueAndResolveTokens("icon-image",w,T,I);V=this.getResolvedImageFromTokens(re)}if(V){const re=h.hasLayoutProperty("icon-size")?h.getUnevaluatedLayoutProperty("icon-size"):p._unevaluatedLayout._values["icon-size"];X=oR(V,nC(this.zoom,re,this.worldview,I),re,T,this.zoom,L,this.pixelRatio,$,this.worldview,I).iconPrimary}return X}updateSymbolInstanceIconVertices(h,p,w,T,I,L){const{canonical:$,availableImages:V,globalProperties:X,layer:re,iconScaleFactor:oe,featureState:le,layoutIconOffset:ge,layoutIconSize:_e,layoutIconRotate:Te}=L;if(h.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(p.activeAppearanceIndex===w)return{vertexOffsetDelta:h.numIconVertices,hasChanges:!1};const Fe=w>=0?re.appearances[w]:null;if(Fe){const He=this.getCombinedIconPrimary(Fe,re,T,$,V,{sortKey:void 0,text:void 0,icon:null,index:h.featureIndex,sourceLayerIndex:h.featureIndex,geometry:[],properties:p.properties,type:"Point",id:p.id},oe);if(!He)return{vertexOffsetDelta:0,hasChanges:!1};const ot=He.toString(),st=this.iconAtlasPositions&&this.iconAtlasPositions.get(ot);if(st){const{appearanceIconOffset:mt,appearanceIconRotate:bt}=M8e(Fe,re,T,$,ge,Te,_e,oe);let wt=J$(st,void 0,mt,re.layout.get("icon-anchor").evaluate(T,le,$));const Gt=st.sdf,Ot=re.layout.get("icon-text-fit").constantOr("none");Ot!=="none"&&p.textShaping&&p.iconTextFitPadding&&p.fontScale&&(wt=a1e(wt,p.textShaping,Ot,p.iconTextFitPadding,mt,p.fontScale));const Ht=this.calculateEffectiveAppearanceIconSize(Fe,X.zoom,T,$,V,oe,_e),Bt=0,$t=1+(Math.min(aC,Math.round(Ht*lj))<<1),Es=h1e(wt,bt,Gt,Ot!=="none",oe);p.isUsingAppearanceIconVertexData||(p.isUsingAppearanceIconVertexData=!0,p.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(I,h.numIconVertices));const Os=Math.floor(h.numIconVertices/4),Hs=Math.min(Es.length,Os);let Qs=I;for(let hr=0;hr0||h.numVerticalGlyphVertices>0;if(!mt)return{vertexOffsetDelta:mt?h.numHorizontalGlyphVertices+h.numVerticalGlyphVertices:0,hasChanges:!1};if(p.activeAppearanceIndex===w)return{vertexOffsetDelta:h.numHorizontalGlyphVertices+h.numVerticalGlyphVertices,hasChanges:!1};const bt=w>=0?V.appearances[w]:null;if(bt&&p.textShaping){const{appearanceTextOffset:wt,appearanceTextRotate:Gt,appearanceTextSize:Ot}=I8e(bt,V,T,$,le,_e,ge);p.fontScale=R8e(Ot,p.textScaleFactor);const Ht=bt.getUnevaluatedLayoutProperty("text-size");let Bt=this.textSizeData,$t=He,Es=ot;bt.hasLayoutProperty("text-size")&&(Bt=nC(this.zoom,Ht,this.worldview,st),$t=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Es=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Os=p.textShaping.bottom-le[1],Hs=p.textShaping.left-le[0],Qs=p.textShaping.right-le[0];p.textShaping.top=wt[1]+(p.textShaping.top-le[1]),p.textShaping.bottom=wt[1]+Os,p.textShaping.left=wt[0]+Hs,p.textShaping.right=wt[0]+Qs;const Gs=E8e(0,p.textShaping,wt,V,!1,T,re,this.allowVerticalPlacement,Gt),hr=Ot&&Bt.kind==="composite"?Ht.possiblyEvaluate(new ja($t,{}),$).evaluate(T,oe,$):Te,Ss=Ot&&Bt.kind==="composite"?Ht.possiblyEvaluate(new ja(Es,{}),$).evaluate(T,oe,$):Fe,Zs=x1e(bt.name,Bt,Ot,X,hr,Ss),tr=Array.isArray(Zs)?Zs[1]:Ot,mr=0,wr=1+(Math.min(aC,Math.round(tr*lj))<<1);p.isUsingAppearanceTextVertexData||(p.isUsingAppearanceTextVertexData=!0,p.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(I,h.numHorizontalGlyphVertices+h.numVerticalGlyphVertices));for(let tn=0;tn0){const X=new Set(Object.keys(h).map(re=>{const oe=Number(re);return!isNaN(oe)&&Number.isSafeInteger(oe)&&String(oe)===re?oe:re}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(X,I[0],p,V,w,h,$),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(X,I[0],p,V,w,h,$)}}}updateRoadElevation(h){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let p=!1;const w=nr(h),T=1/w;let I=!1,L=!1;for(let $=0;$0||le>0,Fe=ge>0,He=this.elevationFeatures[V.elevationFeatureIndex];if(He){const ot=new gs(V.tileAnchorX,V.tileAnchorY),st=.075+He.pointElevation(ot);V.zOffset!==st&&(p=!0,V.zOffset=st),st!==0&&(this.hasAnyZOffset=!0);const mt=He.computeSlopeNormal(ot,T),bt=Ut(kt(),ne(0,0,1),mt);nt(X,X,bt),nt(re,re,bt),X[2]*=w,re[2]*=w,X[0]===1&&X[1]===0&&X[2]===0&&re[0]===0&&re[1]===1&&re[2]===0||(I=I||Te,L=L||Fe)}if(Te&&(dU(this.text.orientationVertexArray,oe,X,re),dU(this.text.orientationVertexArray,le,X,re)),Fe){const{placedIconSymbolIndex:ot,verticalPlacedIconSymbolIndex:st}=V;ot>=0&&dU(this.icon.orientationVertexArray,ge,X,re),st>=0&&dU(this.icon.orientationVertexArray,_e,X,re)}}I||(this.text.orientationVertexArray=void 0),L||(this.icon.orientationVertexArray=void 0),p&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const h=(I,L,$)=>{w+=L,w>I.length&&I.resize(w);for(let V=-L;V<0;V++)I.emplace(V+w,$)},p=(I,L,$)=>{T+=L,T>I.length&&I.resize(T);for(let V=-L;V<0;V++)I.emplace(V+T,$)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let w=0,T=0;for(let I=0;I0;if(($>0||V>0)&&(h(this.text.zOffsetVertexArray,$,re),h(this.text.zOffsetVertexArray,V,re)),oe){const{placedIconSymbolIndex:le,verticalPlacedIconSymbolIndex:ge}=L;le>=0&&p(this.icon.zOffsetVertexArray,X,re),ge>=0&&p(this.icon.zOffsetVertexArray,L.numVerticalIconVertices,re)}}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(h,p,w,T,I){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(h),this.iconCollisionBox.upload(h)),this.text.upload(h,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(L=>L.appearances&&L.appearances.length>0)),this.icon.upload(h,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(h,p,w,T,I,L=!1){const $={hasLayoutChanges:!1,hasUboChanges:!1};if(!h||!w||!this.featureAppearanceData)return $;const V=p||{},X=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,re=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!X&&!re)return $;const oe=this.layers[0],le=oe.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===oe.appearancesVersion||(this.featureAppearances=new jNt(oe.appearances,oe.appearancesVersion));const ge=this.featureAppearances.update(T,L);if(ge.kind==="no-changes")return $;let _e=1,Te=0,Fe=!1,He=!1;if(X){const[wt,Gt]=le.get("icon-size-scale-range");_e=Ke(1,wt,Gt)}let ot=1,st=0,mt=!1;if(re){const[wt,Gt]=le.get("text-size-scale-range");ot=Ke(1,wt,Gt)}const bt=new Map;if(I&&w)for(const wt of w){const Gt=I.getImage(wt,oe.scope);if(Gt){const Ot=new Rm(wt.toString());bt.set(Ot.toString(),Gt)}}for(let wt=0;wtQs.isActive({globals:T,feature:$t,canonical:h,featureState:Bt})):-1;Es=Hs>=0?Hs:-1}const Os=Ot.activeAppearanceIndex!==Es;if(re){const Hs=le.get("text-size"),Qs=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Gs=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,hr={canonical:h,layer:oe,featureState:Bt,availableImages:w,textScaleFactor:ot,imageMap:bt,layoutTextOffset:le.get("text-offset").evaluate($t,Bt,h).map(Zs=>Zs*Ld),layoutTextSize:Hs.evaluate($t,Bt,h),layoutTextRotate:le.get("text-rotate").evaluate($t,Bt,h),layoutMinZoomSize:Hs.evaluate($t,{zoom:Qs},h),layoutMaxZoomSize:Hs.evaluate($t,{zoom:Gs},h),layoutTextSizeMinZoom:Qs,layoutTextSizeMaxZoom:Gs},Ss=this.updateSymbolInstanceTextVertices(Gt,Ot,Es,$t,st,hr);st+=Ss.vertexOffsetDelta,mt=mt||Ss.hasChanges}if(X){const Hs={canonical:h,layer:oe,featureState:Bt,availableImages:w,globalProperties:T,iconScaleFactor:_e,layoutIconOffset:le.get("icon-offset").evaluate($t,Bt,h),layoutIconSize:le.get("icon-size").evaluate($t,Bt,h,w),layoutIconRotate:le.get("icon-rotate").evaluate($t,Bt,h)},Qs=this.updateSymbolInstanceIconVertices(Gt,Ot,Es,$t,Te,Hs);Te+=Qs.vertexOffsetDelta,Fe=Fe||Qs.hasChanges}if(Os){const Hs=Gt.featureIndex,Qs=T?T.brightness:null,Gs=Bt||{},hr=Es>=0?oe.appearances[Es]:null;this.text.uboBinder&&(this.text.uboBinder.layer=oe,He=this.text.uboBinder.updateFeaturePaintForAppearance(Hs,$t,Gs,h,w,Qs,hr)||He),this.icon.uboBinder&&(this.icon.uboBinder.layer=oe,He=this.icon.uboBinder.updateFeaturePaintForAppearance(Hs,$t,Gs,h,w,Qs,hr)||He)}Ot.activeAppearanceIndex=Es}return Fe&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),mt&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:Fe||mt,hasUboChanges:He}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=V8e(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(h,p){const w=this.lineVertexArray.length;if(h.segment!==void 0)for(const{x:T,y:I}of p)this.lineVertexArray.emplaceBack(T,I);return{lineStartIndex:w,lineLength:this.lineVertexArray.length-w}}addSymbols(h,p,w,T,I,L,$,V,X,re,oe,le,ge,_e,Te,Fe,He,ot){const st=h.indexArray,mt=h.layoutVertexArray,bt=h.globeExtVertexArray,wt=ot,Gt=h.uboBinder?h.uboBinder.getCurrentBatchIndex():void 0,Ot=h.segments.prepareSegment(4*wt,mt,st,this.canOverlap?L.sortKey:void 0,Gt),Ht=this.glyphOffsetArray.length,Bt=Ot.vertexLength,$t=this.allowVerticalPlacement&&$===nx.vertical?Math.PI/2:0,Es=L.text&&L.text.sections;let Os=mt.length,Hs=-1;for(let hr=0;hr=0)){const hr=4*Qs;for(let Ss=0;Ss=0?p.rightJustifiedTextSymbolIndex:p.centerJustifiedTextSymbolIndex>=0?p.centerJustifiedTextSymbolIndex:p.leftJustifiedTextSymbolIndex>=0?p.leftJustifiedTextSymbolIndex:p.verticalPlacedTextSymbolIndex>=0?p.verticalPlacedTextSymbolIndex:T),L=i1e(this.textSizeData,h,I)/Ld;return this.tilePixelRatio*L}getSymbolInstanceIconSize(h,p,w){const T=this.icon.placedSymbolArray.get(w),I=i1e(this.iconSizeData,h,T);return this.tilePixelRatio*I}_commitDebugCollisionVertexUpdate(h,p,w,T){h.emplaceBack(p,-w,-w,T),h.emplaceBack(p,w,-w,T),h.emplaceBack(p,w,w,T),h.emplaceBack(p,-w,w,T)}_updateTextDebugCollisionBoxes(h,p,w,T,I,L,$){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(h,p){const w=h.placedSymbolArray.get(p),T=w.vertexStartIndex+4*w.numGlyphs;for(let I=w.vertexStartIndex;IT[$]-T[V]||I[V]-I[$]),L}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let h=0;hthis.symbolInstances.get(p).zOffset-this.symbolInstances.get(h).zOffset)}addToSortKeyRanges(h,p){const w=this.sortKeyRanges[this.sortKeyRanges.length-1];w&&w.sortKey===p?w.symbolInstanceEnd=h+1:this.sortKeyRanges.push({sortKey:p,symbolInstanceStart:h,symbolInstanceEnd:h+1})}sortFeatures(h){if(this.sortFeaturesByY&&this.sortedAngle!==h)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(h),this.sortedAngle=h,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const p of this.symbolInstanceIndexes){const w=this.symbolInstances.get(p);this.featureSortOrder.push(w.featureIndex);const{rightJustifiedTextSymbolIndex:T,centerJustifiedTextSymbolIndex:I,leftJustifiedTextSymbolIndex:L,verticalPlacedTextSymbolIndex:$,placedIconSymbolIndex:V,verticalPlacedIconSymbolIndex:X}=w;T>=0&&this.addIndicesForPlacedSymbol(this.text,T),I>=0&&I!==T&&this.addIndicesForPlacedSymbol(this.text,I),L>=0&&L!==I&&L!==T&&this.addIndicesForPlacedSymbol(this.text,L),$>=0&&this.addIndicesForPlacedSymbol(this.text,$),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(h,p){const w=(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 I of T){const L=this.symbolInstances.get(I.index);I.rotatedY=0|Math.round(h*L.tileAnchorX+p*L.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let T=0;TI.rotatedY-L.rotatedY||L.featureIndex-I.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(h,p){for(const w of h){const T=w.batchIndex;if(T===void 0)continue;const I=p.get(T);if(!I){w.primitiveOffset=this.text.indexArray.length,w.primitiveLength=0;continue}w.primitiveOffset=this.text.indexArray.length;const L=this.text.indexArray.length;for(const{index:$}of I){const V=this.symbolInstances.get($),{rightJustifiedTextSymbolIndex:X,centerJustifiedTextSymbolIndex:re,leftJustifiedTextSymbolIndex:oe,verticalPlacedTextSymbolIndex:le}=V;X>=0&&this.addIndicesForPlacedSymbol(this.text,X),re>=0&&re!==X&&this.addIndicesForPlacedSymbol(this.text,re),oe>=0&&oe!==re&&oe!==X&&this.addIndicesForPlacedSymbol(this.text,oe),le>=0&&this.addIndicesForPlacedSymbol(this.text,le)}w.primitiveLength=this.text.indexArray.length-L}}rebuildIconSegmentIndices(h,p){for(const w of h){const T=w.batchIndex;if(T===void 0)continue;const I=p.get(T);if(!I){w.primitiveOffset=this.icon.indexArray.length,w.primitiveLength=0;continue}w.primitiveOffset=this.icon.indexArray.length;const L=this.icon.indexArray.length;for(const{index:$}of I){const V=this.symbolInstances.get($),{placedIconSymbolIndex:X,verticalPlacedIconSymbolIndex:re}=V;X>=0&&this.addIndicesForPlacedSymbol(this.icon,X),re>=0&&this.addIndicesForPlacedSymbol(this.icon,re)}w.primitiveLength=this.icon.indexArray.length-L}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const h=Math.sin(this.sortedAngle),p=Math.cos(this.sortedAngle),w=this.getOrCreateSortedSymbolsByBatch(h,p),T=Array.from(w.keys()).sort((I,L)=>I-L);for(const I of T){const L=w.get(I);for(const{index:$}of L){const V=this.symbolInstances.get($);this.featureSortOrder.push(V.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),w),this.rebuildIconSegmentIndices(this.icon.segments.get(),w),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(h){const p=this.symbolInstances.get(this.text.symbolInstanceIndices[h]).elevationFeatureIndex;let w;return this.elevationFeatures&&pw in v?String(v[w]):"")}let G8e,W8e,b1e;Wr(Hv,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),Hv.addDynamicAttributes=JM;class K8e{constructor(h){this.type=h.property.overrides?h.property.overrides.runtimeType:ip,this.defaultValue=h}evaluate(h){if(h.formattedSection){const p=this.defaultValue.property.overrides;if(p&&p.hasOverride(h.formattedSection))return p.getOverride(h.formattedSection)}return h.feature&&h.featureState?this.defaultValue.evaluate(h.feature,h.featureState):this.defaultValue.property.specification.default}eachChild(h){this.defaultValue.isConstant()||h(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Wr(K8e,"FormatSectionOverride",{omit:["defaultValue"]});const _1e=()=>b1e||(b1e={layout:G8e||(G8e=new Io({"symbol-placement":new yr(as.layout_symbol["symbol-placement"]),"symbol-spacing":new yr(as.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new yr(as.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new gr(as.layout_symbol["symbol-sort-key"]),"symbol-z-order":new yr(as.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new yr(as.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new yr(as.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new yr(as.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new yr(as.layout_symbol["icon-ignore-placement"]),"icon-optional":new yr(as.layout_symbol["icon-optional"]),"icon-rotation-alignment":new yr(as.layout_symbol["icon-rotation-alignment"]),"icon-size":new gr(as.layout_symbol["icon-size"]),"icon-size-scale-range":new yr(as.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new gr(as.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new gr(as.layout_symbol["icon-text-fit-padding"]),"icon-image":new gr(as.layout_symbol["icon-image"]),"icon-image-use-theme":new yr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new gr(as.layout_symbol["icon-rotate"]),"icon-padding":new yr(as.layout_symbol["icon-padding"]),"icon-keep-upright":new yr(as.layout_symbol["icon-keep-upright"]),"icon-offset":new gr(as.layout_symbol["icon-offset"]),"icon-anchor":new gr(as.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new yr(as.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new yr(as.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new yr(as.layout_symbol["text-rotation-alignment"]),"text-field":new gr(as.layout_symbol["text-field"]),"text-font":new gr(as.layout_symbol["text-font"]),"text-size":new gr(as.layout_symbol["text-size"]),"text-size-scale-range":new yr(as.layout_symbol["text-size-scale-range"]),"text-max-width":new gr(as.layout_symbol["text-max-width"]),"text-line-height":new gr(as.layout_symbol["text-line-height"]),"text-letter-spacing":new gr(as.layout_symbol["text-letter-spacing"]),"text-justify":new gr(as.layout_symbol["text-justify"]),"text-radial-offset":new gr(as.layout_symbol["text-radial-offset"]),"text-variable-anchor":new yr(as.layout_symbol["text-variable-anchor"]),"text-anchor":new gr(as.layout_symbol["text-anchor"]),"text-max-angle":new yr(as.layout_symbol["text-max-angle"]),"text-writing-mode":new yr(as.layout_symbol["text-writing-mode"]),"text-rotate":new gr(as.layout_symbol["text-rotate"]),"text-padding":new yr(as.layout_symbol["text-padding"]),"text-keep-upright":new yr(as.layout_symbol["text-keep-upright"]),"text-transform":new gr(as.layout_symbol["text-transform"]),"text-offset":new gr(as.layout_symbol["text-offset"]),"text-allow-overlap":new yr(as.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new yr(as.layout_symbol["text-ignore-placement"]),"text-optional":new yr(as.layout_symbol["text-optional"]),visibility:new yr(as.layout_symbol.visibility)})),paint:W8e||(W8e=new Io({"icon-opacity":new gr(as.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new gr(as.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new gr(as.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new gr(as.paint_symbol["text-emissive-strength"]),"icon-color":new gr(as.paint_symbol["icon-color"]),"icon-halo-color":new gr(as.paint_symbol["icon-halo-color"]),"icon-halo-width":new gr(as.paint_symbol["icon-halo-width"]),"icon-halo-blur":new gr(as.paint_symbol["icon-halo-blur"]),"icon-translate":new yr(as.paint_symbol["icon-translate"]),"icon-translate-anchor":new yr(as.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new yr(as.paint_symbol["icon-image-cross-fade"]),"text-opacity":new gr(as.paint_symbol["text-opacity"]),"text-occlusion-opacity":new gr(as.paint_symbol["text-occlusion-opacity"]),"text-color":new gr(as.paint_symbol["text-color"],{runtimeType:bh,getOverride:v=>v.textColor,hasOverride:v=>!!v.textColor}),"text-halo-color":new gr(as.paint_symbol["text-halo-color"]),"text-halo-width":new gr(as.paint_symbol["text-halo-width"]),"text-halo-blur":new gr(as.paint_symbol["text-halo-blur"]),"text-translate":new yr(as.paint_symbol["text-translate"]),"text-translate-anchor":new yr(as.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new yr(as.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new yr(as.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new yr(as.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new yr(as.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new gr(as.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"})}))},b1e);class uU extends no{constructor(h,p,w,T){super(h,_1e(),p,w,T,h.layout?h.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=b([]),this.hasOcclusionOpacityProperties=h.paint!==void 0&&("icon-occlusion-opacity"in h.paint||"text-occlusion-opacity"in h.paint)}_handleSpecialPaintPropertyUpdate(h){h!=="icon-occlusion-opacity"&&h!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(h,p){super.recalculate(h,p),this.appearances&&this.appearances.forEach(T=>{T.recalculate(h,p,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 w=this.layout.get("text-writing-mode");if(w){const T=[];for(const I of w)T.indexOf(I)<0&&T.push(I);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(h,p,w,T){return this._saturation===h&&this._contrast===p&&this._brightnessMin===w&&this._brightnessMax===T||(this._colorAdjustmentMatrix=function(I,L,$,V){I=Hi(I),L=Qa(L);const X=y(),re=I/3,oe=1-2*re,le=[oe,re,re,0,re,oe,re,0,re,re,oe,0,0,0,0,1],ge=.5-.5*L,_e=V-$;return N(X,[_e,0,0,0,0,_e,0,0,0,0,_e,0,$,$,$,1],[L,0,0,0,0,L,0,0,0,0,L,0,ge,ge,ge,1]),N(X,X,le),X}(h,p,w,T),this._saturation=h,this._contrast=p,this._brightnessMin=w,this._brightnessMax=T),this._colorAdjustmentMatrix}getValueAndResolveTokens(h,p,w,T){const I=this.layout.get(h).evaluate(p,{},w,T),L=this._unevaluatedLayout._values[h];return L.isDataDriven()||cy(L.value)||!I?I:H8e(p.properties,I)}getAppearanceValueAndResolveTokens(h,p,w,T,I){const L=h.getLayoutProperty(p);if(!L)return;const $=L.evaluate(w,{},T,I),V=h.getUnevaluatedLayoutProperties()._values[p];return V.isDataDriven()||cy(V.value)||!$||typeof $!="string"?$:H8e(w.properties,$)}createBucket(h){return new Hv(h)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const h of _1e().paint.overridableProperties){if(!uU.hasPaintOverride(this.layout,h))continue;const p=this.paint.get(h),w=new K8e(p),T=new Rv(w,p.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let I=null;I=p.value.kind==="constant"||p.value.kind==="source"?new Ug("source",T):new Zp("composite",T,p.value.zoomStops,p.value.interpolationType),this.paint._values[h]=new zv(p.property,I,p.parameters)}}_handleOverridablePaintPropertyUpdate(h,p,w){return!(!this.layout||p.isDataDriven()||w.isDataDriven())&&uU.hasPaintOverride(this.layout,h)}static hasPaintOverride(h,p){const w=h.get("text-field"),T=_1e().paint.properties[p];let I=!1;const L=$=>{for(const V of $)if(T.overrides&&T.overrides.hasOverride(V))return void(I=!0)};if(w.value.kind==="constant"&&w.value.value instanceof Td)L(w.value.value.sections);else if(w.value.kind==="source"){const $=X=>{I||(X instanceof Jr&&kl(X.value)===J0?L(X.value.sections):X instanceof Wh?L(X.sections):X.eachChild($))},V=w.value;V._styleExpression&&$(V._styleExpression.expression)}return I}getProgramIds(){return["symbol"]}getDefaultProgramParams(h,p,w){return{config:new Ae(this,{zoom:p,lut:w}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let Y8e,Z8e,X8e,Q8e;var hU=rr([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function mU(v,h,p,w,T,I,L,$){const V=[v,h,1,p,w,1,T,I,1],X=[L,$,1],re=f([],V),[oe,le,ge]=we(X,X,re);return x(V,V,[oe,0,0,0,le,0,0,0,ge])}function J8e(v,h,p,w,T,I,L,$){const V=function(X,re,oe,le,ge,_e,Te,Fe){const He=mU(0,0,1,0,1,1,0,1),ot=mU(X,re,oe,le,ge,_e,Te,Fe);return x(ot,ot,f([],He))}(v,h,p,w,T,I,L,$);return[V[2]/V[8]/Lr,V[5]/V[8]/Lr]}function fU(v){return[v[0],Math.min(Math.max(v[1],-85.051129),qs)]}class eDe extends xf{constructor(h,p,w,T){super(),this.id=h,this.dispatcher=w,this.coordinates=p.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=p,this._dirty=!1}load(h,p){if(this._loaded=p||!1,this.fire(new _c("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return h&&(this.coordinates=h),this._loaded=!0,void this._finishLoading();this._imageRequest=Up(this.map._requestManager.transformRequest(this.url,Lg.Image),(w,T)=>{this._imageRequest=null,this._loaded=!0,w?this.fire(new Lm(w)):T&&(this.image=T,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,h&&(this.coordinates=h),this._finishLoading())})}loaded(){return this._loaded}updateImage(h){return h.url?(this._imageRequest&&h.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=h.url,this.load(h.coordinates,this._loaded),this):this}setTexture(h){if(!(h.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new JD(this.map.painter.context,h.handle),this.width=h.dimensions[0],this.height=h.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new _c("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(h){this.map=h,this.load()}onRemove(h){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof JD||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(h){if(this.coordinates=h,this._boundsArray=void 0,this._unsupportedCoords=!1,!h.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let p=h[0][1],w=h[0][1];for(const I of h)I[1]>w&&(w=I[1]),I[1]qs?this.onNorthPole=!0:T<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const I=h.map(on.fromLngLat);this.tileID=function(L){let $=1/0,V=1/0,X=-1/0,re=-1/0;for(const Te of L)$=Math.min($,Te.x),V=Math.min(V,Te.y),X=Math.max(X,Te.x),re=Math.max(re,Te.y);const oe=Math.max(X-$,re-V),le=Math.max(0,Math.floor(-Math.log2(oe))),ge=Math.pow(2,le);let _e=Math.floor(($+X)/2*ge);return _e>1&&(_e-=1),new J4(le,_e,Math.floor((V+re)/2*ge))}(I),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new _c("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof JD||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(h){for(const Fe in this.tiles){const He=this.tiles[Fe];He.state!=="loaded"&&(He.state="loaded",He.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const p=iC(new J4(0,0,0),this.map.transform.projection),w=[p.projection.project(this.coordinates[0][0],this.coordinates[0][1]),p.projection.project(this.coordinates[1][0],this.coordinates[1][1]),p.projection.project(this.coordinates[2][0],this.coordinates[2][1]),p.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Fe){const He=Fe[1].x-Fe[0].x,ot=Fe[1].y-Fe[0].y,st=Fe[2].x-Fe[1].x,mt=Fe[2].y-Fe[1].y,bt=Fe[3].x-Fe[2].x,wt=Fe[3].y-Fe[2].y,Gt=Fe[0].x-Fe[3].x,Ot=Fe[0].y-Fe[3].y,Ht=He*mt-st*ot,Bt=st*wt-bt*mt,$t=bt*Ot-Gt*wt,Es=Gt*ot-He*Ot;return Ht>0&&Bt>0&&$t>0&&Es>0||Ht<0&&Bt<0&&$t<0&&Es<0}(w))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const T=iC(this.tileID,this.map.transform.projection),[I,L,$,V]=this.coordinates.map(Fe=>{const He=T.projection.project(Fe[0],Fe[1]);return z8e(T,He)._round()});this.perspectiveTransform=J8e(I.x,I.y,L.x,L.y,$.x,$.y,V.x,V.y);const X=this._boundsArray=new Ja;X.emplaceBack(I.x,I.y,0,0),X.emplaceBack(L.x,L.y,Lr,0),X.emplaceBack(V.x,V.y,0,Lr),X.emplaceBack($.x,$.y,Lr,Lr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=h.createVertexBuffer(X,hU.members),this.boundsSegments=jo.simpleSegment(0,0,4,2);const re=[],oe=function(Fe){return[fU(Fe[0]),fU(Fe[1]),fU(Fe[2]),fU(Fe[3])]}(this.coordinates),[le,ge,_e,Te]=function(Fe){let He=Fe[0][0],ot=He,st=Fe[0][1],mt=st;for(let bt=1;btot&&(ot=Fe[bt][0]),Fe[bt][1]mt&&(mt=Fe[bt][1]);return[He,st,ot-He,mt-st]}(oe);{const Fe=new Ja,[He,ot,st,mt]=function(Gs){let hr=Gs[0].x,Ss=hr,Zs=Gs[0].y,tr=Zs;for(let mr=1;mrSs&&(Ss=Gs[mr].x),Gs[mr].ytr&&(tr=Gs[mr].y);return[hr,Zs,Ss-hr,tr-Zs]}(w),bt=Gs=>[(Gs.x-He)/st,(Gs.y-ot)/mt],[wt,Gt,Ot,Ht]=w.map(bt),Bt=function(Gs,hr,Ss,Zs,tr,mr,wr,tn){const Mr=mU(0,0,1,0,1,1,0,1);return x(Mr,Mr,f([],mU(Gs,hr,Ss,Zs,tr,mr,wr,tn)))}(wt[0],wt[1],Gt[0],Gt[1],Ot[0],Ot[1],Ht[0],Ht[1]);this.elevatedGlobePerspectiveTransform=J8e(wt[0],wt[1],Gt[0],Gt[1],Ot[0],Ot[1],Ht[0],Ht[1]);const $t=(Gs,hr)=>{re.push(Gs.lng);const Ss=Math.round((Gs.lng-le)/_e*Lr),Zs=Math.round((Gs.lat-ge)/Te*Lr),tr=bt(hr),mr=we([],[tr[0],tr[1],1],Bt),wr=Math.round(mr[0]/mr[2]*Lr),tn=Math.round(mr[1]/mr[2]*Lr);Fe.emplaceBack(Ss,Zs,wr,tn)},Es=w[3].x-w[0].x,Os=w[3].y-w[0].y,Hs=w[2].x-w[1].x,Qs=w[2].y-w[1].y;for(let Gs=0;Gs<65;Gs++){const hr=Gs/64,Ss=[w[0].x+hr*Es,w[0].y+hr*Os],Zs=[w[1].x+hr*Hs,w[1].y+hr*Qs],tr=Zs[0]-Ss[0],mr=Zs[1]-Ss[1];for(let wr=0;wr<65;wr++){const tn=wr/64,Mr={x:Ss[0]+tr*tn,y:Ss[1]+mr*tn};$t(p.projection.unproject(Mr.x,Mr.y),Mr)}}this.elevatedGlobeVertexBuffer=h.createVertexBuffer(Fe,hU.members)}{this.maxLongitudeTriangleSize=0;let Fe=[],He=new Gl;const ot=(st,mt,bt)=>{He.emplaceBack(st,mt,bt);const wt=re[st],Gt=re[mt],Ot=re[bt],Ht=Math.min(Math.min(wt,Gt),Ot),Bt=Math.max(Math.max(wt,Gt),Ot)-Ht;Bt>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Bt),Fe.push(Ht+Bt/2)};for(let st=0;st<64;st++)for(let mt=0;mt<64;mt++){const bt=65*st+mt,wt=bt+1,Gt=bt+65,Ot=Gt+1;ot(bt,Gt,wt),ot(wt,Gt,Ot)}[Fe,He]=function(st,mt){const bt=Array.from({length:st.length},(Ot,Ht)=>Ht);bt.sort((Ot,Ht)=>st[Ot]-st[Ht]);const wt=[],Gt=new Gl;for(let Ot=0;Ot{L.segments.push({vertexOffset:0,primitiveOffset:oe,vertexLength:p.segments[0].vertexLength,primitiveLength:le,sortKey:void 0,vaos:{}})},V=.51*this.maxLongitudeTriangleSize;if(Math.abs(w[0]-T)<=V){const oe=zi(w,0,w.length,T+V);return oe===w.length||$(oe,Fi(w,oe+1,w.length,T+360-V)-oe),L}T0}}let sDe,rDe,nDe,aDe,iDe,oDe,lDe;class cDe extends no{constructor(h,p,w,T){super(h,{layout:sDe||(sDe=new Io({visibility:new yr(as["layout_raster-particle"].visibility)})),paint:rDe||(rDe=new Io({"raster-particle-array-band":new yr(as["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new yr(as["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Sf(as["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new yr(as["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new yr(as["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new yr(as["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new yr(as["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new yr(as["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"})}))},p,w,T),this._updateColorRamp(),this.lastInvalidatedAt=Cd.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(h){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(h){return!1}_handleSpecialPaintPropertyUpdate(h){h!=="raster-particle-color"&&h!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),h==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const h=this._transitionablePaint._values["raster-particle-color"].value.expression,p=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=FD({expression:h,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:p}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=Cd.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class TNt extends no{constructor(h,p){super(h,{},p,null),this.implementation=h,h.slot&&(this.slot=h.slot)}is3D(h){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(h){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(h){this.implementation.onAdd&&this.implementation.onAdd(h,h.painter.context.gl)}onRemove(h){this.implementation.onRemove&&this.implementation.onRemove(h,h.painter.context.gl)}}function j1e(v,h,p){const w=[0,0,1],T=St([]);return es(T,T,p?-ps(v)+Math.PI:ps(v)),Yt(T,T,-ps(h)),nt(w,w,T),Ve(w,w)}class pU{constructor(h,p,w,T){this.message=(h?`${h}: `:"")+w,T&&(this.identifier=T),p!=null&&p.__line__&&(this.line=p.__line__)}}function N1e(v,h){const p=v.indexOf("://")===-1;try{return new URL(v,p&&h?"http://example.com":void 0),!0}catch{return!1}}class dDe{constructor(h,p){this.feature=h,this.instancedDataOffset=p,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class uDe{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new ED,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(h){const p=16*h,w=this.instancedDataArray.float32;let T=Math.floor(w[p+2]);const I=1.05*(w[p+2]-T);return T/=100,[w[p]%1*1.05,w[p+1]%1*1.05,I,T]}tileCoordinatesForInstance(h){const p=16*h,w=this.instancedDataArray.float32;let T=w[p+0];return T=T>Lr?T-Lr:T,new gs(Math.trunc(T),Math.trunc(w[p+1]))}translationForInstance(h){const p=16*h,w=this.instancedDataArray.float32;return[w[p+4],w[p+5],w[p+6]]}rotationScaleForInstance(h){const p=16*h,w=this.instancedDataArray.float32;return[w[p+7],w[p+8],w[p+9],w[p+10],w[p+11],w[p+12],w[p+13],w[p+14],w[p+15]]}transformForInstance(h){const p=16*h,w=this.instancedDataArray.float32;return[w[p+7],w[p+8],w[p+9],w[p+4],w[p+10],w[p+11],w[p+12],w[p+5],w[p+13],w[p+14],w[p+15],w[p+6],0,0,0,1]}}class k1e{constructor(h){this.zoom=h.zoom,this.canonical=h.canonical,this.overscaledZ=this.canonical.z+Math.log2(h.overscaling),this.layers=h.layers,this.layerIds=this.layers.map(p=>p.fqid),this.projection=h.projection,this.index=h.index,this.worldview=h.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(p=>p.isStateDependent()).map(p=>p.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=h.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(h,p){}updateAppearances(h,p,w,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(h,p,w,T){this.tileToMeter=nr(w);const I=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const L=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?p.elevationFeatures:void 0;for(const{feature:$,id:V,index:X,sourceLayerIndex:re}of h){const oe=V??($.properties&&$.properties.hasOwnProperty("id")?$.properties.id:void 0),le=Fa($,I);if(!this.layers[0]._featureFilter.filter(new ja(this.zoom,{worldview:this.worldview,activeFloors:p.activeFloors}),le,w))continue;const ge={id:oe,sourceLayerIndex:re,index:X,geometry:I?le.geometry:zn($,w,T),properties:$.properties,type:$.type,patterns:{}},_e=this.addFeature(ge,ge.geometry,le,L,w);_e&&p.featureIndex.insert($,ge.geometry,X,re,this.index,this.instancesPerModel[_e].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const h=this.layers[0].modelManager,p=this.layers[0].scope;let w=0;for(const T of this.modelUris){const I=h.getModel(T,p);if(!I)continue;const L=this.instancesPerModel[T];if(L){const $=.5*Me(I.aabb.max,I.aabb.min)*L.maxScale+L.maxXYTranslationDistance,V=Math.min(Lr,Math.max($/this.tileToMeter,256));w=Math.max(V,w)}}return w}update(h,p,w,T){for(const I in this.instancesPerModel){const L=this.instancesPerModel[I];for(const $ in h)L.idToFeaturesIndex.hasOwnProperty($)&&(this.evaluate(L.features[L.idToFeaturesIndex[$]],h[$],L,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let h=!1;for(const p in this.instancesPerModel){const w=this.instancesPerModel[p];for(const T of w.features){const I=this.layers[0],L=T.feature,$=this.canonical,V=I.paint.get("model-rotation").evaluate(L,{},$),X=I.paint.get("model-scale").evaluate(L,{},$),re=I.paint.get("model-translation").evaluate(L,{},$);Ge(T.rotation,V)&&Ge(T.scale,X)&&Ge(T.translation,re)||(this.evaluate(T,T.featureStates,w,!0),h=!0)}}return h}updateReplacement(h,p,w,T){if(p.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=p.updateTime;const I=p.getReplacementRegionsForTile(h.toUnwrapped(),!0);if(L$(this.activeReplacements,I))return!1;this.activeReplacements=I;let L=!1;for(const $ in this.instancesPerModel){const V=this.instancesPerModel[$],X=V.instancedDataArray;for(const re of V.features){const oe=re.instancedDataOffset,le=re.instancedDataCount;for(let ge=0;geLr;Te=Fe?Te-Lr:Te;const He=Math.floor(Te),ot=Math.floor(X.float32[_e+1]);let st=!1;for(const mt of this.activeReplacements)if(!GPe(mt,w,D$.Model,T)&&!(mt.min.x>He||He>mt.max.x||mt.min.y>ot||ot>mt.max.y)&&(st=XPe(ZPe(He,ot,h.canonical,mt.footprintTileId.canonical),mt.footprint),st))break;X.float32[_e]=st?Te+Lr:Te,L=L||st!==Fe}}}return L}isEmpty(){for(const h in this.instancesPerModel)if(this.instancesPerModel[h].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(h){if(!this.uploaded)for(const p in this.instancesPerModel){const w=this.instancesPerModel[p];w.instancedDataArray.length<0||w.instancedDataArray.length===0||(w.instancedDataBuffer?w.instancedDataBuffer.updateData(w.instancedDataArray):w.instancedDataBuffer=h.createVertexBuffer(w.instancedDataArray,Wjt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(h){for(const w in this.instancesPerModel){const T=this.instancesPerModel[w];T.instancedDataArray.length!==0&&T.instancedDataBuffer&&T.instancedDataBuffer.destroy()}const p=this.layers[0].modelManager;if(h&&p&&this.modelUris&&this.modelsRequested)for(const w of this.modelUris)p.removeModel(w,"",!0)}addFeature(h,p,w,T,I){const L=this.layers[0],$=L.layout.get("model-id"),V=L.layout.get("model-allow-density-reduction"),X=$.evaluate(w,{},this.canonical);if(!X)return Kr(`modelId is not evaluated for layer ${L.id} and it is not going to get rendered.`),X;(N1e(X,!1)||this.styleDefinedModelURLs[X]!==void 0)&&(this.modelUris.includes(X)||this.modelUris.push(X)),this.instancesPerModel[X]||(this.instancesPerModel[X]=new uDe);const re=this.instancesPerModel[X],oe=re.instancedDataArray,le=new dDe(w,oe.length);let ge;T&&(ge=To.getElevationFeature(h,T));for(const _e of p)for(const Te of _e){if(Te.x<0||Te.x>=Lr||Te.y<0||Te.y>=Lr)continue;if(this.lookupDim!==0&&V){const He=(this.lookupDim-1)/Lr,ot=this.lookupDim*(Te.y*He|0)+Te.x*He|0;if(this.lookup){if(this.lookup[ot]!==0)continue;this.lookup[ot]=1}}this.instanceCount++;const Fe=oe.length;if(oe.resize(Fe+1),T){re.instancesRoadElevation||(re.instancesRoadElevation=[]);const He=ge?ge.pointElevation(new gs(Te.x,Te.y)):0;re.instancesRoadElevation.push(He)}re.instancesEvaluatedElevation.push(0),oe.float32[16*Fe]=Te.x,oe.float32[16*Fe+1]=Te.y}return le.instancedDataCount=re.instancedDataArray.length-le.instancedDataOffset,le.instancedDataCount>0&&(h.id&&(re.idToFeaturesIndex[h.id]=re.features.length),re.features.push(le),this.evaluate(le,{},re,!1)),X}getModelUris(){return this.modelUris}evaluate(h,p,w,T){const I=this.layers[0],L=h.feature,$=this.canonical,V=h.rotation=I.paint.get("model-rotation").evaluate(L,p,$),X=h.scale=I.paint.get("model-scale").evaluate(L,p,$),re=h.translation=I.paint.get("model-translation").evaluate(L,p,$),oe=Object.assign({},I.paint.get("model-color").evaluate(L,p,$));oe.a=I.paint.get("model-color-mix-intensity").evaluate(L,p,$);const le=[];this.maxVerticalOffset0?Math.sqrt(ge):0;w.maxScale=Math.max(Math.max(w.maxScale,X[0]),Math.max(X[1],X[2])),w.maxXYTranslationDistance=Math.max(w.maxXYTranslationDistance,_e),this.maxScale=Math.max(Math.max(this.maxScale,X[0]),Math.max(X[1],X[2])),DLe(le,V,X);const Te=Math.round(100*oe.a)+oe.b/1.05;for(let Fe=0;Fe10?this.tileToMeter:nr($,bt)),st[ot+4]=re[0],st[ot+5]=re[1],st[ot+6]=re[2]+(w.instancesRoadElevation?w.instancesRoadElevation[He]:0)+mt,st[ot+7]=le[0],st[ot+8]=le[1],st[ot+9]=le[2],st[ot+10]=le[4],st[ot+11]=le[5],st[ot+12]=le[6],st[ot+13]=le[8],st[ot+14]=le[9],st[ot+15]=le[10],w.instancesEvaluatedElevation[He]=re[2]}}}Wr(k1e,"ModelBucket",{omit:["layers"]}),Wr(uDe,"PerModelAttributes"),Wr(dDe,"ModelFeature");class t6{constructor(h,p,w){this._demTile=h,this._dem=this._demTile.dem,this._scale=p,this._offset=w}static create(h,p,w){const T=w||h.findDEMTileFor(p);if(!T||!T.dem)return;const I=T.dem,L=T.tileID,$=1<X.fqid),this.stateDependentLayerIds=this.layers.filter(X=>X.isStateDependent()).map(X=>X.id),this.modelTraits|=WM.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,T&&(this.modelTraits|=WM.HasMapboxMeshFeatures),I&&(this.modelTraits|=WM.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=L,this.worldview=V,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const X of p)this.nodesInfo.push(new pDe(X)),mDe(X,$.featureIndexArray.length,$.grid),$.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,$.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(h,p){for(const w of this.getNodesInfo()){const T=w.node;T.footprint&&p.push({footprint:T.footprint,id:h})}}updateAppearances(h,p,w,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(h){const p=Object.keys(h).length!==0;if(p&&!this.stateDependentLayers.length)return;const w=p?this.stateDependentLayers:this.layers;if(!mi(h,this.states))for(const T of w)this.evaluate(T,h);this.states=structuredClone(h)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(h){if(!this.needsUpload)return;const p=this.getNodesInfo();for(const w of p){const T=w.node;this.uploaded?this.updatePbrBuffer(T):qve(T,h,!0)}for(const w of p)K$(w.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(h){let p=!1;if(!h.meshes)return p;for(const w of h.meshes)w.pbrBuffer&&(w.pbrBuffer.updateData(w.featureArray),p=!0);return p}needsReEvaluation(h,p,w){const T=h.transform.projectionOptions,I=h.style.getBrightness(),L=this.brightness!==I;if(!this.uploaded||this.dirty||T.name!==this.projection.name||pR(w.paint.get("model-color").value,L)||pR(w.paint.get("model-color-mix-intensity").value,L)||pR(w.paint.get("model-roughness").value,L)||pR(w.paint.get("model-emissive-strength").value,L)||pR(w.paint.get("model-height-based-emissive-strength-multiplier").value,L)){this.projection=T,this.brightness=I;const $=this.getNodesInfo();for(const V of $)V.state=null;return!0}return!1}evaluateTransform(h,p){if(h.transform.zoom===this.zoom)return;this.zoom=h.transform.zoom;const w=this.getNodesInfo(),T=this.id.canonical;for(const I of w){const L=I.feature;I.evaluatedTranslation=p.paint.get("model-translation").evaluate(L,{},T),I.evaluatedScale=p.paint.get("model-scale").evaluate(L,{},T)}}evaluate(h,p){const w=this.getNodesInfo();for(const T of w){if(!T.node.meshes)continue;const I=T.feature,L=p&&p[I.id];if(mi(L,T.state))continue;T.state=structuredClone(L);const $=T.node.meshes&&T.node.meshes[0].featureData,V=T.evaluatedColor[2],X=T.evaluatedRMEA[2],re=this.id.canonical;if(T.hasTranslucentParts=!1,$){for(let oe=0;oe=wt)continue;const hr=S1e[Gs],Ss=Math.abs(hr);Ss>$t&&(Bt=hr,$t=Ss,Es=Qs,Os=Hs)}if($t>.1){const Hs=1-(wt+.5*Math.abs(Es*Os))/_e;let Qs=p._dem.get(Ot,Gt)+Bt*Hs;const Gs=p._dem.get(Ot+Es,Gt+Os),hr=p._dem.get(Ot-Es,Gt-Os,!0);(Qs-Gs)*(Qs-hr)>0&&(Qs=(Gs+hr)/2),S1e[Ht]=p._dem.set(Ot,Gt,Qs),oC[Ht]=wt}}}}}$&&(p._demTile.needsDEMTextureUpload=!0,p._dem._timestamp=Cd.now())}setFilter(h){this.filter=h?xN(h):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(h=>this.filter.filter(new ja(this.id.overscaledZ,{worldview:this.worldview}),h.feature,this.id.canonical)):this.nodesInfo}destroy(){const h=this.getNodesInfo();for(const p of h)K$(p.node),Vve(p.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(h,p){if(p.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=p.updateTime;const w=p.getReplacementRegionsForTile(h.toUnwrapped());for(const T of this.getNodesInfo()){const I=T.node.footprint;T.hiddenByReplacement=!!I&&!w.find(L=>L.footprint===I)}}getHeightAtTileCoord(h,p){const w=[],T=[0,0,0],I=b([]);for(const L of this.getNodesInfo()){const $=L.node.meshes[0],V=$.transformedAabb;if(hV.max[0]||p>V.max[1])continue;if(L.node.hidden===!0)return{height:1/0,maxHeight:L.feature.properties.height,hidden:!1,verticalScale:L.evaluatedScale[2]};j(I,L.node.globalMatrix),T[0]=h,T[1]=p,Qe(T,T,I);const X=(T[0]-$.aabb.min[0])/($.aabb.max[0]-$.aabb.min[0])*sC|0,re=Math.min(63,(T[1]-$.aabb.min[1])/($.aabb.max[1]-$.aabb.min[1])*sC|0)*sC+Math.min(63,X),oe=$.heightmap[re];if(!(oe<0&&L.node.footprint))return L.hiddenByReplacement?void 0:{height:oe,maxHeight:L.feature.properties.height,hidden:!1,verticalScale:L.evaluatedScale[2]};if(L.node.footprint.grid.query(new gs(h,p),new gs(h,p),w),w.length>0)return{height:void 0,maxHeight:L.feature.properties.height,hidden:L.hiddenByReplacement,verticalScale:L.evaluatedScale[2]}}}}function pR(v,h){return v instanceof Ug&&!v.isLightConstant&&h}function ENt(v,h,p,w,T,I,L,$){let V=(61440&h|(61440&h)>>4)>>8,X=(3840&h|(3840&h)>>4)>>4,re=240&h|(240&h)>>4;p[3]>0&&(V=An(V,255*p[0],p[3]),X=An(X,255*p[1],p[3]),re=An(re,255*p[2],p[3]));const oe=V<<8|X,le=re<<8|Math.floor(255*w[3]),ge=function(wt){const Gt=Ke(wt,0,2);return Math.min(Math.round(.5*Gt*255),255)}(w[2])<<8|15*w[0]<<4|15*w[1],_e=Ke(T[0],0,1),Te=Ke(T[1],0,1),Fe=Ke(T[2],0,1),He=Ke(T[3],0,1);let ot,st,mt,bt;if(_e!==Te&&L!==I&&Te!==_e){const wt=L-I;st=1/(wt*(Te-_e)),mt=-(I+wt*_e)/(wt*(Te-_e));const Gt=Ke(T[4],-1,1);bt=Math.pow(10,Gt),ot=255*Fe<<8|255*He}else ot=65535,st=0,mt=1,bt=1;if(v.emplaceBack(oe,le,ge,ot,st,mt,bt),$){const wt=$.length;$.clear();for(let Gt=0;Gt>16&65535,re=I?V>>16&65535:65535&V,oe=(15&re)<8?15&re:0,le=v.evaluatedRMEA[oe],ge=v.evaluatedColor[oe],_e=v.emissionHeightBasedParams[oe];let Te;if($&&oe===2&&w.lights&&(Te=new DM,Te.resize(10*w.lights.length)),ENt(L.featureArray,X,ge,le,_e,L.aabb.min[2],L.aabb.max[2],Te),Te&&$){$=!1;const Fe=w.meshes[w.lightMeshIndex];Fe.featureArray=Te,Fe.featureArray._trim()}}L.featureArray._trim(),T++}}Wr(xU,"Tiled3dModelBucket",{omit:["layers"]}),Wr(pDe,"Tiled3dModelFeature");const MNt=["id","tile","layer","source","sourceLayer","state"];class lC{constructor(h,p,w,T,I){this.type="Feature",this._vectorTileFeature=h,this._z=p,this._x=w,this._y=T,this.properties=h?h.properties:{},this.id=I}clone(){const h=new lC(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(h.state=Object.assign({},this.state)),this.layer&&(h.layer=Object.assign({},this.layer)),this.source&&(h.source=this.source),this.sourceLayer&&(h.sourceLayer=this.sourceLayer),h}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(h){this._geometry=h}toJSON(){const h={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const p of MNt)this[p]!==void 0&&(h[p]=this[p]);return h}}class cC extends xf{constructor(h,p,w,T){super(),this.id=h,this.type="model",this.models=[],this._options=p,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(h,p){return MLe(this.map._requestManager.transformRequest(h,Lg.Model).url,p)}async loadModel(h,p,w){try{const T=await this.loadGLTFFromURI(p.uri,w);if(w.aborted)return;const I=this._modelsInfo.get(h);if(!I)return;const L=Gve(T),$=I.modelSpec,V=new RLe(h,$.uri,$.position,$.orientation,L);cC.applyModelSpecification(V,$),V.computeBoundsAndApplyParent(),this.models.push(V),I.model=V}catch(T){if(T instanceof Error&&T.name==="AbortError")return;const I=T instanceof Error?T.message:"Unknown error";this.fire(new Lm(new Error(`Could not load model ${h} from ${p.uri}: ${I}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const h=this._abortController.signal,p=[];for(const w in this._options.models){const T=this._options.models[w],I=this._modelsInfo.get(w);if(I&&I.model){I.modelSpec=T;const L=I.model;L.position=T.position!=null?new Zt(T.position[0],T.position[1]):new Zt(0,0),L.orientation=T.orientation!=null?T.orientation:[0,0,0],cC.applyModelSpecification(L,T),L.computeBoundsAndApplyParent(),this.models.push(L)}else I?I.modelSpec=T:(this._modelsInfo.set(w,{modelSpec:T,model:null}),p.push(this.loadModel(w,T,h)))}p.length!==0?(await Promise.allSettled(p),h.aborted||this.fire(new _c("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new _c("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(h,p){p.nodeOverrides&&cC.convertNodeOverrides(h,p.nodeOverrides),p.materialOverrides&&cC.convertMaterialOverrides(h,p.materialOverrides),p.nodeOverrideNames&&(h.nodeOverrideNames=[...p.nodeOverrideNames]),p.materialOverrideNames&&(h.materialOverrideNames=[...p.materialOverrideNames]),p.featureProperties&&(h.featureProperties=p.featureProperties)}static convertNodeOverrides(h,p){if(Array.isArray(p)&&p.every(w=>typeof w=="string")){h.nodeOverrideNames=[];for(const w of p)h.nodeOverrideNames.push(w)}else Object.entries(p).forEach(([w,T])=>{const I={orientation:[0,0,0]};if(T.hasOwnProperty("orientation")){const L=T.orientation;L&&(I.orientation=L)}h.nodeOverrides.set(w,I)})}static convertMaterialOverrides(h,p){if(Array.isArray(p)&&p.every(w=>typeof w=="string")){h.materialOverrideNames=[];for(const w of p)h.materialOverrideNames.push(w)}else Object.entries(p).forEach(([w,T])=>{const I={color:new Vr(1,1,1),colorMix:0,emissionStrength:0,opacity:1},L=T["model-color"];L!==void 0&&(I.color.r=L[0],I.color.g=L[1],I.color.b=L[2]);const $=T["model-color-mix-intensity"];$!==void 0&&(I.colorMix=$);const V=T["model-emissive-strength"];V!==void 0&&(I.emissionStrength=V);const X=T["model-opacity"];X!==void 0&&(I.opacity=X),h.materialOverrides.set(w,I)})}onAdd(h){this.map=h,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const h of this._modelsInfo.values())if(h.model==null)return!1;return!0}getModels(){return this.models}loadTile(h,p){}serialize(){return this._options}setProperty(h,p){return!1}reload(){this.cancelModelRequests();const h=yt(this.id,this.scope);this.map.style.clearSource(h),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(h){this.cancelModelRequests()}setModels(h){this.models=[];const p=new Map;for(const w in h){const T=h[w],I=this._modelsInfo.get(w);I&&I.modelSpec.uri===T.uri&&p.set(w,I)}if(this._modelsInfo.size!==p.size){this.cancelModelRequests();for(const[w,T]of p)T.model||p.delete(w)}this._modelsInfo=p,this._options.models=h,this.load()}}function C1e(v,h,p,w){const T=1<V>=bt.vertexArrayOffset&&Vmt.polygon).flat());const Fe=ge?$:null,[He,ot]=xLe(I,w,oe,re,X,L,Fe,le,_e,I.center.lat,v.tileID.canonical),st=v.queryGeometry;return pLe(He,ot,st.isPointQuery()?st.screenBounds:st.screenGeometry)}},building:class extends no{constructor(v,h,p,w){super(v,{layout:qLe||(qLe=new Io({visibility:new yr(as.layout_building.visibility),"building-facade":new gr(as.layout_building["building-facade"]),"building-facade-floors":new gr(as.layout_building["building-facade-floors"]),"building-facade-unit-width":new gr(as.layout_building["building-facade-unit-width"]),"building-facade-window":new gr(as.layout_building["building-facade-window"]),"building-roof-shape":new gr(as.layout_building["building-roof-shape"]),"building-height":new gr(as.layout_building["building-height"]),"building-base":new gr(as.layout_building["building-base"]),"building-flood-light-wall-radius":new gr(as.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new gr(as.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new gr(as.layout_building["building-flip-roof-orientation"])})),paint:VLe||(VLe=new Io({"building-opacity":new yr(as.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new yr(as.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new yr(as.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new yr(as.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new yr(as.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new yr(as.paint_building["building-vertical-scale"]),"building-cast-shadows":new yr(as.paint_building["building-cast-shadows"]),"building-color":new gr(as.paint_building["building-color"]),"building-emissive-strength":new gr(as.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new yr(as.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new yr(as.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new yr(as.paint_building["building-front-cutoff"]),"building-flood-light-color":new yr(as.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new yr(as.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new yr(as.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new gr({type:"string",default:"default","property-type":"data-driven"})}))},h,p,w),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(v){return new ULe(v)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(v){return!0}queryRadius(v){return 0}queryIntersectsFeature(v,h,p,w,T,I,L,$,V,X){let re=this.layout.get("building-height").evaluate(h,p);const oe=this.layout.get("building-base").evaluate(h,p),le=v.tile.getBucket(this).getFootprint(h);if(le){if(le.hiddenFlags!==0)return!1;re=le.height}const[ge,_e]=xLe(I,w,oe,re,new gs(0,0),L,null,[0,0],1,I.center.lat,v.tileID.canonical),Te=v.queryGeometry;return pLe(ge,_e,Te.isPointQuery()?Te.screenBounds:Te.screenGeometry)}},line:class extends no{constructor(v,h,p,w){const T=e8e();super(v,T,h,p,w),T.layout&&(this.layout=new Id(T.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(v){if(v==="line-gradient"){const h=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=h._styleExpression&&h._styleExpression.expression instanceof Lw,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(v,h){super.recalculate(v,h),this.paint._values["line-floorwidth"]=(()=>{if(tR)return tR;const p=e8e();return tR=new k2t(p.paint.properties["line-width"].specification),tR.useIntegerZoom=!0,tR})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,v)}createBucket(v){return new Z$(v)}getProgramIds(){const v=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&v.push("lineBlendComposite"),v}getDefaultProgramParams(v,h,p){if(v==="lineBlendComposite")return{};const w=QLe(this);return{config:new Ae(this,{zoom:h,lut:p}),defines:w,overrideFog:!1}}queryRadius(v){const h=v,p=t8e(wN("line-width",this,h),wN("line-gap-width",this,h)),w=wN("line-offset",this,h);return p/2+Math.abs(w)+b$(this.paint.get("line-translate"))}queryIntersectsFeature(v,h,p,w,T,I){if(v.queryGeometry.isAboveHorizon)return!1;const L=JIe(v.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),I.angle,v.pixelToTileUnitsFactor),$=v.pixelToTileUnitsFactor/2*t8e(this.paint.get("line-width").evaluate(h,p),this.paint.get("line-gap-width").evaluate(h,p)),V=this.paint.get("line-offset").evaluate(h,p);return V&&(w=function(X,re){const oe=[],le=new gs(0,0);for(let ge=0;ge=3){for(let _e=0;_e{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 xDe{constructor(h){this._stringToNumber={},this._numberToString=[];for(let p=0;p=0&&le[3]>=0&&X.insert(V,le[0],le[1],le[2],le[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Ii(new X$(this.rawTileData)).layers,this.sourceLayerCoder=new xDe(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const h in this.vtLayers)this.vtFeatures[h]=[]}return this.vtLayers}query(h,p){const{tilespaceGeometry:w,transform:T,tileTransform:I,pixelPosMatrix:L,availableImages:$,worldview:V}=p;this.loadVTLayers(),this.serializedLayersCache.clear();const X=p.queryRadius?p.queryRadius:0,re=w.bufferedTilespaceBounds,oe=this.grid.query(re.min.x,re.min.y,re.max.x,re.max.y,(Te,Fe,He,ot)=>kb(w.bufferedTilespaceGeometry,Te-X,Fe-X,He+X,ot+X));oe.sort(DNt);let le=null;T.elevation&&oe.length>0&&(le=t6.create(T.elevation,this.tileID));const ge={};let _e;for(let Te=0;Te(ot||(ot=zn(st,this.tileID.canonical,I)),mt.queryIntersectsFeature(w,st,bt,ot,this.z,T,L,le,wt,p.scope)))}return ge}loadMatchingFeature(h,p,w,T,I,L){const{featureIndex:$,bucketIndex:V,sourceLayerIndex:X,layoutVertexArrayOffset:re}=p,oe=this.bucketLayerIDs[V],le=w.layers,ge=Object.keys(le);if(ge.length&&!Ar(ge,oe))return;const _e=w.sourceCache,Te=this.sourceLayerCoder.decode(X),Fe=this.vtLayers[Te].feature($),He=this.getId(Fe,Te);for(let ot=0;ot`${$.key}: ${$.message}`).join(", ");return void Kr(`Failed to create expression for promoteId: ${L}`)}this.promoteIdExpression=I.value}w=this.promoteIdExpression.evaluate({zoom:0},h)}else w=h.properties[T];typeof w=="boolean"&&(w=Number(w))}return w}}function yDe(v,h,p,w,T){return Bs(v,(I,L)=>{const $=h instanceof Id?h.get(L):null;return $&&$.evaluate?$.evaluate(p,w,void 0,T):$})}function DNt(v,h){return h-v}function vDe(v,h){const p={};if(!h)return p;for(const w of v){const T=w.layerIds.map(I=>h.getLayer(I)).filter(Boolean);if(T.length!==0){w.layers=T,w.stateDependentLayerIds&&(w.stateDependentLayers=w.stateDependentLayerIds.map(I=>T.filter(L=>L.id===I)[0]));for(const I of T)p[I.fqid]=w}}return p}Wr(gDe,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const xy=32,Ib=33,EN=new Uint16Array(8184);for(let v=0;v<2046;v++){let h=v+2,p=0,w=0,T=0,I=0,L=0,$=0;for(1&h?T=I=L=xy:p=w=$=xy;(h>>=1)>1;){const X=p+T>>1,re=w+I>>1;1&h?(T=p,I=w,p=L,w=$):(p=T,w=I,T=L,I=$),L=X,$=re}const V=4*v;EN[V+0]=p,EN[V+1]=w,EN[V+2]=T,EN[V+3]=I}const Pb=new Uint16Array(2178),AN=new Uint8Array(1089),gU=new Uint16Array(1089);function bDe(v){return v===0?-.03125:v===32?.03125:0}const _De={Other:0,Symbol:1,FillExtrusion:2},wDe={type:2,extent:Lr,loadGeometry:()=>[[new gs(0,0),new gs(8193,0),new gs(8193,8193),new gs(0,8193),new gs(0,0)]]};class RNt{constructor(){this.tasks={},this.taskQueue=[],Xt(["process"],this),this.invoker=new LNt(this.process),this.nextId=0}add(h,p){const w=this.nextId++,T=function({type:I,renderSourceType:L,zoom:$}){$=$||0;const V=L===_De.Symbol;return I==="message"?0:I!=="maybePrepare"||V?I!=="parseTile"||V?I==="parseTile"&&V?300-$:I==="maybePrepare"&&V?400-$:500:200-$:100-$}(p);if(T===0){try{h()}finally{}return null}return this.tasks[w]={fn:h,metadata:p,priority:T,id:w},this.taskQueue.push(w),this.invoker.trigger(),{cancel:()=>{delete this.tasks[w]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(w=>!!this.tasks[w]),!this.taskQueue.length)return;const h=this.pick();if(h===null)return;const p=this.tasks[h];if(delete this.tasks[h],this.taskQueue.length&&this.invoker.trigger(),!p)return;p.fn()}finally{}}pick(){let h=null,p=1/0;for(let T=0;T>16&255)/255,(v>>8&255)/255,(255&v)/255,1)}function KNt(v,h,p){v===1?(h.rgb_color=bU(p.readVarint()),h.paint="rgb_color"):v===2?(h.linear_gradient_idx=p.readVarint(),h.paint="linear_gradient_idx"):v===3?(h.radial_gradient_idx=p.readVarint(),h.paint="radial_gradient_idx"):v===5?p.readPackedFloat(h.dasharray):v===6?h.dashoffset=p.readFloat():v===7?h.miterlimit=p.readFloat():v===8?h.opacity=p.readVarint():v===9?h.width=p.readFloat():v===10?h.linecap=p.readVarint():v===11&&(h.linejoin=p.readVarint())}function YNt(v,h,p){v===1?h.transform=vU(p,p.readVarint()+p.pos):v===2?h.spread_method=p.readVarint():v===3?h.stops.push(kDe(p,p.readVarint()+p.pos)):v===4?h.x1=p.readFloat():v===5?h.y1=p.readFloat():v===6?h.x2=p.readFloat():v===7&&(h.y2=p.readFloat())}function kDe(v,h){return v.readFields(ZNt,{offset:0,opacity:255,rgb_color:T1e},h)}function ZNt(v,h,p){v===1?h.offset=p.readFloat():v===2?h.opacity=p.readVarint():v===3&&(h.rgb_color=bU(p.readVarint()))}function XNt(v,h,p){v===1?h.transform=vU(p,p.readVarint()+p.pos):v===2?h.spread_method=p.readVarint():v===3?h.stops.push(kDe(p,p.readVarint()+p.pos)):v===4?h.cx=p.readFloat():v===5?h.cy=p.readFloat():v===6?h.r=p.readFloat():v===7?h.fx=p.readFloat():v===8?h.fy=p.readFloat():v===9&&(h.fr=p.readFloat())}function QNt(v,h,p){v===1?h.transform=vU(p,p.readVarint()+p.pos):v===2?h.clip_path_idx=p.readVarint():v===3&&h.children.push(yU(p,p.readVarint()+p.pos))}function JNt(v,h,p){v===1?h.left=h.top=p.readFloat():v===2?h.width=h.height=p.readFloat():v===3?h.top=p.readFloat():v===4?h.height=p.readFloat():v===5?h.mask_type=p.readVarint():v===6?h.mask_idx=p.readVarint():v===7&&h.children.push(yU(p,p.readVarint()+p.pos))}class ekt{static calculate(h={},p=[]){const w=new Map,T=new Map;if(Object.keys(h).length===0)return w;p.forEach(I=>{T.set(I.name,I.rgb_color||new Vr(0,0,0))});for(const[I,L]of Object.entries(h))T.has(I)?w.set(T.get(I).toString(),L):console.warn(`Ignoring unknown image variable "${I}"`);return w}}function s6(v,h=255,p){const w=h/255,T=v.toString(),I=p.has(T)?p.get(T).clone():v.clone();return I.a*=w,I.toString()}function xR(v,h){if(!ku()){const p=document.createElement("canvas");return p.width=v,p.height=h,p}return new OffscreenCanvas(v,h)}let E1e,gR=null;function A1e(v,h,p,w,T){for(const I of w.children)SDe(v,h,p,I,T)}function SDe(v,h,p,w,T){w.group?(v.save(),function(I,L,$,V,X){const re=V.mask_idx!=null?$.masks[V.mask_idx]:null,oe=V.clip_path_idx!=null?$.clip_paths[V.clip_path_idx]:null;if(V.transform&&(L=r6(V.transform).preMultiplySelf(L)),!function(_e,Te,Fe){return _e.opacity!==255||Te||Fe}(V,oe!=null,re!=null))return void A1e(I,L,$,V,X);const le=xR(I.canvas.width,I.canvas.height),ge=le.getContext("2d");A1e(ge,L,$,V,X),oe&&PDe(ge,L,$,oe),re&&LDe(ge,L,$,re,X),I.globalAlpha=V.opacity/255,I.drawImage(le,0,0)}(v,h,p,w.group,T),v.restore()):w.path&&(v.save(),function(I,L,$,V,X){I.setTransform(L),V.paint_order===1?(CDe(I,$,V,X),EDe(I,$,V,X)):(EDe(I,$,V,X),CDe(I,$,V,X))}(v,h,p,w.path,T),v.restore())}function CDe(v,h,p,w){const T=p.fill;if(!T)return;const I=T.opacity/255;switch(v.save(),v.beginPath(),DDe(p,v),T.paint){case"rgb_color":v.fillStyle=s6(T.rgb_color,T.opacity,w);break;case"linear_gradient_idx":{const L=h.linear_gradients[T.linear_gradient_idx];L.transform&&v.setTransform(r6(L.transform).preMultiplySelf(v.getTransform())),v.fillStyle=ADe(v,L,I,w);break}case"radial_gradient_idx":{const L=h.radial_gradients[T.radial_gradient_idx];L.transform&&v.setTransform(r6(L.transform).preMultiplySelf(v.getTransform())),v.fillStyle=MDe(v,L,I,w)}}v.fill(TDe(p)),v.restore()}function TDe(v){return v.rule===1?"nonzero":v.rule===2?"evenodd":void 0}function EDe(v,h,p,w){const T=p.stroke;if(!T)return;const I=RDe(p);v.lineWidth=T.width,v.miterLimit=T.miterlimit,v.setLineDash(T.dasharray),v.lineDashOffset=T.dashoffset;const L=T.opacity/255;switch(T.paint){case"rgb_color":v.strokeStyle=s6(T.rgb_color,T.opacity,w);break;case"linear_gradient_idx":v.strokeStyle=ADe(v,h.linear_gradients[T.linear_gradient_idx],L,w,!0);break;case"radial_gradient_idx":v.strokeStyle=MDe(v,h.radial_gradients[T.radial_gradient_idx],L,w,!0)}switch(T.linejoin){case 2:case 1:v.lineJoin="miter";break;case 3:v.lineJoin="round";break;case 4:v.lineJoin="bevel"}switch(T.linecap){case 1:v.lineCap="butt";break;case 2:v.lineCap="round";break;case 3:v.lineCap="square"}v.stroke(I)}function ADe(v,h,p,w,T=!1){if(h.stops.length===1){const le=h.stops[0];return s6(le.rgb_color,le.opacity*p,w)}const{x1:I,y1:L,x2:$,y2:V}=h;let X=new DOMPoint(I,L),re=new DOMPoint($,V);if(T){const le=r6(h.transform);X=le.transformPoint(X),re=le.transformPoint(re)}const oe=v.createLinearGradient(X.x,X.y,re.x,re.y);for(const le of h.stops)oe.addColorStop(le.offset,s6(le.rgb_color,le.opacity*p,w));return oe}function MDe(v,h,p,w,T=!1){if(h.stops.length===1){const He=h.stops[0];return s6(He.rgb_color,He.opacity*p,w)}const I=r6(h.transform),{fx:L,fy:$,fr:V,cx:X,cy:re,r:oe}=h;let le=new DOMPoint(L,$),ge=new DOMPoint(X,re),_e=V,Te=oe;if(T){le=I.transformPoint(le),ge=I.transformPoint(ge);const He=(I.a+I.d)/2;_e=V*He,Te=h.r*He}const Fe=v.createRadialGradient(le.x,le.y,_e,ge.x,ge.y,Te);for(const He of h.stops)Fe.addColorStop(He.offset,s6(He.rgb_color,He.opacity*p,w));return Fe}function IDe(v,h,p,w){const T=w.transform?r6(w.transform).preMultiplySelf(h):h,I=xR(v.canvas.width,v.canvas.height),L=I.getContext("2d");for(const V of w.children)if(V.group)IDe(L,T,p,V.group);else if(V.path){const X=V.path,re=new Path2D;re.addPath(RDe(X),T),L.fill(re,TDe(X))}const $=w.clip_path_idx!=null?p.clip_paths[w.clip_path_idx]:null;$&&PDe(L,T,p,$),v.globalCompositeOperation="source-over",v.drawImage(I,0,0)}function PDe(v,h,p,w){const T=xR(v.canvas.width,v.canvas.height);IDe(T.getContext("2d"),h,p,w),v.globalCompositeOperation="destination-in",v.drawImage(T,0,0)}function LDe(v,h,p,w,T){if(w.children.length===0)return;const I=w.mask_idx!=null?p.masks[w.mask_idx]:null;I&&LDe(v,h,p,I,T);const L=v.canvas.width,$=v.canvas.height,V=xR(L,$),X=V.getContext("2d"),re=w.width,oe=w.height,le=w.left,ge=w.top,_e=new Path2D,Te=new Path2D;Te.rect(le,ge,re,oe),_e.addPath(Te,h),X.clip(_e);for(const ot of w.children)SDe(X,h,p,ot,T);const Fe=X.getImageData(0,0,L,$),He=Fe.data;if(w.mask_type===1)for(let ot=0;oth[L])return null}else{const $=1/w[L];let V=(v[L]-p[L])*$,X=(h[L]-p[L])*$;if(V>X){const re=V;V=X,X=re}if(V>T&&(T=V),XI)return null}return T}function zDe(v,h,p,w,T,I,L,$,V,X,re){const oe=w-v,le=T-h,ge=I-p,_e=L-v,Te=$-h,Fe=V-p,He=re[1]*Fe-re[2]*Te,ot=re[2]*_e-re[0]*Fe,st=re[0]*Te-re[1]*_e,mt=oe*He+le*ot+ge*st;if(Math.abs(mt)<1e-15)return null;const bt=1/mt,wt=X[0]-v,Gt=X[1]-h,Ot=X[2]-p,Ht=(wt*He+Gt*ot+Ot*st)*bt;if(Ht<0||Ht>1)return null;const Bt=Gt*ge-Ot*le,$t=Ot*oe-wt*ge,Es=wt*le-Gt*oe,Os=(re[0]*Bt+re[1]*$t+re[2]*Es)*bt;return Os<0||Ht+Os>1?null:(_e*Bt+Te*$t+Fe*Es)*bt}function BDe(v,h,p){return(v-h)/(p-h)}function $De(v,h,p,w,T,I,L,$,V){const X=1<{const ot=Fe?1:0,st=(ge+1)*Te-ot,mt=_e*Te,bt=(_e+1)*Te-ot;He[0]=ge*Te,He[1]=mt,He[2]=st,He[3]=bt};let oe=new ODe(V);const le=[];for(let ge=0;ge=1;V/=2){const ge=$[$.length-1];oe=new ODe(V);for(let _e=0;_e0;){const{idx:_e,t:Te,nodex:Fe,nodey:He,depth:ot}=ge.pop();if(this.leaves[_e]){$De(Fe,He,ot,h,p,w,T,oe,le);const mt=1<=Gs[2])return Te}continue}let st=0;for(let mt=0;mt=X[re[Ot]]&&(re.splice(Ot,0,mt),Gt=!0);Gt||(re[st]=mt),st++}}for(let mt=0;mt=this.dim+1||p<-1||p>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(p+1)*this.stride+(h+1)}static pack(h,p){const w=[0,0,0,0],T=wU.getUnpackVector(p);let I=Math.floor((h+T[3])/T[2]);return w[2]=I%256,I=Math.floor(I/256),w[1]=I%256,I=Math.floor(I/256),w[0]=I,w}getPixels(){return new NPe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(h,p,w){if(this.dim!==h.dim)throw new Error("dem dimension mismatch");let T=p*this.dim,I=p*this.dim+this.dim,L=w*this.dim,$=w*this.dim+this.dim;switch(p){case-1:T=I-1;break;case 1:I=T+1}switch(w){case-1:L=$-1;break;case 1:$=L+1}const V=-p*this.dim,X=-w*this.dim;for(let re=L;re<$;re++)for(let oe=T;oe=1;w--){const T=w===1?1:0,I=w===2?1:0;for(let L=0;L>>1^-(1&v[h]);return v}function fkt(v,h){switch(h){case"uint32":return v;case"uint16":for(let p=0;p>4|(61440&w)>>8|(240&T)<<4|61440&T,v[p+1]=15&w|(3840&w)>>4|(15&T)<<8|(3840&T)<<4}return v;case"uint8":for(let p=0;p>6|(192&T)>>4|(192&I)>>2|192&L,v[p+1]=(48&w)>>4|(48&T)>>2|48&I|(48&L)<<2,v[p+2]=(12&w)>>2|12&T|(12&I)<<2|(12&L)<<4,v[p+3]=3&w|(3&T)<<2|(3&I)<<4|(3&L)<<6}return v;default:throw new Error(`Invalid pixel format, "${h}"`)}}Wr(wU,"DEMData"),Wr(UDe,"DemMinMaxQuadTree",{omit:["dem"]});var Yg=Uint8Array,yR=Uint16Array,pkt=Int32Array,VDe=new Yg([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]),HDe=new Yg([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]),xkt=new Yg([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),GDe=function(v,h){for(var p=new yR(31),w=0;w<31;++w)p[w]=h+=1<>1|(21845&pd)<<1;YDe[pd]=((65280&(n6=(61680&(n6=(52428&n6)>>2|(13107&n6)<<2))>>4|(3855&n6)<<4))>>8|(255&n6)<<8)>>1}var vR=function(v,h,p){for(var w=v.length,T=0,I=new yR(h);T>V]=X;return L},bR=new Yg(288);for(pd=0;pd<144;++pd)bR[pd]=8;for(pd=144;pd<256;++pd)bR[pd]=9;for(pd=256;pd<280;++pd)bR[pd]=7;for(pd=280;pd<288;++pd)bR[pd]=8;var ZDe=new Yg(32);for(pd=0;pd<32;++pd)ZDe[pd]=5;var vkt=vR(bR,9),bkt=vR(ZDe,5),I1e=function(v){for(var h=v[0],p=1;ph&&(h=v[p]);return h},Gv=function(v,h,p){var w=h/8|0;return(v[w]|v[w+1]<<8)>>(7&h)&p},P1e=function(v,h){var p=h/8|0;return(v[p]|v[p+1]<<8|v[p+2]<<16)>>(7&h)},_kt=function(v){return(v+7)/8|0},wkt=["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"],Wv=function(v,h,p){var w=new Error(h||wkt[v]);if(w.code=v,Error.captureStackTrace&&Error.captureStackTrace(w,Wv),!p)throw w;return w},jkt=new Yg(0),Nkt=typeof TextDecoder<"u"&&new TextDecoder;try{Nkt.decode(jkt,{stream:!0})}catch{}const kkt={gzip_data:"gzip"};class gy extends Error{constructor(h){super(h),this.name="MRTError"}}const Skt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},XDe={uint32:1,uint16:2,uint8:4},Ckt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let L1e;class jU{constructor(h=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=h}getLayer(h){const p=this.layers[h];if(!p)throw new gy(`Layer '${h}' not found`);return p}getHeaderLength(h){const p=new Uint8Array(h),w=new DataView(h);if(p[0]!==13)throw new gy("File is not a valid MRT.");return w.getUint32(1,!0)}parseHeader(h){const p=new Uint8Array(h),w=this.getHeaderLength(h);if(p.length= ${w} but got buffer of length ${p.length}`);const T=new L1e(p.subarray(0,w)).readFields(nkt,{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 gy(`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 I of T.layers)this.layers[I.name]=new QDe(I,{cacheSize:this._cacheSize});return this}createDecodingTask(h){const p=[],w=this.getLayer(h.layerName);for(let T of h.blockIndices){const I=w.dataIndex[T],L=I.firstByte-h.firstByte,$=I.lastByte-h.firstByte;if(w._blocksInProgress.has(T))continue;const V={layerName:w.name,firstByte:L,lastByte:$,pixelFormat:w.pixelFormat,blockIndex:T,blockShape:[I.bands.length].concat(w.bandShape),buffer:w.buffer,codec:I.codec.codec,filters:I.filters.map(X=>X.filter)};w._blocksInProgress.add(T),p.push(V)}return new JDe(p,()=>{p.forEach(T=>w._blocksInProgress.delete(T.blockIndex))},(T,I)=>{if(p.forEach(L=>w._blocksInProgress.delete(L.blockIndex)),T)throw T;I.forEach(L=>{this.getLayer(L.layerName).processDecodedData(L)})})}}class QDe{constructor({version:h,name:p,units:w,tileSize:T,pixelFormat:I,buffer:L,dataIndex:$},V){if(this.version=h,this.version!==1)throw new gy(`Cannot parse raster layer encoded with MRT version ${h}`);this.name=p,this.units=w,this.tileSize=T,this.buffer=L,this.pixelFormat=Skt[I],this.dataIndex=$,this.bandShape=[T+2*L,T+2*L,XDe[this.pixelFormat]],this._decodedBlocks=new _U(V?V.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return XDe[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:h})=>h).flat()}processDecodedData(h){const p=h.blockIndex.toString();this._decodedBlocks.get(p)||this._decodedBlocks.put(p,h.data)}getBlockForBand(h){let p=0;switch(typeof h){case"string":for(const[w,T]of this.dataIndex.entries()){for(const[I,L]of T.bands.entries())if(L===h)return{bandIndex:p+I,blockIndex:w,blockBandIndex:I};p+=T.bands.length}break;case"number":for(const[w,T]of this.dataIndex.entries()){if(h>=p&&hthis.cacheSize)throw new gy(`Number of blocks to decode (${I.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:p,lastByte:w,blockIndices:T}}hasBand(h){const{blockIndex:p}=this.getBlockForBand(h);return p>=0}hasDataForBand(h){const{blockIndex:p}=this.getBlockForBand(h);return p>=0&&!!this._decodedBlocks.get(p.toString())}getBandView(h){const{blockIndex:p,blockBandIndex:w}=this.getBlockForBand(h);if(p<0)throw new gy(`Band not found: ${JSON.stringify(h)}`);const T=this._decodedBlocks.get(p.toString());if(!T)throw new gy(`Data for band ${JSON.stringify(h)} of layer "${this.name}" not decoded.`);const I=this.dataIndex[p],L=this.bandShape.reduce((X,re)=>X*re,1),$=w*L,V=T.subarray($,$+L);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:I.offset,scale:I.scale}}}jU.setPbf=function(v){L1e=v};class JDe{constructor(h,p,w){this.tasks=h,this._onCancel=p,this._onComplete=w,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(h,p){this._finalized||(this._onComplete(h,p),this._finalized=!0)}}jU.performDecoding=function(v,h){const p=new Uint8Array(v);return Promise.all(h.tasks.map(w=>{const{layerName:T,firstByte:I,lastByte:L,pixelFormat:$,blockShape:V,blockIndex:X,filters:re,codec:oe}=w,le=p.subarray(I,L+1),ge=new Uint32Array(V[0]*V[1]*V[2]);let _e;if(oe!=="gzip_data")throw new gy(`Unhandled codec: ${oe}`);return _e=function(Te,Fe){if(!globalThis.DecompressionStream&&Fe==="gzip_data")return Promise.resolve((bt=function(Ot){Ot[0]==31&&Ot[1]==139&&Ot[2]==8||Wv(6,"invalid gzip data");var Ht=Ot[3],Bt=10;4&Ht&&(Bt+=2+(Ot[10]|Ot[11]<<8));for(var $t=(Ht>>3&1)+(Ht>>4&1);$t>0;$t-=!Ot[Bt++]);return Bt+(2&Ht)}(He=Te),bt+8>He.length&&Wv(6,"invalid gzip data"),function(Ot,Ht,Bt,$t){var Es=Ot.length;if(!Es||Ht.f&&!Ht.l)return Bt||new Yg(0);var Os=!Bt,Hs=Os||Ht.i!=2,Qs=Ht.i;Os&&(Bt=new Yg(3*Es));var Gs=function(Dl){var em=Bt.length;if(Dl>em){var su=new Yg(Math.max(2*em,Dl));su.set(Bt),Bt=su}},hr=Ht.f||0,Ss=Ht.p||0,Zs=Ht.b||0,tr=Ht.l,mr=Ht.d,wr=Ht.m,tn=Ht.n,Mr=8*Es;do{if(!tr){hr=Gv(Ot,Ss,1);var Tr=Gv(Ot,Ss+1,3);if(Ss+=3,!Tr){var jr=Ot[(Wi=_kt(Ss)+4)-4]|Ot[Wi-3]<<8,Xr=Wi+jr;if(Xr>Es){Qs&&Wv(0);break}Hs&&Gs(Zs+jr),Bt.set(Ot.subarray(Wi,Xr),Zs),Ht.b=Zs+=jr,Ht.p=Ss=8*Xr,Ht.f=hr;continue}if(Tr==1)tr=vkt,mr=bkt,wr=9,tn=5;else if(Tr==2){var ln=Gv(Ot,Ss,31)+257,On=Gv(Ot,Ss+10,15)+4,xn=ln+Gv(Ot,Ss+5,31)+1;Ss+=14;for(var va=new Yg(xn),xi=new Yg(19),ba=0;ba>4)<16)va[ba++]=Wi;else{var So=0,Sl=0;for(Wi==16?(Sl=3+Gv(Ot,Ss,3),Ss+=2,So=va[ba-1]):Wi==17?(Sl=3+Gv(Ot,Ss,7),Ss+=3):Wi==18&&(Sl=11+Gv(Ot,Ss,127),Ss+=7);Sl--;)va[ba++]=So}}var Dd=va.subarray(0,ln),Cl=va.subarray(ln);wr=I1e(Dd),tn=I1e(Cl),tr=vR(Dd,wr),mr=vR(Cl,tn)}else Wv(1);if(Ss>Mr){Qs&&Wv(0);break}}Hs&&Gs(Zs+131072);for(var Wl=(1<>4;if((Ss+=15&So)>Mr){Qs&&Wv(0);break}if(So||Wv(2),sh<256)Bt[Zs++]=sh;else{if(sh==256){Kl=Ss,tr=null;break}var Rd=sh-254;sh>264&&(Rd=Gv(Ot,Ss,(1<<(sc=VDe[ba=sh-257]))-1)+KDe[ba],Ss+=sc);var Ha=mr[P1e(Ot,Ss)&Nc],Vm=Ha>>4;if(Ha||Wv(3),Ss+=15&Ha,Cl=ykt[Vm],Vm>3){var sc=HDe[Vm];Cl+=P1e(Ot,Ss)&(1<Mr){Qs&&Wv(0);break}Hs&&Gs(Zs+131072);var tu=Zs+Rd;if(ZsDl.length)&&(su=Dl.length),new Yg(Dl.subarray(0,su))}(Bt,0,Zs):Bt.subarray(0,Zs)}(He.subarray(bt,-8),{i:2},new Yg(((st=He)[(mt=st.length)-4]|st[mt-3]<<8|st[mt-2]<<16|st[mt-1]<<24)>>>0),ot)));var He,ot,st,mt,bt;const wt=kkt[Fe];if(!wt)throw new Error(`Unhandled codec: ${Fe}`);const Gt=new globalThis.DecompressionStream(wt);return new Response(new Blob([Te]).stream().pipeThrough(Gt)).arrayBuffer().then(Ot=>new Uint8Array(Ot))}(le,oe).then(Te=>(function(Fe,He){Fe.readFields(dkt,He)}(new L1e(Te),ge),new Ckt[$](ge.buffer))),_e.then(Te=>{for(let Fe=re.length-1;Fe>=0;Fe--)switch(re[Fe]){case"delta_filter":hkt(Te,V);break;case"zigzag_filter":mkt(Te);break;case"bitshuffle_filter":fkt(Te,$);break;default:throw new gy(`Unhandled filter "${re[Fe]}"`)}return{layerName:T,blockIndex:X,data:Te}}).catch(Te=>{throw Te})}))},Wr(JDe,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Wr(jU,"MapboxRasterTile"),Wr(QDe,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const eRe=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class D1e{static from(h){if(!(h instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[p,w]=new Uint8Array(h,0,2);if(p!==219)throw new Error("Data does not appear to be in a KDBush format.");const T=w>>4;if(T!==1)throw new Error(`Got v${T} data when expected v1.`);const I=eRe[15&w];if(!I)throw new Error("Unrecognized array type.");const[L]=new Uint16Array(h,2,1),[$]=new Uint32Array(h,4,1);return new D1e($,L,I,h)}constructor(h,p=64,w=Float64Array,T){if(isNaN(h)||h<0)throw new Error(`Unpexpected numItems value: ${h}.`);this.numItems=+h,this.nodeSize=Math.min(Math.max(+p,2),65535),this.ArrayType=w,this.IndexArrayType=h<65536?Uint16Array:Uint32Array;const I=eRe.indexOf(this.ArrayType),L=2*h*this.ArrayType.BYTES_PER_ELEMENT,$=h*this.IndexArrayType.BYTES_PER_ELEMENT,V=(8-$%8)%8;if(I<0)throw new Error(`Unexpected typed array class: ${w}.`);T&&T instanceof ArrayBuffer?(this.data=T,this.ids=new this.IndexArrayType(this.data,8,h),this.coords=new this.ArrayType(this.data,8+$+V,2*h),this._pos=2*h,this._finished=!0):(this.data=new ArrayBuffer(8+L+$+V),this.ids=new this.IndexArrayType(this.data,8,h),this.coords=new this.ArrayType(this.data,8+$+V,2*h),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+I]),new Uint16Array(this.data,2,1)[0]=p,new Uint32Array(this.data,4,1)[0]=h)}add(h,p){const w=this._pos>>1;return this.ids[w]=w,this.coords[this._pos++]=h,this.coords[this._pos++]=p,w}finish(){const h=this._pos>>1;if(h!==this.numItems)throw new Error(`Added ${h} items when expected ${this.numItems}.`);return R1e(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(h,p,w,T){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:I,coords:L,nodeSize:$}=this,V=[0,I.length-1,0],X=[];for(;V.length;){const re=V.pop()||0,oe=V.pop()||0,le=V.pop()||0;if(oe-le<=$){for(let Fe=le;Fe<=oe;Fe++){const He=L[2*Fe],ot=L[2*Fe+1];He>=h&&He<=w&&ot>=p&&ot<=T&&X.push(I[Fe])}continue}const ge=le+oe>>1,_e=L[2*ge],Te=L[2*ge+1];_e>=h&&_e<=w&&Te>=p&&Te<=T&&X.push(I[ge]),(re===0?h<=_e:p<=Te)&&(V.push(le),V.push(ge-1),V.push(1-re)),(re===0?w>=_e:T>=Te)&&(V.push(ge+1),V.push(oe),V.push(1-re))}return X}within(h,p,w){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:T,coords:I,nodeSize:L}=this,$=[0,T.length-1,0],V=[],X=w*w;for(;$.length;){const re=$.pop()||0,oe=$.pop()||0,le=$.pop()||0;if(oe-le<=L){for(let Fe=le;Fe<=oe;Fe++)sRe(I[2*Fe],I[2*Fe+1],h,p)<=X&&V.push(T[Fe]);continue}const ge=le+oe>>1,_e=I[2*ge],Te=I[2*ge+1];sRe(_e,Te,h,p)<=X&&V.push(T[ge]),(re===0?h-w<=_e:p-w<=Te)&&($.push(le),$.push(ge-1),$.push(1-re)),(re===0?h+w>=_e:p+w>=Te)&&($.push(ge+1),$.push(oe),$.push(1-re))}return V}}function R1e(v,h,p,w,T,I){if(T-w<=p)return;const L=w+T>>1;tRe(v,h,L,w,T,I),R1e(v,h,p,w,L-1,1-I),R1e(v,h,p,L+1,T,1-I)}function tRe(v,h,p,w,T,I){for(;T>w;){if(T-w>600){const X=T-w+1,re=p-w+1,oe=Math.log(X),le=.5*Math.exp(2*oe/3),ge=.5*Math.sqrt(oe*le*(X-le)/X)*(re-X/2<0?-1:1);tRe(v,h,p,Math.max(w,Math.floor(p-re*le/X+ge)),Math.min(T,Math.floor(p+(X-re)*le/X+ge)),I)}const L=h[2*p+I];let $=w,V=T;for(_R(v,h,w,p),h[2*T+I]>L&&_R(v,h,w,T);$L;)V--}h[2*w+I]===L?_R(v,h,w,V):(V++,_R(v,h,V,T)),V<=p&&(w=V+1),p<=V&&(T=V-1)}}function _R(v,h,p,w){O1e(v,p,w),O1e(h,2*p,2*w),O1e(h,2*p+1,2*w+1)}function O1e(v,h,p){const w=v[h];v[h]=v[p],v[p]=w}function sRe(v,h,p,w){const T=v-p,I=h-w;return T*T+I*I}o.$=iy,o.A=class{constructor(v,h,p){this.target=v,this.parent=h,this.mapId=p,this.callbacks={},this.cancelCallbacks={},Xt(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new RNt}send(v,h,p,w,T=!1,I){const L=Math.round(1e18*Math.random()).toString(36).substring(0,10);p&&(p.metadata=I,this.callbacks[L]=p);const $=new Set;return this.target.postMessage({id:L,type:v,hasCallback:!!p,targetMapId:w,mustQueue:T,sourceMapId:this.mapId,data:ec(h,$)},$),{cancel:()=>{p&&delete this.callbacks[L],this.target.postMessage({id:L,type:"",targetMapId:w,sourceMapId:this.mapId})}}}receive(v){const h=v.data;if(!h)return;const p=h.id;if(p&&(!h.targetMapId||this.mapId===h.targetMapId))if(h.type===""){const w=this.cancelCallbacks[p];delete this.cancelCallbacks[p],w&&w.cancel()}else if(h.mustQueue||ca(self)){const w=this.callbacks[p],T=this.scheduler.add(()=>this.processTask(p,h),w&&w.metadata||{type:"message"});T&&(this.cancelCallbacks[p]=T)}else this.processTask(p,h)}processTask(v,h){if(delete this.cancelCallbacks[v],h.type===""){const p=this.callbacks[v];delete this.callbacks[v],p&&(h.error?p(Hl(h.error)):p(null,Hl(h.data)))}else{const p=new Set,w=h.hasCallback?(I,L)=>{this.target.postMessage({id:v,type:"",sourceMapId:this.mapId,error:I?ec(I):null,data:ec(L,p)},p)}:()=>{},T=Hl(h.data);if(this.parent[h.type])this.parent[h.type](h.sourceMapId,T,w);else if(this.parent.getWorkerSource){const I=h.type.split("."),{source:L,scope:$}=T;this.parent.getWorkerSource(h.sourceMapId,{type:I[0],source:L,scope:$,uid:0})[I[1]](T,w)}else w(new Error(`Could not find function ${h.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=Lm,o.C=_c,o.D=Rm,o.E=xf,o.F=yt,o.G=2,o.H=nR,o.I=It,o.J=b8e,o.K=bw,o.L=Xw,o.M=ty,o.N=rb,o.O=$m,o.P=gs,o.Q=wf,o.R=Lg,o.S=oN,o.T=Mb,o.U=cy,o.V=pU,o.W=jb,o.X=Yp,o.Y=qw,o.Z=Yh,o._=ay,o.a=function(v){return Qn.API_CDN_URL_REGEX.test(v)},o.a$=X$,o.a0=wc,o.a1=Dg,o.a2=bv,o.a3=Sn,o.a4=Qw,o.a5=class extends pU{},o.a6=lN,o.a7=iN,o.a8=as,o.a9=function(v){const h=v.value;return h?bv(h)?N1e(h,!0)?[]:[new pU(v.key,h,`invalid url "${h}"`)]:[new pU(v.key,h,`string expected, "${ty(h)}" found`)]:[]},o.aA=KLe,o.aB=function(v){let h=1/0,p=1/0,w=-1/0,T=-1/0;for(const I of v)h=Math.min(h,I.x),p=Math.min(p,I.y),w=Math.max(w,I.x),T=Math.max(T,I.y);return{min:new gs(h,p),max:new gs(w,T)}},o.aC=Ke,o.aD=N,o.aE=vt,o.aF=Tt,o.aG=Tf,o.aH=er,o.aI=en,o.aJ=function(v,h){const p={};for(let w=0;w=0?h.slice(p+1):""}catch{return""}},o.aN=class{constructor(v){this.entries={},this.scheduler=v}request(v,h,p,w){const T=this.entries[v]=this.entries[v]||{callbacks:[]};if(T.result){const[I,L]=T.result;return this.scheduler?this.scheduler.add(()=>{w(I,L)},h):w(I,L),()=>{}}return T.callbacks.push(w),T.cancel||(T.cancel=p((I,L)=>{T.result=[I,L];for(const $ of T.callbacks)this.scheduler?this.scheduler.add(()=>{$(I,L)},h):$(I,L);setTimeout(()=>delete this.entries[v],3e3)})),()=>{T.result||(T.callbacks=T.callbacks.filter(I=>I!==w),T.callbacks.length||(T.cancel(),delete this.entries[v]))}}},o.aO=function(v,h,p){const w=JSON.stringify(v.request);return v.data&&(this.deduped.entries[w]={result:[null,v.data]}),this.deduped.request(w,{type:"parseTile",renderSourceType:v.renderSourceType,zoom:v.tileZoom},T=>{const I=X0(v.request,(L,$,V)=>{L?np(L)?T(null,null):T(L):$&&T(null,{rawData:$,vectorTile:p?void 0:new Ii(new X$($)),responseHeaders:new Map(V.entries())})});return()=>{I.cancel(),T(null,null)}},h)},o.aP=function(v){return v?{cacheControl:v.get("cache-control"),expires:v.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(v){X1++,X1>Y0&&(v.getActor().send("enforceCacheSizeLimit",K0),X1=0)},o.aR=qm,o.aS=tDe,o.aT=cDe,o.aU=Zt,o.aV=eDe,o.aW=function(v,h){const p=document.createElement("video");p.muted=!0,p.onloadstart=function(){h(null,p)};for(let w=0;w{}}},o.aX=JD,o.aY=cC,o.aZ=Xt,o.a_=jU,o.aa=mN,o.ab=Io,o.ac=yr,o.ad=class{constructor(v){this.specification=v}possiblyEvaluate(v,h){return wn(v.expression.evaluate(h))}interpolate(v,h,p){return{x:An(v.x,h.x,p),y:An(v.y,h.y,p),z:An(v.z,h.z,p),azimuthal:An(v.azimuthal,h.azimuthal,p),polar:An(v.polar,h.polar,p)}}},o.ae=ja,o.af=Zp,o.ag=on,o.ah=Qe,o.ai=te,o.aj=at,o.ak=Id,o.al=aj,o.am=An,o.an=Lr,o.ao=fd,o.ap=ps,o.aq=Vr,o.ar=class{constructor(v){this.specification=v}possiblyEvaluate(v,h){return function([p,w]){const T=wn([1,p,w]);return{x:T.x,y:T.y,z:T.z}}(v.expression.evaluate(h))}interpolate(v,h,p){return{x:An(v.x,h.x,p),y:An(v.y,h.y,p),z:An(v.z,h.z,p)}}},o.as=function(v,h,p=0,w=!0){const T=new gs(p,p),I=v.sub(T),L=h.add(T),$=[I,new gs(L.x,I.y),L,new gs(I.x,L.y)];return w&&$.push(I.clone()),$},o.at=function(v,h){const p=[];for(let w=0;wthis.buckets[oe].layers.some(le=>L.has(le.fqid))),V=Object.keys(this.buckets).some(oe=>this.buckets[oe].layers.some(le=>le.hasTransition&&le.hasTransition())),X=this._firstPrepareComplete&&I!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(h));const re=this._lastUpdatedBrightness!==w;this._lastAvailableImagesCount=I,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||w||this._hasAppearances||$||V||X)&&(!(this._hasAppearances||$||V||X)&&this._lastUpdatedBrightness&&w&&Math.abs(this._lastUpdatedBrightness-w)<.001||(this.updateBuckets(h,re,void 0,X||$||V,L,T),this._lastUpdatedBrightness=w))}evaluateQueryRenderedFeaturePadding(){let v=0;for(const h in this.buckets){const p=this.buckets[h];p.evaluateQueryRenderedFeaturePadding&&(v=Math.max(v,p.evaluateQueryRenderedFeaturePadding()))}return v}queryRenderedFeatures(v,h,p,w,T,I,L){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const $=this.evaluateQueryRenderedFeaturePadding(),V=function(X,re){const oe=F([],[.5*X.width,.5*-X.height,1]);return C(oe,oe,[1,-1,0]),N(oe,oe,X.calculateProjMatrix(re.toUnwrapped())),Float32Array.from(oe)}(T,this.tileID);return this.latestFeatureIndex.query(v,{tilespaceGeometry:h,pixelPosMatrix:V,transform:w,availableImages:p,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:$,scope:L})}querySourceFeatures(v,h){const p=this.latestFeatureIndex;if(!p||!p.rawTileData)return;const w=p.loadVTLayers(),T=h?h.sourceLayer:"",I=w._geojsonTileLayer||w[T];if(!I)return;const L=xN(h&&h.filter),{z:$,x:V,y:X}=this.tileID.canonical,re={z:$,x:V,y:X};for(let oe=0;oep)w=!1;else if(h)if(this.expirationTimep.appearances&&p.appearances.length>0))return!0;return!1}updateBuckets(v,h,p,w,T,I){if(!this.latestFeatureIndex||!v.style)return;const L=I||v.style.listImages(),$=v.style.getBrightness(),V=T||new Set;for(const X in this.buckets){if(!v.style.hasLayer(X))continue;const re=this.buckets[X],oe=re.layers[0],le=oe.sourceLayer||"_geojsonTileLayer",ge=v.style.getLayerSourceCache(oe),_e=re.layers.some(bt=>V.has(bt.fqid)),Te=(w||_e)&&re instanceof Hv?v.style.getOwnLayer(X):void 0;let Fe=p&&p[le]||{};ge&&!p&&(Fe=ge._state.getState(le,void 0));const He=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},ot=Object.keys(Fe).length>0&&!h;re.hasAppearances=re.layers.some(bt=>bt.appearances&&bt.appearances.length>0);const st=ot?re.stateDependentLayers:re.layers;if(ot&&re.stateDependentLayers.length!==0||h||_e||w){const bt=this.latestFeatureIndex.loadVTLayers()[le];if(re.update(Fe,bt,L,He,st,h,$,this.tileID.canonical),(w||_e)&&!h&&re instanceof Hv&&Te&&Te.type==="symbol"){const wt=re;wt.text&&wt.text.uboBinder&&wt.text.uboBinder.updateDynamicExpressions(Te,bt,this.tileID.canonical,L,Fe,$),wt.icon&&wt.icon.uboBinder&&wt.icon.uboBinder.updateDynamicExpressions(Te,bt,this.tileID.canonical,L,Fe,$)}if(re instanceof Hv){const wt=re,Gt=v.context;wt.text&&wt.text.uboBinder&&wt.text.uboBinder.upload(Gt),wt.icon&&wt.icon.uboBinder&&wt.icon.uboBinder.upload(Gt)}}if(ot&&re.stateDependentLayers.length!==0||h||re.hasAppearances){const bt={zoom:v.transform.zoom,pitch:v.transform.pitch,brightness:v.style.getBrightness()||0,worldview:v.worldview},wt=re.updateAppearances(this.tileID.canonical,Fe,L,bt,v.imageManager,ot&&re.stateDependentLayers.length!==0);if(wt&&wt.hasUboChanges){const Gt=v.context;re instanceof Hv&&re.text&&re.text.uboBinder&&re.text.uboBinder.upload(Gt),re instanceof Hv&&re.icon&&re.icon.uboBinder&&re.icon.uboBinder.upload(Gt)}}(re instanceof Z$||re instanceof M$)&&v._terrain&&v._terrain.enabled&&ge&&re.uploadPending()&&v._terrain._clearRenderCacheForTile(ge.id,this.tileID);const mt=v&&v.style&&v.style.getOwnLayer(X);mt&&(this.queryPadding=Math.max(this.queryPadding,mt.queryRadius(re)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Te--){const Fe=4*Te,He=EN[Fe+0],ot=EN[Fe+1],st=EN[Fe+2],mt=EN[Fe+3],bt=He+st>>1,wt=ot+mt>>1,Gt=bt+wt-ot,Ot=wt+He-bt,Ht=ot*Ib+He,Bt=mt*Ib+st,$t=wt*Ib+bt,Es=Math.hypot((Pb[2*Ht+0]+Pb[2*Bt+0])/2-Pb[2*$t+0],(Pb[2*Ht+1]+Pb[2*Bt+1])/2-Pb[2*$t+1])>=16;AN[$t]=AN[$t]||(Es?1:0),Te<1022&&(AN[$t]=AN[$t]||AN[(ot+Ot>>1)*Ib+(He+Gt>>1)]||AN[(mt+Ot>>1)*Ib+(st+Gt>>1)])}const re=new Ja,oe=new Gl;let le=0;function ge(Te,Fe){const He=Fe*Ib+Te;return gU[He]===0&&(re.emplaceBack(Pb[2*He+0],Pb[2*He+1],Te*Lr/xy,Fe*Lr/xy),gU[He]=++le),gU[He]-1}function _e(Te,Fe,He,ot,st,mt){const bt=Te+He>>1,wt=Fe+ot>>1;if(Math.abs(Te-st)+Math.abs(Fe-mt)>1&&AN[wt*Ib+bt])_e(st,mt,Te,Fe,bt,wt),_e(He,ot,st,mt,bt,wt);else{const Gt=ge(Te,Fe),Ot=ge(He,ot),Ht=ge(st,mt);oe.emplaceBack(Gt,Ot,Ht)}}return _e(0,0,xy,xy,xy,0),_e(xy,xy,0,0,0,xy),{vertices:re,indices:oe}}(this.tileID.canonical,h);w=I.vertices,T=I.indices}else{w=new Ja,T=new Gl;for(const{x:L,y:$}of p)w.emplaceBack(L,$,0,0);const I=UM(w.int16.subarray(0,4*w.length),void 0,4);for(let L=0;L0&&(L=j(new Float64Array(16),h.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(v,w,h,T,L,I),this._makeGlobeTileDebugTextBuffer(v,w,h,T,L,I)}_globePoint(v,h,p,w,T,I,L){let $=RD(v,h,p);if(I){const V=1<.5?le=-1:oe<-.5&&(le=1);let ge=(v/Lr+p.x)/V+le,_e=(h/Lr+p.y)/V;ge=(ge-X)*w._pixelsPerMercatorPixel+X,_e=(_e-re)*w._pixelsPerMercatorPixel+re;const Te=[ge*w.worldSize,_e*w.worldSize,0];Qe(Te,Te,I),$=nj($,Te,L)}return Qe($,$,T)}_makeGlobeTileDebugBorderBuffer(v,h,p,w,T,I){const L=new Ra,$=new tj,V=new Ai,X=(oe,le,ge,_e,Te)=>{const Fe=(ge-oe)/(Te-1),He=(_e-le)/(Te-1),ot=L.length;for(let st=0;stX*oe+le;for(let oe=0;oe1)return!1;const p=h.getSource().maxzoom,w=1<1)return h;const T=w.getSource().maxzoom,I=1<{const $=this.getAtTileOffset(v,T,I,L),V=w.upVector(v.canonical,T.x,T.y);return xe(V,V,$*w.upVectorScale(v.canonical,h,p).metersToTile),V}}getForTilePoints(v,h,p,w){if(this.isUsingMockSource())return!1;const T=t6.create(this,v,w);return!!T&&(h.forEach(I=>{I[2]=this.exaggeration()*T.getElevationAt(I[0],I[1],p)}),!0)}getMinMaxForTile(v){if(this.isUsingMockSource())return null;const h=this.findDEMTileFor(v);if(!h||!h.dem)return null;const p=h.dem.tree,w=h.tileID,T=1<0&&(w+=(v[T]-0)*(v[T]-0)),h[T]<0&&(w+=(0-h[T])*(0-h[T]));return w},o.cL=function(v){return v*v*v*v*v},o.cM=Ns,o.cN=45,o.cO=zM,o.cP=function(v,h,p){const w=Math.sqrt(v*v+h*h+p*p),T=w>0?Math.acos(p/w)*Br:0;let I=v!==0||h!==0?Math.atan2(-h,-v)*Br+90:0;return I<0&&(I+=360),[w,I,T]},o.cQ=ne,o.cR=wn,o.cS=nr,o.cT=ue,o.cU=Xi,o.cV=me,o.cW=function(v){return[Math.pow(v[0],1/2.2),Math.pow(v[1],1/2.2),Math.pow(v[2],1/2.2)]},o.cX=MLe,o.cY=Gve,o.cZ=RLe,o.c_=N1e,o.ca=2,o.cb=7,o.cc=6,o.cd=ve,o.ce=Q,o.cf=W,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=$M,o.cl=pp,o.cm=PLe,o.cn=J4,o.co=lPe,o.cp=function(v,h,p,w,T,I,L,$,V){if(V.name==="globe")return lPe(v,h,new J4(p,w,T),!1);const X=iC({z:p,x:w,y:T},V);return new Xi([(I+X.x/X.scale)*h,h*(X.y/X.scale),L],[(I+X.x2/X.scale)*h,h*(X.y2/X.scale),$])},o.cq=function(v,h,p){return v[0]=Math.min(h[0],p[0]),v[1]=Math.min(h[1],p[1]),v[2]=Math.min(h[2],p[2]),v[3]=Math.min(h[3],p[3]),v},o.cr=function(v,h,p){return v[0]=Math.max(h[0],p[0]),v[1]=Math.max(h[1],p[1]),v[2]=Math.max(h[2],p[2]),v[3]=Math.max(h[3],p[3]),v},o.cs=function(v){const h=Math.round((v+45+360)%360/90)%4;return Qr[h]},o.ct=qs,o.cu=Ze,o.cv=6,o.cw=function(v){const h=b(new Float64Array(16));N(h,v.pixelMatrix,v.globeMatrix);const p=[0,Rt,0],w=[0,Wt,0];return Qe(p,p,h),Qe(w,w,h),[p[0]>0&&p[0]<=v.width&&p[1]>0&&p[1]<=v.height&&!mve(v,new Zt(v.center.lat,90)),w[0]>0&&w[0]<=v.width&&w[1]>0&&w[1]<=v.height&&!mve(v,new Zt(v.center.lat,-90))]},o.cx=function(v,h){const{scale:p}=v.tileTransform,w=p*Lr/(v.tileSize*Math.pow(2,h.zoom-v.tileID.overscaledZ+v.tileID.canonical.z));return function(T,I,L){var $=I[1],V=I[2],X=I[3],re=L[0],oe=L[1];return T[0]=I[0]*re,T[1]=$*re,T[2]=V*oe,T[3]=X*oe,T}(new Float32Array(4),h.inverseAdjustmentMatrix,[w,w])},o.cy=V$,o.cz=Z,o.d=function(v){return Qn.API_TILEJSON_REGEX.test(v)},o.d$=Rwt,o.d0=Pl,o.d1=class{static calculate(v,h,p){const w=new Set,T=new Map,I=new Set,L=new Set;for(const V of Object.values(v))for(const[X,re]of Object.entries(V.floors)){I.add(X),re.isDefault&&L.add(X),re.conflicts&&T.set(X,re.conflicts);const oe=X===h,le=re.connections&&h&&re.connections.has(h);(oe||le)&&w.add(X)}const $=V=>{const X=T.get(V)||new Set;for(const re of w)if((T.get(re)||new Set).has(V)||X.has(re))return!0;return!1};if(p)for(const V of p)I.has(V)&&($(V)||w.add(V));for(const V of L)w.has(V)||$(V)||w.add(V);return w}},o.d2=tU,o.d3=u1e,o.d4=qa,o.d5=function(){return{API_URL:Qn.API_URL,DRACO_URL:Qn.DRACO_URL,MESHOPT_URL:Qn.MESHOPT_URL,MESHOPT_SIMD_URL:Qn.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Qn.BUILDING_GEN_URL}},o.d6=TM,o.d7=gw,o.d8=md,o.d9=cr,o.dA=w$,o.dB=Ra,o.dC=Gl,o.dD=function(v,h){return[Math.pow(v[0],2.2)*h,Math.pow(v[1],2.2)*h,Math.pow(v[2],2.2)*h]},o.dE=m,o.dF=function(v,h){var p=Math.sin(h),w=Math.cos(h);return v[0]=w,v[1]=p,v[2]=0,v[3]=-p,v[4]=w,v[5]=0,v[6]=0,v[7]=0,v[8]=1,v},o.dG=we,o.dH=dPe,o.dI=Qa,o.dJ=Hi,o.dK=w1e,o.dL=function(v,h){const p=[0,0,0];return Qe(p,p,OD(Tb(h.canonical))),Qe(p,p,v),p},o.dM=v=>({u_matrix:new g(v),u_texsize:new Kx(v),u_pixels_to_tile_units:new z(v),u_device_pixel_ratio:new Xc(v),u_width_scale:new Xc(v),u_floor_width_scale:new Xc(v),u_image:new X4(v),u_units_to_pixels:new Kx(v),u_tile_units_to_pixels:new Xc(v),u_alpha_discard_threshold:new Xc(v),u_trim_offset:new Kx(v),u_trim_fade_range:new Kx(v),u_trim_gradient_mix_range:new Kx(v),u_trim_color:new zM(v),u_zbias_factor:new Xc(v),u_tile_to_meter:new Xc(v),u_ground_shadow_factor:new Q4(v),u_pattern_transition:new Xc(v)}),o.dN=v=>({u_matrix:new g(v),u_pixels_to_tile_units:new z(v),u_device_pixel_ratio:new Xc(v),u_width_scale:new Xc(v),u_floor_width_scale:new Xc(v),u_units_to_pixels:new Kx(v),u_dash_image:new X4(v),u_gradient_image:new X4(v),u_image_height:new Xc(v),u_texsize:new Kx(v),u_tile_units_to_pixels:new Xc(v),u_alpha_discard_threshold:new Xc(v),u_trim_offset:new Kx(v),u_trim_fade_range:new Kx(v),u_trim_gradient_mix_range:new Kx(v),u_trim_color:new zM(v),u_zbias_factor:new Xc(v),u_tile_to_meter:new Xc(v),u_ground_shadow_factor:new Q4(v)}),o.dO=v=>({u_camera_to_center_distance:new Xc(v),u_extrude_scale:new z(v),u_device_pixel_ratio:new Xc(v),u_matrix:new g(v),u_inv_rot_matrix:new g(v),u_merc_center:new Kx(v),u_tile_id:new Q4(v),u_zoom_transition:new Xc(v),u_up_dir:new Q4(v),u_emissive_strength:new Xc(v)}),o.dP=ND,o.dQ=D2t,o.dR=class{constructor(v,h,p,w){this.context=v,this.format=w,this.size=p,this.texture=v.gl.createTexture();const[T,I,L]=this.size,{gl:$}=v;$.bindTexture($.TEXTURE_3D,this.texture),v.pixelStoreUnpackFlipY.set(!1),v.pixelStoreUnpack.set(1),v.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in h&&h.data&&$.texImage3D($.TEXTURE_3D,0,this.format,T,I,L,0,zve(this.format),Bve(this.format),h.data)}bind(v,h){const{context:p}=this,{gl:w}=p;w.bindTexture(w.TEXTURE_3D,this.texture),v!==this.minFilter&&(w.texParameteri(w.TEXTURE_3D,w.TEXTURE_MAG_FILTER,v),w.texParameteri(w.TEXTURE_3D,w.TEXTURE_MIN_FILTER,v),this.minFilter=v),h!==this.wrapS&&(w.texParameteri(w.TEXTURE_3D,w.TEXTURE_WRAP_S,h),w.texParameteri(w.TEXTURE_3D,w.TEXTURE_WRAP_T,h),this.wrapS=h)}destroy(){const{gl:v}=this.context;v.deleteTexture(this.texture),this.texture=null}},o.dS=fPe,o.dT=(v,h,p,w,T,I)=>{const L=v.transform,$=L.projection.name==="globe";let V;if(I.paint.get("circle-pitch-alignment")==="map")if($){const re=dPe(L.zoom,h.canonical)*L._pixelsPerMercatorPixel;V=Float32Array.from([re,0,0,re])}else V=L.calculatePixelsToTileUnitsMatrix(p);else V=new Float32Array([L.pixelsToGLUnits[0],0,0,L.pixelsToGLUnits[1]]);const X={u_camera_to_center_distance:v.transform.getCameraToCenterDistance(L.projection),u_matrix:v.translatePosMatrix(h.projMatrix,p,I.paint.get("circle-translate"),I.paint.get("circle-translate-anchor")),u_device_pixel_ratio:Cd.devicePixelRatio,u_extrude_scale:V,u_inv_rot_matrix:Uwt,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:I.paint.get("circle-emissive-strength")};if($){X.u_inv_rot_matrix=w,X.u_merc_center=T,X.u_tile_id=[h.canonical.x,h.canonical.y,1<{const re=v.transform,oe=re.pitch<15?YLe(.07,.7,Ke((14-re.zoom)/5,0,1)):.07,le=p.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:XLe(v,h,p,w),u_texsize:h.imageAtlasTexture?h.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:re.calculatePixelsToTileUnitsMatrix(h),u_device_pixel_ratio:T,u_width_scale:I,u_floor_width_scale:L,u_image:0,u_tile_units_to_pixels:ZLe(h,re),u_units_to_pixels:[1/re.pixelsToGLUnits[0],1/re.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:$,u_trim_fade_range:p.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:p.paint.get("line-trim-color").toPremultipliedRenderColor(le?null:p.lut).toArray01(),u_zbias_factor:oe,u_tile_to_meter:nr(h.tileID.canonical,0),u_ground_shadow_factor:V,u_pattern_transition:X}},o.dX=(v,h,p,w,T,I,L,$,V,X)=>{const re=v.transform,oe=re.calculatePixelsToTileUnitsMatrix(h),le=p.paint.get("line-trim-color-use-theme").constantOr("default")==="none",ge=re.pitch<15?YLe(.07,.7,Ke((14-re.zoom)/5,0,1)):.07;return{u_matrix:XLe(v,h,p,w),u_pixels_to_tile_units:oe,u_device_pixel_ratio:I,u_width_scale:L,u_floor_width_scale:$,u_units_to_pixels:[1/re.pixelsToGLUnits[0],1/re.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:T,u_texsize:JLe(p)&&h.lineAtlasTexture?h.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:ZLe(h,v.transform),u_alpha_discard_threshold:0,u_trim_offset:V,u_trim_fade_range:p.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:p.paint.get("line-trim-color").toPremultipliedRenderColor(le?null:p.lut).toArray01(),u_zbias_factor:ge,u_tile_to_meter:nr(h.tileID.canonical,0),u_ground_shadow_factor:X}},o.dY=it,o.dZ=FD,o.d_=Rs,o.da=function(v){const h=v.indexOf(Je);return h>=0?v.slice(0,h):v},o.db=function(v){return v.indexOf(Je)>=0},o.dc=function(v){const h=v.lastIndexOf(Je);return h>=0?v.slice(h+1):""},o.dd=function(v){const h=[],p=v.id;return p===void 0&&h.push({message:`layers.${p}: missing required property "id"`}),v.render===void 0&&h.push({message:`layers.${p}: missing required method "render"`}),v.renderingMode&&v.renderingMode!=="2d"&&v.renderingMode!=="3d"&&h.push({message:`layers.${p}: property "renderingMode" must be either "2d" or "3d"`}),h},o.de=function(v,h,p,w){return v.type==="custom"?new TNt(v,h):new PNt[v.type](v,h,p,w)},o.df=us,o.dg=xN,o.dh=ns,o.di=class extends lC{constructor(v,h){super(v._vectorTileFeature,v._z,v._x,v._y,v.id),v.state&&(this.state=Object.assign({},v.state)),this.target=h.target,this.namespace=h.namespace,h.properties&&(this.properties=h.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=v.source,this.sourceLayer=v.sourceLayer,this.layer=v.layer)}toJSON(){const v=super.toJSON();return v.target=this.target,v.namespace=this.namespace,v}},o.dj=hN,o.dk=function(v){return v({pluginStatus:Md,pluginURL:kf}),hN.on("pluginStateChange",v),v},o.dl=lve,o.dm=class extends Wx{constructor(v){super(v),this.current=S}set(v,h,p){if(this.fetchUniformLocation(v,h)){for(let w=0;w<9;w++)if(p[w]!==this.current[w]){this.current=p,this.gl.uniformMatrix3fv(this.location,!1,p);break}}}},o.dn=Tn,o.dp=function(v,h,p){const w=aj(p.zoom),T=v.style.map._antialias,I=v.terrain&&v.terrain.exaggeration()>0;return w===0&&!T&&!I},o.dq=function(v){const h=v.pixelsPerMeter,p=h/hs(1,v.center.lat),w=b(new Float64Array(16));return C(w,w,[v.point.x,v.point.y,0]),A(w,w,[p,p,h]),Float32Array.from(w)},o.dr=j$,o.ds=function(v){const h=80.051129;v=Ke(v,-80.051129,h)/h*90;const p=Math.pow(Math.abs(Math.sin(ps(v))),3);return Math.round(p*(Kt.length-1))},o.dt=function(v,h,p,w){const T=h.getNorth(),I=h.getSouth(),L=h.getWest(),$=h.getEast(),V=1<0){const _e=180/w;x(ge,ge,[_e/X+1,0,0,0,_e/re+1,0,-.5*_e/oe,.5*_e/le,1])}return ge[2]=V,ge[5]=v.x,ge[8]=v.y,ge},o.du=OD,o.dv=Tb,o.dw=function(v,h,p){const w=b(new Float64Array(16)),T=(h/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(v,h=!1){const p=KPe(new gs(0,0),new gs(Lr,Lr),v),w=[];if(h&&!Tve(p,this._globalClipBounds))return w;for(const T of this._activeRegions){if(T.hiddenByOverlap||!Tve(p,T))continue;const I=Njt(T.min,T.max,v);w.push({min:I.min,max:I.max,sourceId:this._sourceIds[T.priority],footprint:T.footprint,footprintTileId:T.tileId,order:T.order,clipMask:T.clipMask,clipScope:T.clipScope})}return w}setSources(v){this._setSources(v.map(h=>({getSourceId:()=>h.cache.id,getFootprints:()=>{const p=[];for(const w of h.cache.getVisibleCoordinates()){const T=h.cache.getTile(w).buckets[h.layer];T&&T.updateFootprints(w.toUnwrapped(),p)}return p},getOrder:()=>h.order,getClipMask:()=>h.clipMask,getClipScope:()=>h.clipScope})))}_addSource(v){const h=v.getFootprints();if(h.length===0)return;const p=v.getOrder(),w=v.getClipMask(),T=v.getClipScope();for(const I of h){if(!I.footprint)continue;const L=KPe(I.footprint.min,I.footprint.max,I.id);this._activeRegions.push({min:L.min,max:L.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:I.id,footprint:I.footprint,order:p,clipMask:w,clipScope:T})}this._sourceIds.push(v.getSourceId())}_computeReplacement(){this._activeRegions.sort((h,p)=>h.priority-p.priority||P$(h.min,p.min)||P$(h.max,p.max)||h.order-p.order||h.clipMask-p.clipMask||function(w,T){const I=(L,$)=>L+$;return w.length-T.length||w.reduce(I,"").localeCompare(T.reduce(I,""))}(h.clipScope,p.clipScope));let v=this._activeRegions.length!==this._prevRegions.length;if(!v){let h=0;for(;!v&&h!==this._activeRegions.length;){const p=this._activeRegions[h],w=this._prevRegions[h];v=p.priority!==w.priority||!WPe(p,w)||p.order!==w.order||p.clipMask!==w.clipMask||!mi(p.clipScope,w.clipScope),this._activeRegions[h].hiddenByOverlap=w.hiddenByOverlap,++h}}if(v){++this._updateTime;for(const p of this._activeRegions)p.order!==GD&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,p.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,p.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,p.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,p.max.y));const h=p=>{const w=this._activeRegions;if(p>=w.length)return p;const T=w[p].priority;for(;p1){let p=0,w=h(p);for(;p!==w;){let T=p;const I=p;for(;T!==w;){const L=this._activeRegions[T];L.hiddenByOverlap=!1;for(let $=0;$=0;h--)this._addSource(v[h]);this._computeReplacement()}},o.eH=Ja,o.eI=hU,o.eJ=tj,o.eK=GD,o.eL=class{constructor(v){this._createGrid(v),this._createPoles(v)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const v of this._poleSegments)v.destroy();for(const v of this._gridSegments)v.withSkirts.destroy(),v.withoutSkirts.destroy()}_fillGridMeshWithLods(v,h){const p=new Ra,w=new Gl,T=[],I=v+1+2,L=h[0]+1,$=h[0]+1+(1+h.length),V=(X,re,oe)=>{let le=X===I-1?X-2:X===0?X:X-1;return le+=oe?24575:0,[le,re]};for(let X=0;X>>=0,v=Math.imul(2747636419^v,2654435769)>>>0,v=Math.imul(v^v>>>16,2654435769)>>>0,(v=Math.imul(v^v>>>16,2654435769)>>>0)/4294967296},o.ec=iPe,o.ed=uve,o.ee=Hx,o.ef=D,o.eg=function(v,h){return v[0]=h[0],v[1]=h[1],v[2]=h[2],v[3]=h[4],v[4]=h[5],v[5]=h[6],v[6]=h[8],v[7]=h[9],v[8]=h[10],v},o.eh=Jw,o.ei=G4,o.ej=function(v,h,p,w,T){return Ke((v-h)/(p-h)*(T-w)+w,w,T)},o.ek=es,o.el=function(v,h){var p=h[0],w=h[1],T=h[2],I=h[3],L=h[4],$=h[5],V=h[6],X=h[7],re=h[8],oe=re*L-$*X,le=-re*I+$*V,ge=X*I-L*V,_e=p*oe+w*le+T*ge;return _e?(v[0]=oe*(_e=1/_e),v[1]=(-re*w+T*X)*_e,v[2]=($*w-T*L)*_e,v[3]=le*_e,v[4]=(re*p-T*V)*_e,v[5]=(-$*p+T*I)*_e,v[6]=ge*_e,v[7]=(-X*p+w*V)*_e,v[8]=(L*p-w*I)*_e,v):null},o.em=M4,o.en=2,o.eo=ze,o.ep=kt,o.eq=B,o.er=function(v,h){var p=new d(3);B(p,h);var w=1/p[0],T=1/p[1],I=1/p[2],L=h[0]*w,$=h[1]*T,V=h[2]*I,X=h[4]*w,re=h[5]*T,oe=h[6]*I,le=h[8]*w,ge=h[9]*T,_e=h[10]*I,Te=L+re+_e,Fe=0;return Te>0?(Fe=2*Math.sqrt(Te+1),v[3]=.25*Fe,v[0]=(oe-ge)/Fe,v[1]=(le-V)/Fe,v[2]=($-X)/Fe):L>re&&L>_e?(Fe=2*Math.sqrt(1+L-re-_e),v[3]=(oe-ge)/Fe,v[0]=.25*Fe,v[1]=($+X)/Fe,v[2]=(le+V)/Fe):re>_e?(Fe=2*Math.sqrt(1+re-L-_e),v[3]=(le-V)/Fe,v[0]=($+X)/Fe,v[1]=.25*Fe,v[2]=(oe+ge)/Fe):(Fe=2*Math.sqrt(1+_e-L-re),v[3]=($-X)/Fe,v[0]=(le+V)/Fe,v[1]=(oe+ge)/Fe,v[2]=.25*Fe),v},o.es=function(v,h){var p=2*Math.acos(h[3]),w=Math.sin(p/2);return w>c?(v[0]=h[0]/w,v[1]=h[1]/w,v[2]=h[2]/w):(v[0]=1,v[1]=0,v[2]=0),p},o.et=C1e,o.eu=W$,o.ev=G$,o.ew=[1,1,1],o.ex=t6,o.ey=function(v,h,p,w){var T=h[0],I=h[1],L=h[2],$=h[3];return v[0]=T+w*(p[0]-T),v[1]=I+w*(p[1]-I),v[2]=L+w*(p[2]-L),v[3]=$+w*(p[3]-$),v},o.ez=WM,o.f=Zo,o.f0=hPe,o.f1=function(v){const h=[0,0,0],p=b(new Float64Array(16));return N(p,v.pixelMatrix,v.globeMatrix),Qe(h,h,p),new gs(h[0],h[1])},o.f2=Kg,o.f3=function(v,h,p=!1){if(Md===Qh.deferred||Md===Qh.loading||Md===Qh.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");kf=Cd.resolveURL(v),Md=Qh.deferred,fp=h,uN(),p||EM()},o.f4=Ji,o.f5=Ca,o.f6=vr,o.f7=function(v){const h=Bp();if(!h)return;const p=h.delete(Vh);v&&p.then(()=>v()).catch(v)},o.f8=Wr,o.f9=jN,o.fA=ia,o.fB=function(v){let h=0;if(new Uint32Array(v,0,1)[0]!==SLe){const p=new Uint32Array(v,0,7),[,,w,T,I,L]=p;h=p.byteLength+T+I+L+I,(w!==v.byteLength||h>=v.byteLength)&&Kr("Invalid b3dm header information.")}return ALe(v,h)},o.fC=function(v,h){const p=Gve(v);for(const w of p){for(const T of w.meshes)t2t(T);w.lights&&(w.lightMeshIndex=w.meshes.length,w.meshes.push(s2t(w.lights,h)))}return p},o.fD=xU,o.fE=ca,o.fF=Jh,o.fG=Qh,o.fH=function(v){co(),Xu!=null&&Xu.then(h=>{h.keys().then(p=>{for(let w=0;wKr(T.message))}).catch(p=>Kr(p.message))}).catch(h=>Kr(h.message))},o.fa=2,o.fb=zx,o.fc=iC,o.fd=AD,o.fe=xDe,o.ff=gDe,o.fg=HLe,o.fh=Ea,o.fi="hd_road_elevation",o.fj=To,o.fk=Bs,o.fl=M$,o.fm=ij,o.fn=c1e,o.fo=1,o.fp=Hv,o.fq=function(v,h,p,w,T,I,L,$=1,V,X,re,oe){v.createArrays(),v.tilePixelRatio=Lr/(512*v.overscaling),v.compareText={},v.iconsNeedLinear=!1;const le=v.layers[0].layout,ge=v.layers[0]._unevaluatedLayout._values,_e={};_e.scaleFactor=$,_e.textSizeScaleRange=le.get("text-size-scale-range"),_e.iconSizeScaleRange=le.get("icon-size-scale-range");const[Te,Fe]=_e.textSizeScaleRange,[He,ot]=_e.iconSizeScaleRange;_e.textScaleFactor=Ke(_e.scaleFactor,Te,Fe),_e.iconScaleFactor=Ke(_e.scaleFactor,He,ot);const st=ge["text-size"],mt=ge["icon-size"];if(v.textSizeData.kind==="composite"){const{minZoom:Bt,maxZoom:$t}=v.textSizeData;_e.compositeTextSizes=[st.possiblyEvaluate(new ja(Bt,{worldview:re}),I),st.possiblyEvaluate(new ja($t,{worldview:re}),I)]}if(v.iconSizeData.kind==="composite"){const{minZoom:Bt,maxZoom:$t}=v.iconSizeData;_e.compositeIconSizes=[mt.possiblyEvaluate(new ja(Bt,{worldview:re}),I,oe),mt.possiblyEvaluate(new ja($t,{worldview:re}),I,oe)]}_e.layoutTextSize=st.possiblyEvaluate(new ja(L+1,{worldview:re}),I),_e.layoutIconSize=mt.possiblyEvaluate(new ja(L+1,{worldview:re}),I,oe),_e.textMaxSize=st.possiblyEvaluate(new ja(18,{worldview:re}),I);const bt=le.get("symbol-placement"),wt=le.get("text-rotation-alignment")==="map"&&bt!=="point",Gt=le.get("text-size");let Ot=!1;const Ht=[];for(const Bt of v.features){const $t=le.get("text-font").evaluate(Bt,{},I).join(","),Es=Gt.evaluate(Bt,{},I)*_e.textScaleFactor,Os=_e.layoutTextSize.evaluate(Bt,{},I)*_e.textScaleFactor,Hs=_e.layoutIconSize.evaluate(Bt,{},I,oe)*_e.iconScaleFactor,Qs={horizontal:{},vertical:void 0},Gs=Bt.text;let hr,Ss=[0,0];if(Gs){const za=Gs.toString(),Ll=le.get("text-letter-spacing").evaluate(Bt,{},I)*Ld,Wi=le.get("text-line-height").evaluate(Bt,{},I)*Ld,Ci=SM(za)?Ll:0,So=le.get("text-anchor").evaluate(Bt,{},I),Sl=le.get("text-variable-anchor");if(!Sl){const Kl=le.get("text-radial-offset").evaluate(Bt,{},I);if(Kl)Ss=A8e(So,[Kl*Ld,m1e]);else{const sh=le.get("text-offset").evaluate(Bt,{},I);Ss=[sh[0]*Ld,sh[1]*Ld]}}let Dd=wt?"center":le.get("text-justify").evaluate(Bt,{},I);const Cl=bt==="point",Wl=Cl?le.get("text-max-width").evaluate(Bt,{},I)*Ld:1/0,Nc=Kl=>{v.allowVerticalPlacement&&kh(za)&&(Qs.vertical=s1e(Gs,h,p,T,$t,Wl,Wi,So,Kl,Ci,Ss,nx.vertical,!0,Os,Es,V,_e.textScaleFactor))};if(!wt&&Sl){const Kl=Dd==="auto"?Sl.map(Rd=>f1e(Rd)):[Dd];let sh=!1;for(let Rd=0;Rd=0||!kh(za)){const Kl=s1e(Gs,h,p,T,$t,Wl,Wi,So,Dd,Ci,Ss,nx.horizontal,!1,Os,Es,V,_e.textScaleFactor);Kl&&(Qs.horizontal[Dd]=Kl)}Nc(Cl?"left":Dd)}}let Zs,tr,mr,wr,tn,Mr,Tr=!1;const jr=le.get("icon-text-fit").evaluate(Bt,{},I);if(Bt.icon&&Bt.icon.hasPrimary()){const za=oR(Bt.icon,v.iconSizeData,ge["icon-size"],I,v.zoom,Bt,V,_e.iconScaleFactor,re,oe);Zs=za.iconPrimary,mr=za.iconSecondary;const Ll=Zs.toString();if(tr=w.get(Ll),tr&&(tn=le.get("icon-offset").evaluate(Bt,{},I),Mr=le.get("icon-anchor").evaluate(Bt,{},I),hr=J$(T.get(Ll),mr?T.get(mr.toString()):void 0,tn,Mr),Tr=tr.sdf,v.sdfIcons===void 0?v.sdfIcons=tr.sdf:v.sdfIcons!==tr.sdf&&Kr("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(tr.pixelRatio!==v.pixelRatio||le.get("icon-rotate").constantOr(1)!==0)&&(v.iconsNeedLinear=!0)),mr){const Wi=mr.toString();wr=w.get(Wi)}}Ot=Ot||!(!Bt.icon||!Bt.icon.hasSecondary());const Xr=iU(Qs.horizontal)||Qs.vertical;v.iconsInText||(v.iconsInText=!!Xr&&Xr.iconsInText);const ln=Os*_e.textScaleFactor/Ld,{defaultShapedIcon:On,verticallyShapedIcon:xn}=hNt(v,hr,le,Bt,I,Qs,ln,tn,jr);jr!=="none"&&hr&&(h8e(hr)||m8e(hr))&&(aU(0,tr,Zs,hr,On,jr,X,w,T),aU(0,wr,mr,hr,On,jr,X,w,T),xn&&(aU(0,tr,Zs,hr,xn,jr,X,w,T),aU(0,wr,mr,hr,xn,jr,X,w,T))),hr=On;const{iconBBox:va,iconVerticalBBox:xi,textBBox:ba,textVerticalBBox:bi}=oNt(v,hr,xn,le,Bt,I,Hs,tn,_e,T,Mr,Qs,Os,Ss,oe);Ht.push({feature:Bt,shapedTextOrientations:Qs,shapedText:Xr,shapedIcon:hr,iconPrimary:Zs,iconSecondary:mr,iconOffset:tn,iconAnchor:Mr,verticallyShapedIcon:xn,layoutTextSize:Os,layoutIconSize:Hs,textOffset:Ss,isSDFIcon:Tr,iconTextFit:jr,iconCollisionBounds:va,iconVerticalCollisionBounds:xi,textCollisionBounds:ba,textVerticalCollisionBounds:bi})}return{featureData:Ht,sizes:_e,hasAnySecondaryIcon:Ot,textAlongLine:wt,symbolPlacement:bt}},o.fr=d1e,o.fs=l1e,o.ft=w8e,o.fu=j8e,o.fv=function(v,h,p,w,T,I,L,$,V,X){v.iconAtlasPositions=X.iconPositions;const{featureData:re,hasAnySecondaryIcon:oe,sizes:le,textAlongLine:ge,symbolPlacement:_e}=h;for(const Te of re){const{shapedIcon:Fe,verticallyShapedIcon:He,feature:ot,shapedTextOrientations:st,shapedText:mt,layoutTextSize:bt,textOffset:wt,isSDFIcon:Gt,iconPrimary:Ot,iconSecondary:Ht,iconTextFit:Bt,iconOffset:$t,iconCollisionBounds:Es,iconVerticalCollisionBounds:Os,textCollisionBounds:Hs}=Te;L8e(Fe,X.iconPositions,Ot,Ht),L8e(He,X.iconPositions,Ot,Ht),uNt(st,X.iconPositions),dNt(Ot,Ht,X.iconPositions),(mt||Fe)&&mNt(v,ot,st,Fe,He,V,le,bt,0,wt,Gt,w,T,L,$,oe,Bt,$t,ge,_e,Es,Os,Hs)}p&&v.generateCollisionDebugBuffers(I,v.collisionBoxArray,le.textScaleFactor)},o.fw=Z$,o.fx=Ii,o.fy=function(v){return v<=1?1:Math.pow(2,Math.floor(Math.log2(v)))},o.fz=wU,o.g=Qn,o.h=function(v,h){return Z0(Object.assign(v,{method:"GET"}),h)},o.i=function(v){return Qn.API_STYLE_REGEX.test(v)&&!vl(v)},o.j=function(v){return btoa(encodeURIComponent(v).replace(/%([0-9A-F]{2})/g,(h,p)=>String.fromCharCode(+("0x"+p))))},o.k=Hh,o.l=function(v){return decodeURIComponent(atob(v).split("").map(h=>"%"+("00"+h.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(v,h){return Z0(Object.assign(v,{type:"json"}),h)},o.n=Up,o.o=Cd,o.p=function(v,h){return Z0(Object.assign(v,{method:"POST"}),h)},o.q=Ch,o.r=cs,o.s=function(v){try{const h=self[v];return h.setItem("_mapbox_test_",1),h.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=Ft,o.u=function(){return function v(h){return h?(h^Math.random()*(16>>h/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,v)}()},o.v=function(v){return!!v&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v)},o.w=Kr,o.x=class{constructor(v){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(v&&v.maxTextureMemoryMB?v.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(h=>{this.cache.delete(h),this.clearExpiredTextures()})}calculateTextureMemory(v){return v.image?Math.ceil(v.image.width*v.image.height*4*(v.patternPositions.size>0?1.33:1)):0}evictTexture(v){const h=this.textures.get(v);if(h){const p=this.calculateTextureMemory(v);h.destroy(),this.textures.delete(v),this.textureAccessTimes.delete(v),this.textureMemoryUsed-=p}}evictTexturesIfNeeded(v){for(;this.textureMemoryUsed+v>this.maxTextureMemory&&this.textures.size>0;){let h=null,p=1/0;for(const[w]of this.textures.entries()){const T=this.textureAccessTimes.get(w)||0;Tthis._layers[cr.id]),cs=qt[0];if(cs.visibility==="none")continue;const it=cs.source||"";let Xt=this.familiesBySource[it];Xt||(Xt=this.familiesBySource[it]=Object.create(null));const Bs=cs.sourceLayer||"_geojsonTileLayer";let us=Xt[Bs];us||(us=Xt[Bs]=[]),us.push(qt)}}}const y=1*c.fa;class _{constructor(Re){const Ke={},at=[];for(const cs in Re){const it=Re[cs],Xt=Ke[cs]={};for(const Bs in it.glyphs){const us=it.glyphs[+Bs];if(!us||us.bitmap.width===0||us.bitmap.height===0)continue;const cr=us.metrics.localGlyph?y:1,Ar={x:0,y:0,w:us.bitmap.width+2*cr,h:us.bitmap.height+2*cr};at.push(Ar),Xt[Bs]=Ar}}const{w:Nt,h:Ft}=c.J(at),qt=new c.f9({width:Nt||1,height:Ft||1});for(const cs in Re){const it=Re[cs];for(const Xt in it.glyphs){const Bs=it.glyphs[+Xt];if(!Bs||Bs.bitmap.width===0||Bs.bitmap.height===0)continue;const us=Ke[cs][Xt],cr=Bs.metrics.localGlyph?y:1;c.f9.copy(Bs.bitmap,qt,{x:0,y:0},{x:us.x+cr,y:us.y+cr},Bs.bitmap)}}this.image=qt,this.positions=Ke}}function b(Qt,Re,Ke){Qt[Re]?Ke&&(Qt[Re].center=Ke):Qt[Re]={floorIds:new Set,center:Ke||[0,0],floors:{}}}function j(Qt,Re,Ke,at){for(const Nt of Re)b(Qt,Nt),Qt[Nt].floors[Ke]=at,Qt[Nt].floorIds.add(Ke)}function N(Qt){return{id:Qt.properties.id.toString(),center:[Qt.properties.center_lon||0,Qt.properties.center_lat||0]}}function C(Qt,Re){const Ke=Qt.properties.id.toString(),at=!!Qt.properties.is_default&&Qt.properties.is_default,Nt=Qt.properties.connected_floor_ids?new Set(Qt.properties.connected_floor_ids.toString().split(";")):new Set,Ft=Qt.properties.conflicted_floor_ids?new Set(Qt.properties.conflicted_floor_ids.toString().split(";")):new Set,qt=Qt.properties.structure_ids?new Set(Qt.properties.structure_ids.toString().split(";")):new Set,cs=Qt.properties.name.toString(),it=Qt.properties.z_index,Xt=function(Bs,us){const cr=Bs.loadGeometry();if(!cr||cr.length===0)return;const Ar=cr.map(xr=>xr.map(Kr=>c.fb(Kr,us,Bs.extent)));return Ar.length===0?void 0:{type:"Polygon",coordinates:[Ar[0]]}}(Qt,Re);return{id:Ke,isDefault:at,connections:Nt,conflicts:Ft,buildings:qt,name:cs,zIndex:it,geometry:Xt}}function A(Qt,Re){return Re.every(Ke=>Qt.properties&&Qt.properties[Ke]!=null)}function E(Qt){return A(Qt,["type","id","name"])&&Qt.properties.type==="structure"}function D(Qt){return A(Qt,["type","id","name","z_index"])&&Qt.properties.type==="floor"}c.f8(_,"GlyphAtlas");class R{constructor(Re){this.tileID=new c.aR(Re.tileID.overscaledZ,Re.tileID.wrap,Re.tileID.canonical.z,Re.tileID.canonical.x,Re.tileID.canonical.y),this.tileZoom=Re.tileZoom,this.uid=Re.uid,this.zoom=Re.zoom,this.lut=Re.lut,this.canonical=Re.tileID.canonical,this.pixelRatio=Re.pixelRatio,this.tileSize=Re.tileSize,this.source=Re.source,this.scope=Re.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=Re.showCollisionBoxes,this.collectResourceTiming=!!Re.request&&Re.request.collectResourceTiming,this.promoteId=Re.promoteId,this.renderSourceType=Re.renderSourceType,this.tileTransform=c.fc(Re.tileID.canonical,Re.projection),this.projection=Re.projection,this.worldview=Re.worldview,this.localizableLayerIds=Re.localizableLayerIds,this.brightness=Re.brightness,this.extraShadowCaster=!!Re.extraShadowCaster,this.tessellationStep=Re.tessellationStep,this.scaleFactor=Re.scaleFactor,this.worldview=Re.worldview,this.indoor=Re.indoor}parse(Re,Ke,at,Nt,Ft,qt){this.status="parsing",this.data=Re,this.collisionBoxArray=new c.fd;const cs=new c.fe(Object.keys(Re.layers).sort()),it=new c.ff(this.tileID,this.promoteId);it.bucketLayerIDs=[];const Xt={},Bs=new c.fg(256,256),us={featureIndex:it,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Bs,availableImages:at,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(us.activeFloors=function(Kr,mn,pn,wn){const ca=mn.indoorState.activeFloorsVisible;if(!mn.sourceLayers)return ca?mn.indoorState.activeFloors:void 0;const Vi=function(kn,Fi){if(!kn)return c.w("No source layers defined in indoor specification"),Fi;if(kn.size===0)return Fi;const zi=kn.difference(Fi);for(const Qa of zi)c.w(`Missing source layer required in indoor specification: ${Qa}`);return Fi.intersection(Fi)}(mn.sourceLayers,new Set(Object.keys(Kr.layers))),so=mn.indoorState,Ka=function(kn,Fi,zi,Qa,Hi){const Gi={};for(const Qn of Fi){const vr=kn.layers[Qn];if(vr)for(let Ca=0;Ca=Qa.maxzoom||Qa.visibility==="none")continue;F(zi,this.zoom,us.brightness,at,this.worldview,us.activeFloors);const Hi=Xt[Qa.id]=Qa.createBucket({index:it.bucketLayerIDs.length,layers:zi,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:so,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Nt,worldview:this.worldview,localizable:kn,availableImages:at,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});it.bucketLayerIDs.push(zi.map(Qn=>c.F(Qn.id,Qn.scope)));let Gi=Hi.prepare?Hi.prepare():null;Gi!=null?(Gi=Gi.then(()=>Hi.populate(Ka,us,this.tileID.canonical,this.tileTransform)),cr.push(Gi)):Hi.populate(Ka,us,this.tileID.canonical,this.tileTransform)}}const xr=()=>{Bs.trim();const Kr=!(!us.elevationFeatures||!us.elevationFeatures.some(Qa=>Qa.heightRange.min<0));let mn,pn,wn,ca,Vi,so,Ka;const kn={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},Fi=()=>{if(mn)return this.status="done",qt(mn);if(this.extraShadowCaster)this.status="done",qt(null,{buckets:Object.values(Xt).filter(Qa=>!Qa.isEmpty()),featureIndex:it,collisionBoxArray:null,hasTunnelGeometry:Kr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:us.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(pn&&wn&&ca&&Ka){const Hi=new _(pn),Gi=new Map;for(const[Ca,Ji]of wn.entries()){const{imagePosition:Zo}=c.fn(Ca,Ji,c.fo);Gi.set(Ca,Zo)}const Qn={};for(const Ca in Xt){const Ji=Xt[Ca];Ji instanceof c.fp&&(F(Ji.layers,this.zoom,us.brightness,at,this.worldview,us.activeFloors),Qn[Ca]=c.fq(Ji,pn,Hi.positions,wn,Gi,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Vi,this.worldview,at))}const vr={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Ft,wn,Vi,()=>{vr.iconsPending=!1,zi(Qn,Hi,vr,void 0,Ka)}),this.rasterizeIfNeeded(Ft,ca,so,()=>{vr.patternsPending=!1,zi(Qn,Hi,vr,void 0,Ka)})}},zi=(Qa,Hi,Gi,Qn,vr)=>{if(Gi.iconsPending||Gi.patternsPending)return;const Ca=wn.size>0||ca.size>0,Ji=Object.keys(Qa).length>0;if(!Ca&&!Ji)return this.status="done",void qt(null,{buckets:Object.values(Xt).filter(vl=>!vl.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Kr,glyphAtlasImage:Hi.image,lineAtlas:Bs,imageAtlas:null,brightness:us.brightness});const Zo=(vl,vo)=>{for(const hd in Xt){const ju=Xt[hd];if(hd in Qa)c.fv(ju,Qa[hd],this.showCollisionBoxes,at,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,wn,vo);else if(ju.hasPattern&&(ju instanceof c.fw||ju instanceof c.fl||ju instanceof c.e0)){F(ju.layers,this.zoom,us.brightness,at,this.worldview,us.activeFloors);const sp=Object.fromEntries(vo.patternPositions);ju.addFeatures(us,this.tileID.canonical,sp,at,this.tileTransform,this.brightness)}}this.status="done",qt(null,{buckets:Object.values(Xt).filter(hd=>!hd.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Kr,glyphAtlasImage:Hi.image,lineAtlas:Bs,imageAtlas:vl,brightness:us.brightness})};if(Ca){const vl=new Map,vo=c.fr(wn,vl),hd=c.fr(ca,vl),ju=new c.fs(vo,hd,vr,this.lut,vl);Ft.send("checkAtlasCache",{descriptor:ju,scope:this.scope},(sp,Nu)=>{let qh,ku;if(sp&&c.w(`[Worker] Error checking atlas cache: ${sp.message}`),Nu)qh=new c.ft(Nu.sourceHash),ku=Nu;else{const Cd=new c.fu(wn,ca,this.lut,vr);qh=Cd,ku=Cd}Zo(qh,ku)})}else Zo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Qa=c.fk(us.glyphDependencies,Qn=>Object.keys(Qn).map(Number));Object.keys(Qa).length?Ft.send("getGlyphs",{uid:this.uid,stacks:Qa},(Qn,vr)=>{mn||(mn=Qn,pn=vr,Fi())},void 0,!1,kn):pn={},Ka=new Map;const Hi=Array.from(us.iconDependencies.keys()).map(Qn=>c.I.parse(Qn));Hi.length?Ft.send("getImages",{images:Hi,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(Qn,vr)=>{if(!mn){mn=Qn,wn=new Map,Vi=this.updateImageMapAndGetImageTaskQueue(wn,vr.images,us.iconDependencies);for(const[Ca,Ji]of vr.versions.entries())Ka.set(Ca,Ji);Fi()}},void 0,!1,kn):(wn=new Map,Vi=new Map);const Gi=Array.from(us.patternDependencies.keys()).map(Qn=>c.I.parse(Qn));Gi.length?Ft.send("getImages",{images:Gi,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(Qn,vr)=>{if(!mn){mn=Qn,ca=new Map,so=this.updateImageMapAndGetImageTaskQueue(ca,vr.images,us.patternDependencies);for(const[Ca,Ji]of vr.versions.entries())Ka.set(Ca,Ji);Fi()}},void 0,!1,kn):(ca=new Map,so=new Map)}if(us.elevationFeatures&&us.elevationFeatures.length>0){const Qa=[];for(const Gi of Object.values(Xt))if(Gi instanceof c.fl){const Qn=Gi.getUnevaluatedPortalGraph();Qn&&Qa.push(Qn)}const Hi=c.fm.evaluate(Qa);for(const Gi of Object.values(Xt))if(Gi instanceof c.fl){const Qn=Re.layers[cs.decode(Gi.sourceLayerIndex)];Gi.setEvaluatedPortalGraph(Hi,Qn,this.tileID.canonical,us.availableImages,us.brightness)}}Fi()};cr.length>0?Promise.allSettled(cr).then(xr).catch(qt):xr()}updateParameters(Re){this.scaleFactor=Re.scaleFactor,this.showCollisionBoxes=Re.showCollisionBoxes,this.projection=Re.projection,this.brightness=Re.brightness,this.tileTransform=c.fc(Re.tileID.canonical,Re.projection),this.extraShadowCaster=Re.extraShadowCaster,this.lut=Re.lut,this.worldview=Re.worldview,this.indoor=Re.indoor}rasterizeIfNeeded(Re,Ke,at,Nt){Array.from(Ke.values()).some(Ft=>Ft.usvg)?this.rasterize(Re,Ke,at,Nt):Nt()}updateImageMapAndGetImageTaskQueue(Re,Ke,at){const Nt=new Map;for(const Ft of Ke.keys()){const qt=at.get(Ft)||[];for(const cs of qt){const it=cs.toString(),Xt=Ke.get(cs.id.toString());Xt.usvg?Nt.has(it)||(Nt.set(it,cs),Re.set(it,Object.assign({},Xt))):Re.set(it,Xt)}}return Nt}rasterize(Re,Ke,at,Nt){this.rasterizeTask=Re.send("rasterizeImages",{scope:this.scope,tasks:at},(Ft,qt)=>{if(!Ft)for(const[cs,it]of qt.entries()){const Xt=Object.assign(Ke.get(cs),{data:it});Ke.set(cs,Xt)}Nt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function F(Qt,Re,Ke,at,Nt,Ft){const qt=new c.ae(Re,{brightness:Ke,worldview:Nt,activeFloors:Ft});for(const cs of Qt)cs.recalculate(qt,at)}class O extends c.E{constructor({actor:Re,layerIndex:Ke,availableImages:at,availableModels:Nt,isSpriteLoaded:Ft,tileProvider:qt,brightness:cs,maxUniformBufferBindings:it,maxUniformBlockSizeDwords:Xt,disableSymbolUBO:Bs}){super(),this.actor=Re,this.layerIndex=Ke,this.availableImages=at,this.availableModels=Nt,this.loadVectorData=c.aO,this.tileProvider=qt,this.loading={},this.loaded={},this.deduped=new c.aN(Re.scheduler),this.isSpriteLoaded=Ft,this.scheduler=Re.scheduler,this.brightness=cs,this.maxUniformBufferBindings=it,this.maxUniformBlockSizeDwords=Xt,this.disableSymbolUBO=Bs}loadTileData(Re,Ke){if(!this.tileProvider)return this.loadVectorData(Re,Ke);const at=new AbortController,{z:Nt,x:Ft,y:qt}=Re.tileID.canonical;return this.tileProvider.loadTile({z:Nt,x:Ft,y:qt},{request:Re.request,signal:at.signal}).then(cs=>{if(at.signal.aborted)return;if(cs==null){const Xt=new Error("Tile not found");return Xt.status=404,Ke(Xt)}if(cs.data===null)return Ke(null,null);const it=new Map;cs.expires&&it.set("expires",cs.expires),cs.cacheControl&&it.set("cache-control",cs.cacheControl),Ke(null,{rawData:cs.data,responseHeaders:it})}).catch(cs=>{at.signal.aborted||Ke(cs instanceof Error?cs:new Error(String(cs)))}),()=>at.abort()}loadTile(Re,Ke){const at=Re.uid,Nt=Re&&Re.request,Ft=Nt&&Nt.collectResourceTiming,qt=this.loading[at]=new R(Re);qt.maxUniformBufferBindings=this.maxUniformBufferBindings,qt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,qt.disableSymbolUBO=this.disableSymbolUBO,qt.abort=this.loadTileData(Re,(cs,it)=>{const Xt=!this.loading[at];if(delete this.loading[at],qt.cancelRasterize(),Xt||cs||!it)return qt.status="done",Xt||(this.loaded[at]=qt),Ke(cs);const Bs=it.rawData,us={},cr=c.aP(it.responseHeaders);cr&&cr.expires&&(us.expires=cr.expires),cr&&cr.cacheControl&&(us.cacheControl=cr.cacheControl),qt.vectorTile=it.vectorTile||new c.fx(new c.a$(Bs));const Ar=()=>{qt.parse(qt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(xr,Kr)=>{if(xr||!Kr)return Ke(xr);const mn={};if(Ft){const pn=d(Nt);pn.length>0&&(mn.resourceTiming=JSON.parse(JSON.stringify(pn)))}Ke(null,Object.assign({rawTileData:Bs.slice(0),responseHeaders:it.responseHeaders},Kr,us,mn))})};this.isSpriteLoaded?Ar():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Ar,{type:"parseTile",renderSourceType:Re.renderSourceType,zoom:Re.tileZoom}):Ar()}),this.loaded=this.loaded||{},this.loaded[at]=qt})}reloadTile(Re,Ke){const at=this.loaded,Nt=Re.uid;if(at&&at[Nt]){const Ft=at[Nt];Ft.updateParameters(Re);const qt=(cs,it)=>{const Xt=Ft.reloadCallback;Xt&&(delete Ft.reloadCallback,Ft.parse(Ft.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Xt)),Ke(cs,it)};Ft.status==="parsing"?Ft.reloadCallback=qt:Ft.status==="done"&&(Ft.vectorTile?Ft.parse(Ft.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,qt):qt())}else Ke(null,void 0)}abortTile(Re,Ke){const at=Re.uid,Nt=this.loading[at];Nt&&(Nt.abort&&Nt.abort(),delete this.loading[at]),Ke()}removeTile(Re,Ke){const at=this.loaded,Nt=Re.uid;at&&at[Nt]&&delete at[Nt],Ke()}}class B{constructor(Re){this.loading={}}loadTile(Re,Ke){const at=Re.uid,{cancel:Nt}=c.b1(Re.request,(Ft,qt,cs)=>{const it=!this.loading[at];if(delete this.loading[at],it||Ft||!qt)return Ke(Ft);this.decodeTile(at,qt,Re.encoding).then(Xt=>{const{expires:Bs,cacheControl:us}=c.aP(cs);Ke(null,Object.assign(Xt,{expires:Bs,cacheControl:us}))}).catch(Xt=>Ke(Xt))});this.loading[at]={cancel:Nt}}async decodeTile(Re,Ke,at){const Nt=await createImageBitmap(new Blob([new Uint8Array(Ke)],{type:"image/png"})),Ft=1-(Nt.width-c.fy(Nt.width))/2,qt=Ft<1,cs=this.getImageData(Nt,Ft);return Nt.close(),{dem:new c.fz(Re,cs,at,qt),borderReady:qt}}reloadTile(Re,Ke){Ke(null,null)}abortTile(Re,Ke){const at=Re.uid,Nt=this.loading[at];Nt&&(Nt.cancel(),delete this.loading[at]),Ke()}removeTile(Re,Ke){Ke()}getImageData(Re,Ke){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(Re.width,Re.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=Re.width,this.offscreenCanvas.height=Re.height,this.offscreenCanvasContext.drawImage(Re,0,0,Re.width,Re.height);const at=this.offscreenCanvasContext.getImageData(-Ke,-Ke,Re.width+2*Ke,Re.height+2*Ke);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),at}}c.a_.setPbf(c.a$);class K{constructor(Re){this._mrt=new c.a_(Re.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=Re.uid,this.tileID=Re.tileID,this.source=Re.source}parse(Re,Ke){const at=this._mrt;this.status="parsing",this._entireBuffer=Re;try{at.parseHeader(Re),this._isHeaderLoaded=!0;const Nt=[];for(const Ft in at.layers){const qt=at.getLayer(Ft),cs=qt.getDataRange(qt.getBandList()),it=at.createDecodingTask(cs),Xt=Re.slice(cs.firstByte,cs.lastByte+1),Bs=c.a_.performDecoding(Xt,it).then(us=>it.complete(null,us)).catch(us=>it.complete(us,null));Nt.push(Bs)}Promise.allSettled(Nt).then(()=>Ke(null,at)).catch(Ft=>Ke(Ft))}catch(Nt){Ke(Nt)}}}class Z{constructor({actor:Re}){this.actor=Re,this.loading={},this.loaded={}}loadTile(Re,Ke){const at=Re.uid,Nt=Re.request,Ft=this.loading[at]=new K(Re),{cancel:qt}=c.b1(Nt,(cs,it,Xt)=>{const Bs=!this.loading[at];if(delete this.loading[at],Bs||cs||!it)return Ft.status="done",Bs||(this.loaded[at]=Ft),Ke(cs);Ft.parse(it,(us,cr)=>{if(us||!cr)return Ke(us);Ke(null,cr,Xt)}),this.loaded[at]=Ft});Ft.abort=qt}reloadTile(Re,Ke){Ke(null,void 0)}abortTile(Re,Ke){const at=Re.uid,Nt=this.loading[at];Nt&&(Nt.abort&&Nt.abort(),delete this.loading[at]),Ke()}removeTile(Re,Ke){const at=Re.uid;this.loaded[at]&&delete this.loaded[at],Ke()}decodeRasterArray(Re,Ke){c.a_.performDecoding(Re.buffer,Re.task).then(at=>Ke(null,at)).catch(at=>Ke(at))}}const Q=c.fA.prototype.toGeoJSON;class W{constructor(Re){this._feature=Re,this.extent=c.an,this.type=Re.type,this.properties=Re.tags,"id"in Re&&!isNaN(Re.id)&&(this.id=parseInt(Re.id,10))}loadGeometry(){if(this._feature.type===1){const Re=[];for(const Ke of this._feature.geometry)Re.push([new c.P(Ke[0],Ke[1])]);return Re}{const Re=[];for(const Ke of this._feature.geometry){const at=[];for(const Nt of Ke)at.push(new c.P(Nt[0],Nt[1]));Re.push(at)}return Re}}toGeoJSON(Re,Ke,at){return Q.call(this,Re,Ke,at)}}class te{constructor(Re,Ke){this.name=Re,this.extent=c.an,this.length=Ke.length,this._jsonFeatures=Ke}feature(Re){return new W(this._jsonFeatures[Re])}}class ne{constructor(Re){this.layers={},this.extent=c.an;for(const Ke of Object.keys(Re))this.layers[Ke]=new te(Ke,Re[Ke])}}const ae=64/4096;class ue{constructor(){this.features=new Map}clear(){this.features.clear()}load(Re=[],Ke){for(const at of Re){const Nt=at.id;if(Nt==null)continue;let Ft=this.features.get(Nt);Ft&&this.updateCache(Ft,Ke),at.geometry?(Ft=de(at),this.updateCache(Ft,Ke),this.features.set(Nt,Ft)):this.features.delete(Nt),this.updateCache(Ft,Ke)}}updateCache(Re,Ke){for(const{canonical:at,uid:Nt}of Object.values(Ke)){const{z:Ft,x:qt,y:cs}=at;me(Re,Math.pow(2,Ft),qt,cs)&&delete Ke[Nt]}}getTile(Re,Ke,at){const Nt=Math.pow(2,Re),Ft=[];for(const qt of this.features.values())me(qt,Nt,Ke,at)&&Ft.push(Ee(qt,Nt,Ke,at));return{features:Ft}}getFeatures(){return[...this.features.values()]}}function me({minX:Qt,minY:Re,maxX:Ke,maxY:at},Nt,Ft,qt){return Qt<(Ft+1+ae)/Nt&&Re<(qt+1+ae)/Nt&&Ke>(Ft-ae)/Nt&&at>(qt-ae)/Nt}function de(Qt){const{id:Re,geometry:Ke,properties:at}=Qt;if(!Ke)return;if(Ke.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Nt,coordinates:Ft}=Ke,qt={id:Re,type:1,geometry:[],tags:at,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},cs=qt.geometry;if(Nt==="Point")fe(Ft,cs,qt);else if(Nt==="MultiPoint")for(const it of Ft)fe(it,cs,qt);else if(Nt==="LineString")qt.type=2,je(Ft,cs,qt);else if(Nt==="MultiLineString")qt.type=2,xe(Ft,cs,qt);else if(Nt==="Polygon")qt.type=3,xe(Ft,cs,qt,!0);else{if(Nt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");qt.type=3;for(const it of Ft)xe(it,cs,qt,!0)}return qt}function fe([Qt,Re],Ke,at){const Nt=c.aH(Qt);let Ft=c.aL(Re);Ft=Ft<0?0:Ft>1?1:Ft,Ke.push(Nt,Ft),at.minX=Math.min(at.minX,Nt),at.minY=Math.min(at.minY,Ft),at.maxX=Math.max(at.maxX,Nt),at.maxY=Math.max(at.maxY,Ft)}function je(Qt,Re,Ke,at=!1,Nt=!1){const Ft=[];for(const qt of Qt)fe(qt,Ft,Ke);Re.push(Ft),at&&function(qt,cs){let it=0;for(let Xt=0,Bs=qt.length,us=Bs-2;Xt0===cs)for(let Xt=0,Bs=qt.length;Xt=qt&&us>=qt||(Xt>=qt?(Bs+=Math.round(xr*((qt-Xt)/Ar)),Xt=qt):us>=qt&&(cr=Bs+Math.round(xr*((qt-Xt)/Ar)),us=qt),Bs>=qt&&cr>=qt||(Bs>=qt?(Xt+=Math.round(Ar*((qt-Bs)/xr)),Bs=qt):cr>=qt&&(us=Xt+Math.round(Ar*((qt-Bs)/xr)),cr=qt),cs&&Xt===cs[cs.length-1][0]&&Bs===cs[cs.length-1][1]||(cs=[[Xt,Bs]],Nt.push(cs)),cs.push([us,cr])))))}}function Oe(Qt,Re,Ke,at,Nt){const Ft=(Ke-ae)/Re,qt=(at-ae)/Re,cs=(Ke+1+ae)/Re,it=(at+1+ae)/Re;function Xt(cr,Ar){let xr=0;return crcs&&(xr|=2),Arit&&(xr|=8),xr}let Bs=[];for(let cr=1;cr<=8;cr*=2){let Ar=Qt[Qt.length-2],xr=Qt[Qt.length-1],Kr=!(Xt(Ar,xr)&cr);for(let mn=0;mn>31}function ve(Qt,Re){const{geometry:Ke,type:at}=Qt;let Nt=0,Ft=0;if(at===1){Re.writeVarint(Le(1,Ke.length));for(const qt of Ke){const cs=qt[0]-Nt,it=qt[1]-Ft;Re.writeVarint($e(cs)),Re.writeVarint($e(it)),Nt+=cs,Ft+=it}}else for(const qt of Ke){if(qt.length===0)continue;Re.writeVarint(Le(1,1));const cs=qt.length-(at===3?1:0);for(let it=0;itQt},nt=Math.fround||(Se=new Float32Array(1),Qt=>(Se[0]=+Qt,Se[0]));var Se;class Ge{constructor(Re){this.options=Object.assign(Object.create(we),Re),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(Re){const{log:Ke,minZoom:at,maxZoom:Nt}=this.options;Ke&&console.time("total time");const Ft=`prepare ${Re.length} points`;Ke&&console.time(Ft),this.points=Re;const qt=[];for(let it=0;it=at;it--){const Xt=+Date.now();cs=this.trees[it]=this._createTree(this._cluster(cs,it)),Ke&&console.log("z%d: %d clusters in %dms",it,cs.numItems,+Date.now()-Xt)}return Ke&&console.timeEnd("total time"),this}getClusters(Re,Ke){let at=((Re[0]+180)%360+360)%360-180;const Nt=Math.max(-90,Math.min(90,Re[1]));let Ft=Re[2]===180?180:((Re[2]+180)%360+360)%360-180;const qt=Math.max(-90,Math.min(90,Re[3]));if(Re[2]-Re[0]>=360)at=-180,Ft=180;else if(at>Ft){const us=this.getClusters([at,Nt,180,qt],Ke),cr=this.getClusters([-180,Nt,Ft,qt],Ke);return us.concat(cr)}const cs=this.trees[this._limitZoom(Ke)],it=cs.range(qe(at),et(qt),qe(Ft),et(Nt)),Xt=cs.data,Bs=[];for(const us of it){const cr=this.stride*us;Bs.push(Xt[cr+5]>1?We(Xt,cr,this.clusterProps):this.points[Xt[cr+3]])}return Bs}getChildren(Re){const Ke=this._getOriginId(Re),at=this._getOriginZoom(Re),Nt="No cluster with the specified id.",Ft=this.trees[at];if(!Ft)throw new Error(Nt);const qt=Ft.data;if(Ke*this.stride>=qt.length)throw new Error(Nt);const cs=this.options.radius/(this.options.extent*Math.pow(2,at-1)),it=Ft.within(qt[Ke*this.stride],qt[Ke*this.stride+1],cs),Xt=[];for(const Bs of it){const us=Bs*this.stride;qt[us+4]===Re&&Xt.push(qt[us+5]>1?We(qt,us,this.clusterProps):this.points[qt[us+3]])}if(Xt.length===0)throw new Error(Nt);return Xt}getLeaves(Re,Ke,at){const Nt=[];return this._appendLeaves(Nt,Re,Ke=Ke||10,at=at||0,0),Nt}getTile(Re,Ke,at){const Nt=this.trees[this._limitZoom(Re)],Ft=Math.pow(2,Re),{extent:qt,radius:cs}=this.options,it=cs/qt,Xt=(at-it)/Ft,Bs=(at+1+it)/Ft,us={features:[]};return this._addTileFeatures(Nt.range((Ke-it)/Ft,Xt,(Ke+1+it)/Ft,Bs),Nt.data,Ke,at,Ft,us),Ke===0&&this._addTileFeatures(Nt.range(1-it/Ft,Xt,1,Bs),Nt.data,Ft,at,Ft,us),Ke===Ft-1&&this._addTileFeatures(Nt.range(0,Xt,it/Ft,Bs),Nt.data,-1,at,Ft,us),us.features.length?us:null}getClusterExpansionZoom(Re){let Ke=this._getOriginZoom(Re)-1;for(;Ke<=this.options.maxZoom;){const at=this.getChildren(Re);if(Ke++,at.length!==1)break;Re=at[0].properties.cluster_id}return Ke}_appendLeaves(Re,Ke,at,Nt,Ft){const qt=this.getChildren(Ke);for(const cs of qt){const it=cs.properties;if(it&&it.cluster?Ft+it.point_count<=Nt?Ft+=it.point_count:Ft=this._appendLeaves(Re,it.cluster_id,at,Nt,Ft):Ft1;let Bs,us,cr;if(Xt)Bs=Ce(Ke,it,this.clusterProps),us=Ke[it],cr=Ke[it+1];else{const Kr=this.points[Ke[it+3]];Bs=Kr.properties;const[mn,pn]=Kr.geometry.coordinates;us=qe(mn),cr=et(pn)}const Ar={type:1,geometry:[[Math.round(this.options.extent*(us*Ft-at)),Math.round(this.options.extent*(cr*Ft-Nt))]],tags:Bs};let xr;xr=Xt||this.options.generateId?Ke[it+3]:this.points[Ke[it+3]].id,xr!==void 0&&(Ar.id=xr),qt.features.push(Ar)}}_limitZoom(Re){return Math.max(this.options.minZoom,Math.min(Math.floor(+Re),this.options.maxZoom+1))}_cluster(Re,Ke){const{radius:at,extent:Nt,reduce:Ft,minPoints:qt}=this.options,cs=at/(Nt*Math.pow(2,Ke)),it=Re.data,Xt=[],Bs=this.stride;for(let us=0;usKe&&(mn+=it[wn+5])}if(mn>Kr&&mn>=qt){let pn,wn=cr*Kr,ca=Ar*Kr,Vi=-1;const so=(us/Bs<<5)+(Ke+1)+this.points.length;for(const Ka of xr){const kn=Ka*Bs;if(it[kn+2]<=Ke)continue;it[kn+2]=Ke;const Fi=it[kn+5];wn+=it[kn]*Fi,ca+=it[kn+1]*Fi,it[kn+4]=so,Ft&&(pn||(pn=this._map(it,us,!0),Vi=this.clusterProps.length,this.clusterProps.push(pn)),Ft(pn,this._map(it,kn)))}it[us+4]=so,Xt.push(wn/mn,ca/mn,1/0,so,-1,mn),Ft&&Xt.push(Vi)}else{for(let pn=0;pn1)for(const pn of xr){const wn=pn*Bs;if(!(it[wn+2]<=Ke)){it[wn+2]=Ke;for(let ca=0;ca>5}_getOriginZoom(Re){return(Re-this.points.length)%32}_map(Re,Ke,at){if(Re[Ke+5]>1){const qt=this.clusterProps[Re[Ke+6]];return at?Object.assign({},qt):qt}const Nt=this.points[Re[Ke+3]].properties,Ft=this.options.map(Nt);return at&&Ft===Nt?Object.assign({},Ft):Ft}}function We(Qt,Re,Ke){return{type:"Feature",id:Qt[Re+3],properties:Ce(Qt,Re,Ke),geometry:{type:"Point",coordinates:[(at=Qt[Re],360*(at-.5)),Ze(Qt[Re+1])]}};var at}function Ce(Qt,Re,Ke){const at=Qt[Re+5],Nt=at>=1e4?`${Math.round(at/1e3)}k`:at>=1e3?Math.round(at/100)/10+"k":at,Ft=Qt[Re+6],qt=Ft===-1?{}:Object.assign({},Ke[Ft]);return Object.assign(qt,{cluster:!0,cluster_id:Qt[Re+3],point_count:at,point_count_abbreviated:Nt})}function qe(Qt){return Qt/360+.5}function et(Qt){const Re=Math.sin(Qt*Math.PI/180),Ke=.5-.25*Math.log((1+Re)/(1-Re))/Math.PI;return Ke<0?0:Ke>1?1:Ke}function Ze(Qt){const Re=(180-360*Qt)*Math.PI/180;return 360*Math.atan(Math.exp(Re))/Math.PI-90}function rt(Qt,Re,Ke,at){let Nt=at;const Ft=Re+(Ke-Re>>1);let qt,cs=Ke-Re;const it=Qt[Re],Xt=Qt[Re+1],Bs=Qt[Ke],us=Qt[Ke+1];for(let cr=Re+3;crNt)qt=cr,Nt=Ar;else if(Ar===Nt){const xr=Math.abs(cr-Ft);xrat&&(qt-Re>3&&rt(Qt,Re,qt,at),Qt[qt+2]=Nt,Ke-qt>3&&rt(Qt,qt,Ke,at))}function ct(Qt,Re,Ke,at,Nt,Ft){let qt=Nt-Ke,cs=Ft-at;if(qt!==0||cs!==0){const it=((Qt-Ke)*qt+(Re-at)*cs)/(qt*qt+cs*cs);it>1?(Ke=Nt,at=Ft):it>0&&(Ke+=qt*it,at+=cs*it)}return qt=Qt-Ke,cs=Re-at,qt*qt+cs*cs}function vt(Qt,Re,Ke,at){const Nt={id:Qt??null,type:Re,geometry:Ke,tags:at,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(Re==="Point"||Re==="MultiPoint"||Re==="LineString")kt(Nt,Ke);else if(Re==="Polygon")kt(Nt,Ke[0]);else if(Re==="MultiLineString")for(const Ft of Ke)kt(Nt,Ft);else if(Re==="MultiPolygon")for(const Ft of Ke)kt(Nt,Ft[0]);return Nt}function kt(Qt,Re){for(let Ke=0;Ke0&&(qt+=at?(Nt*Bs-Xt*Ft)/2:Math.sqrt(Math.pow(Xt-Nt,2)+Math.pow(Bs-Ft,2))),Nt=Xt,Ft=Bs}const cs=Re.length-3;Re[2]=1,rt(Re,0,cs,Ke),Re[cs+2]=1,Re.size=Math.abs(qt),Re.start=0,Re.end=Re.size}function zs(Qt,Re,Ke,at){for(let Nt=0;Nt1?1:Ke}function gt(Qt,Re,Ke,at,Nt,Ft,qt,cs){if(at/=Re,Ft>=(Ke/=Re)&&qt=at)return null;const it=[];for(const Xt of Qt){const Bs=Xt.geometry;let us=Xt.type;const cr=Nt===0?Xt.minX:Xt.minY,Ar=Nt===0?Xt.maxX:Xt.maxY;if(cr>=Ke&&Ar=at)continue;let xr=[];if(us==="Point"||us==="MultiPoint")Ut(Bs,xr,Ke,at,Nt);else if(us==="LineString")ht(Bs,xr,Ke,at,Nt,!1,cs.lineMetrics);else if(us==="MultiLineString")Ms(Bs,xr,Ke,at,Nt,!1);else if(us==="Polygon")Ms(Bs,xr,Ke,at,Nt,!0);else if(us==="MultiPolygon")for(const Kr of Bs){const mn=[];Ms(Kr,mn,Ke,at,Nt,!0),mn.length&&xr.push(mn)}if(xr.length){if(cs.lineMetrics&&us==="LineString"){for(const Kr of xr)it.push(vt(Xt.id,us,Kr,Xt.tags));continue}us!=="LineString"&&us!=="MultiLineString"||(xr.length===1?(us="LineString",xr=xr[0]):us="MultiLineString"),us!=="Point"&&us!=="MultiPoint"||(us=xr.length===3?"Point":"MultiPoint"),it.push(vt(Xt.id,us,xr,Xt.tags))}}return it.length?it:null}function Ut(Qt,Re,Ke,at,Nt){for(let Ft=0;Ft=Ke&&qt<=at&&ts(Re,Qt[Ft],Qt[Ft+1],Qt[Ft+2])}}function ht(Qt,Re,Ke,at,Nt,Ft,qt){let cs=Jt(Qt);const it=Nt===0?Xs:js;let Xt,Bs,us=Qt.start;for(let mn=0;mnKe&&(Bs=it(cs,pn,wn,Vi,so,Ke),qt&&(cs.start=us+Xt*Bs)):Ka>at?kn=Ke&&(Bs=it(cs,pn,wn,Vi,so,Ke),Fi=!0),kn>at&&Ka<=at&&(Bs=it(cs,pn,wn,Vi,so,at),Fi=!0),!Ft&&Fi&&(qt&&(cs.end=us+Xt*Bs),Re.push(cs),cs=Jt(Qt)),qt&&(us+=Xt)}let cr=Qt.length-3;const Ar=Qt[cr],xr=Qt[cr+1],Kr=Nt===0?Ar:xr;Kr>=Ke&&Kr<=at&&ts(cs,Ar,xr,Qt[cr+2]),cr=cs.length-3,Ft&&cr>=3&&(cs[cr]!==cs[0]||cs[cr+1]!==cs[1])&&ts(cs,cs[0],cs[1],cs[2]),cs.length&&Re.push(cs)}function Jt(Qt){const Re=[];return Re.size=Qt.size,Re.start=Qt.start,Re.end=Qt.end,Re}function Ms(Qt,Re,Ke,at,Nt,Ft){for(const qt of Qt)ht(qt,Re,Ke,at,Nt,Ft,!1)}function ts(Qt,Re,Ke,at){Qt.push(Re,Ke,at)}function Xs(Qt,Re,Ke,at,Nt,Ft){const qt=(Ft-Re)/(at-Re);return ts(Qt,Ft,Ke+(Nt-Ke)*qt,1),qt}function js(Qt,Re,Ke,at,Nt,Ft){const qt=(Ft-Ke)/(Nt-Ke);return ts(Qt,Re+(at-Re)*qt,Ft,1),qt}function $s(Qt,Re){const Ke=[];for(let at=0;at0&&Re.size<(Nt?qt:at))return void(Ke.numPoints+=Re.length/3);const cs=[];for(let it=0;itqt)&&(Ke.numSimplified++,cs.push(Re[it],Re[it+1])),Ke.numPoints++;Nt&&function(it,Xt){let Bs=0;for(let us=0,cr=it.length,Ar=cr-2;us0===Xt)for(let us=0,cr=it.length;us24)throw new Error("maxZoom should be in the 0-24 range");if(Ke.promoteId&&Ke.generateId)throw new Error("promoteId and generateId cannot be used together.");let Nt=function(Ft,qt){const cs=[];if(Ft.type==="FeatureCollection")for(let it=0;it1&&console.time("creation"),Ar=this.tiles[cr]=Sr(Re,Ke,at,Nt,Xt),this.tileCoords.push({z:Ke,x:at,y:Nt}),Bs)){Bs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",Ke,at,Nt,Ar.numFeatures,Ar.numPoints,Ar.numSimplified),console.timeEnd("creation"));const Fi=`z${Ke}`;this.stats[Fi]=(this.stats[Fi]||0)+1,this.total++}if(Ar.source=Re,Ft==null){if(Ke===Xt.indexMaxZoom||Ar.numPoints<=Xt.indexMaxPoints)continue}else{if(Ke===Xt.maxZoom||Ke===Ft)continue;if(Ft!=null){const Fi=Ft-Ke;if(at!==qt>>Fi||Nt!==cs>>Fi)continue}}if(Ar.source=null,Re.length===0)continue;Bs>1&&console.time("clipping");const xr=.5*Xt.buffer/Xt.extent,Kr=.5-xr,mn=.5+xr,pn=1+xr;let wn=null,ca=null,Vi=null,so=null,Ka=gt(Re,us,at-xr,at+mn,0,Ar.minX,Ar.maxX,Xt),kn=gt(Re,us,at+Kr,at+pn,0,Ar.minX,Ar.maxX,Xt);Re=null,Ka&&(wn=gt(Ka,us,Nt-xr,Nt+mn,1,Ar.minY,Ar.maxY,Xt),ca=gt(Ka,us,Nt+Kr,Nt+pn,1,Ar.minY,Ar.maxY,Xt),Ka=null),kn&&(Vi=gt(kn,us,Nt-xr,Nt+mn,1,Ar.minY,Ar.maxY,Xt),so=gt(kn,us,Nt+Kr,Nt+pn,1,Ar.minY,Ar.maxY,Xt),kn=null),Bs>1&&console.timeEnd("clipping"),it.push(wn||[],Ke+1,2*at,2*Nt),it.push(ca||[],Ke+1,2*at,2*Nt+1),it.push(Vi||[],Ke+1,2*at+1,2*Nt),it.push(so||[],Ke+1,2*at+1,2*Nt+1)}}getTile(Re,Ke,at){Re=+Re,Ke=+Ke,at=+at;const Nt=this.options,{extent:Ft,debug:qt}=Nt;if(Re<0||Re>24)return null;const cs=1<1&&console.log("drilling down to z%d-%d-%d",Re,Ke,at);let Xt,Bs=Re,us=Ke,cr=at;for(;!Xt&&Bs>0;)Bs--,us>>=1,cr>>=1,Xt=this.tiles[gs(Bs,us,cr)];return Xt&&Xt.source?(qt>1&&(console.log("found parent tile z%d-%d-%d",Bs,us,cr),console.time("drilling down")),this.splitTile(Xt.source,Bs,us,cr,Re,Ke,at),qt>1&&console.timeEnd("drilling down"),this.tiles[it]?or(this.tiles[it],Ft):null):null}}function gs(Qt,Re,Ke){return 32*((1<Xt.tags&&"3d_elevation_id"in Xt.tags&&"source"in Xt.tags&&Xt.tags.source==="elevation",Ft=at.features.filter(Xt=>Nt(Xt));let qt={_geojsonTileLayer:at.features};Ft.length>0&&(qt={_geojsonTileLayer:at.features.filter(Xt=>!Nt(Xt)),hd_road_elevation:Ft});const cs=new ne(qt),it=function(Xt){const Bs=new c.a$;for(const us of Object.keys(Xt))Bs.writeMessage(3,Ie,{name:us,features:Xt[us]});return Bs.finish()}(qt).buffer;Re(null,{vectorTile:cs,rawData:it})}class In extends O{constructor(Re){super(Re),this.loadVectorData=mi,this._dynamicIndex=new ue}loadData(Re,Ke){const at=Re&&Re.request,Nt=at&&at.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(Re,(Ft,qt)=>{if(Ft||!qt)return Ke(Ft);if(typeof qt!="object")return Ke(new Error(`Input data given to '${Re.source}' is not a valid GeoJSON object.`));{try{if(Re.filter){const it=c.X(Re.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(it.result==="error")throw new Error(it.value.map(Xt=>`${Xt.key}: ${Xt.message}`).join(", "));qt.features=qt.features.filter(Xt=>it.value.evaluate({zoom:0},Xt))}Re.dynamic?(qt.type==="Feature"&&(qt={type:"FeatureCollection",features:[qt]}),Re.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(qt.features,this.loaded),Re.cluster&&(qt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=Re.cluster?new Ge(function({superclusterOptions:it,clusterProperties:Xt}){if(!Xt||!it)return it;const Bs={},us={},cr={accumulated:null,zoom:0},Ar={properties:null},xr=Object.keys(Xt);for(const Kr of xr){const[mn,pn]=Xt[Kr],wn=c.X(pn),ca=c.X(typeof mn=="string"?[mn,["accumulated"],["get",Kr]]:mn);Bs[Kr]=wn.value,us[Kr]=ca.value}return it.map=Kr=>{Ar.properties=Kr;const mn={};for(const pn of xr)mn[pn]=Bs[pn].evaluate(cr,Ar);return mn},it.reduce=(Kr,mn)=>{Ar.properties=mn;for(const pn of xr)cr.accumulated=Kr[pn],Kr[pn]=us[pn].evaluate(cr,Ar)},it}(Re)).load(qt.features):Re.dynamic?this._dynamicIndex:function(it,Xt){return new sa(it,Xt)}(qt,Re.geojsonVtOptions)}catch(it){return Ke(it)}const cs={};if(Nt){const it=d(at);it&&(cs.resourceTiming={},cs.resourceTiming[Re.source]=JSON.parse(JSON.stringify(it)))}Ke(null,cs)}})}reloadTile(Re,Ke){const at=this.loaded;return at&&at[Re.uid]?Re.partial?Ke(null,void 0):super.reloadTile(Re,Ke):this.loadTile(Re,Ke)}loadGeoJSON(Re,Ke){if(Re.request)c.m(Re.request,Ke);else{if(typeof Re.data!="string")return Ke(new Error(`Input data given to '${Re.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return Ke(null,JSON.parse(Re.data))}catch{return Ke(new Error(`Input data given to '${Re.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(Re,Ke){try{Ke(null,this._geoJSONIndex.getClusterExpansionZoom(Re.clusterId))}catch(at){Ke(at)}}getClusterChildren(Re,Ke){try{Ke(null,this._geoJSONIndex.getChildren(Re.clusterId))}catch(at){Ke(at)}}getClusterLeaves(Re,Ke){try{Ke(null,this._geoJSONIndex.getLeaves(Re.clusterId,Re.limit,Re.offset))}catch(at){Ke(at)}}}class Br{constructor(Re,Ke,at){this.tileID=new c.aR(Re.tileID.overscaledZ,Re.tileID.wrap,Re.tileID.canonical.z,Re.tileID.canonical.x,Re.tileID.canonical.y),this.tileZoom=Re.tileZoom,this.uid=Re.uid,this.zoom=Re.zoom,this.canonical=Re.tileID.canonical,this.pixelRatio=Re.pixelRatio,this.tileSize=Re.tileSize,this.source=Re.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=Re.projection,this.brightness=Ke,this.worldview=at}parse(Re,Ke,at,Nt){this.status="parsing";const Ft=new c.aR(at.tileID.overscaledZ,at.tileID.wrap,at.tileID.canonical.z,at.tileID.canonical.x,at.tileID.canonical.y),qt=[],cs=Ke.familiesBySource[at.source],it=new c.ff(Ft,at.promoteId);it.bucketLayerIDs=[],it.is3DTile=!0,c.fB(Re).then(Xt=>{const Bs=Xt.json.extensionsUsed&&Xt.json.extensionsUsed.includes("MAPBOX_mesh_features")||Xt.json.asset.extras&&Xt.json.asset.extras.MAPBOX_mesh_features,us=Xt.json.extensionsUsed&&Xt.json.extensionsUsed.includes("EXT_meshopt_compression"),cr=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Ar in cs)for(const xr of cs[Ar]){const Kr=xr[0];it.bucketLayerIDs.push(xr.map(wn=>c.F(wn.id,wn.scope))),Kr.recalculate(cr,[]);const mn=c.fC(Xt,1/c.cS(at.tileID.canonical)),pn=new c.fD(xr,mn,Ft,Bs,us,this.brightness,it,this.worldview);Bs||(pn.needsUpload=!0),qt.push(pn),pn.evaluate(Kr)}this.status="done",Nt(null,{buckets:qt,featureIndex:it,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Xt=>Nt(new Error(Xt.message)))}}class ps{constructor({actor:Re,layerIndex:Ke,availableImages:at,availableModels:Nt,brightness:Ft,worldview:qt}){this.actor=Re,this.layerIndex=Ke,this.availableImages=at,this.availableModels=Nt,this.brightness=Ft,this.loading={},this.loaded={},this.worldview=qt}loadTile(Re,Ke){const at=Re.uid,Nt=this.loading[at]=new Br(Re,this.brightness,this.worldview);c.b1(Re.request,(Ft,qt)=>{const cs=!this.loading[at];return delete this.loading[at],cs||Ft?(Nt.status="done",cs||(this.loaded[at]=Nt),Ke(Ft)):qt&&qt.byteLength!==0?void Nt.parse(qt,this.layerIndex,Re,(it,Xt)=>{Nt.status="done",this.loaded=this.loaded||{},this.loaded[at]=Nt,it||!Xt?Ke(it):Ke(null,Xt)}):(Nt.status="done",this.loaded[at]=Nt,Ke())})}reloadTile(Re,Ke){const at=this.loaded,Nt=Re.uid;if(at&&at[Nt]){const Ft=at[Nt];Ft.projection=Re.projection,Ft.brightness=Re.brightness;const qt=(cs,it)=>{Ft.reloadCallback&&(delete Ft.reloadCallback,this.loadTile(Re,Ke)),Ke(cs,it)};Ft.status==="parsing"?Ft.reloadCallback=qt:Ft.status==="done"&&this.loadTile(Re,Ke)}}abortTile(Re,Ke){const at=Re.uid;this.loading[at]&&delete this.loading[at],Ke()}removeTile(Re,Ke){const at=this.loaded,Nt=Re.uid;at&&at[Nt]&&delete at[Nt],Ke()}}const Or=new Map,Qr=new Map;class Tn{constructor(Re){this.self=Re,this.actor=new c.A(Re,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:O,geojson:In,"raster-dem":B,"raster-array":Z,"batched-model":ps},this.workerSources={},this.self.registerWorkerSource=(Ke,at)=>{if(this.workerSourceTypes[Ke])throw new Error(`Worker source with name "${Ke}" already registered.`);this.workerSourceTypes[Ke]=at},this.self.registerRTLTextPlugin=Ke=>{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=Ke.applyArabicShaping,c.fF.processBidirectionalText=Ke.processBidirectionalText,c.fF.processStyledBidirectionalText=Ke.processStyledBidirectionalText;for(const at of this.rtlPluginParsingListeners)at(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(Re,Ke,at){delete this.layerIndexes[Re],delete this.availableImages[Re],delete this.availableModels[Re],delete this.workerSources[Re],at()}checkIfReady(Re,Ke,at){at()}setReferrer(Re,Ke){this.referrer=Ke}spriteLoaded(Re,Ke){this.isSpriteLoaded[Re]||(this.isSpriteLoaded[Re]={});const{scope:at,isLoaded:Nt}=Ke;if(this.isSpriteLoaded[Re][at]=Nt,this.workerSources[Re]&&this.workerSources[Re][at])for(const Ft in this.workerSources[Re][at]){const qt=this.workerSources[Re][at][Ft];for(const cs in qt){const it=qt[cs];it instanceof O&&(it.isSpriteLoaded=Nt,it.fire(new c.C("isSpriteLoaded")))}}}setImages(Re,Ke,at){this.availableImages[Re]||(this.availableImages[Re]={});const{scope:Nt,images:Ft}=Ke;if(this.availableImages[Re][Nt]=Ft,this.workerSources[Re]&&this.workerSources[Re][Nt]){for(const qt in this.workerSources[Re][Nt]){const cs=this.workerSources[Re][Nt][qt];for(const it in cs)cs[it].availableImages=Ft}at()}else at()}setModels(Re,{scope:Ke,models:at},Nt){if(this.availableModels[Re]||(this.availableModels[Re]={}),this.availableModels[Re][Ke]=at,this.workerSources[Re]&&this.workerSources[Re][Ke]){for(const Ft in this.workerSources[Re][Ke]){const qt=this.workerSources[Re][Ke][Ft];for(const cs in qt)qt[cs].availableModels=at}Nt()}else Nt()}setProjection(Re,Ke){this.projections[Re]=c.c0(Ke)}setBrightness(Re,Ke,at){this.brightness=Ke,at()}setContextParams(Re,Ke,at){this.maxUniformBufferBindings=Ke.maxBindingPoints,this.maxUniformBlockSizeDwords=Ke.maxUniformBlockSizeDwords,this.disableSymbolUBO=Ke.disableSymbolUBO,at()}setWorldview(Re,Ke,at){this.worldview=Ke,at()}setLayers(Re,Ke,at){this.getLayerIndex(Re,Ke.scope).replace(Ke.layers,Ke.options),at()}updateLayers(Re,Ke,at){this.getLayerIndex(Re,Ke.scope).update(Ke.layers,Ke.removedIds,Ke.options),at()}loadTile(Re,Ke,at){Ke.projection=this.projections[Re]||this.defaultProjection,this.getWorkerSource(Re,Ke).loadTile(Ke,at)}decodeRasterArray(Re,Ke,at){this.getWorkerSource(Re,Ke).decodeRasterArray(Ke,at)}reloadTile(Re,Ke,at){Ke.projection=this.projections[Re]||this.defaultProjection,this.getWorkerSource(Re,Ke).reloadTile(Ke,at)}abortTile(Re,Ke,at){this.getWorkerSource(Re,Ke).abortTile(Ke,at)}removeTile(Re,Ke,at){this.getWorkerSource(Re,Ke).removeTile(Ke,at)}removeSource(Re,Ke,at){if(!(this.workerSources[Re]&&this.workerSources[Re][Ke.scope]&&this.workerSources[Re][Ke.scope][Ke.type]&&this.workerSources[Re][Ke.scope][Ke.type][Ke.source]))return;const Nt=this.workerSources[Re][Ke.scope][Ke.type][Ke.source];delete this.workerSources[Re][Ke.scope][Ke.type][Ke.source],Nt.removeSource!==void 0?Nt.removeSource(Ke,at):at()}loadTileProvider(Re,Ke,at){(async function(Nt,Ft){const qt=Qr.get(Nt);if(qt)return qt;const cs=Or.get(Nt);if(cs!==void 0)return cs;const it=import(Ft).then(Xt=>{const Bs=Xt.default;if(typeof Bs!="function")throw new Error(`TileProvider "${Nt}" module must default-export a class`);if(typeof Bs.prototype.loadTile!="function")throw new Error(`TileProvider "${Nt}" class must have a loadTile method`);return Qr.set(Nt,Bs),Bs}).finally(()=>{Or.delete(Nt)});return Or.set(Nt,it),it})(Ke.name,Ke.url).then(Nt=>{const Ft=new Nt(Ke.options);return this.getWorkerSource(Re,{type:Ke.type,source:Ke.source,scope:Ke.scope},Ft),Ft.load&&Ke.request?Ft.load({request:Ke.request}):null}).then(Nt=>at(null,Nt)).catch(Nt=>at(Nt instanceof Error?Nt:new Error(typeof Nt=="string"?Nt:"Unknown error")))}loadWorkerSource(Re,Ke,at){try{this.self.importScripts(Ke.url),at()}catch(Nt){at(Nt)}}syncRTLPluginState(Re,Ke,at){if(c.fF.isParsed())at(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(at);else try{c.fF.setState(Ke);const Nt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||Nt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(Nt),c.fF.isParsed()?at(null,!0):this.rtlPluginParsingListeners.push(at))}catch(Nt){at(Nt)}}setConfig(Re,Ke){Object.assign(c.g,Ke)}getAvailableImages(Re,Ke){this.availableImages[Re]||(this.availableImages[Re]={});let at=this.availableImages[Re][Ke];return at||(at=[]),at}getAvailableModels(Re,Ke){this.availableModels[Re]||(this.availableModels[Re]={});let at=this.availableModels[Re][Ke];return at||(at={}),at}getLayerIndex(Re,Ke){this.layerIndexes[Re]||(this.layerIndexes[Re]={});let at=this.layerIndexes[Re][Ke];return at||(at=this.layerIndexes[Re][Ke]=new x,at.scope=Ke),at}getWorkerSource(Re,Ke,at){const{type:Nt,source:Ft,scope:qt}=Ke,cs=this.workerSources;if(cs[Re]||(cs[Re]={}),cs[Re][qt]||(cs[Re][qt]={}),cs[Re][qt][Nt]||(cs[Re][qt][Nt]={}),this.isSpriteLoaded[Re]||(this.isSpriteLoaded[Re]={}),!cs[Re][qt][Nt][Ft]){const it={send:(Bs,us,cr,Ar,xr,Kr)=>this.actor.send(Bs,us,cr,Re,xr,Kr),scheduler:this.actor.scheduler},Xt=this.workerSourceTypes[Nt];if(!Xt)throw new Error(`Unknown worker source type "${Nt}".`);cs[Re][qt][Nt][Ft]=new Xt({actor:it,layerIndex:this.getLayerIndex(Re,qt),availableImages:this.getAvailableImages(Re,qt),availableModels:this.getAvailableModels(Re,qt),isSpriteLoaded:this.isSpriteLoaded[Re][qt],tileProvider:at,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return cs[Re][qt][Nt][Ft]}rasterizeImagesWorker(Re,Ke,at){const Nt=new Map;for(const[Ft,{image:qt,imageVariant:cs}]of Ke.tasks.entries()){const it=this.imageRasterizer.rasterize(cs,qt,Ke.scope,Re);Nt.set(Ft,it)}at(void 0,Nt)}removeRasterizedImages(Re,Ke,at){this.imageRasterizer.removeImagesFromCacheByIds(Ke.imageIds,Ke.scope,Re),at()}enforceCacheSizeLimit(Re,Ke){c.fH(Ke)}getWorkerPerformanceMetrics(Re,Ke,at){at(void 0,void 0)}}return c.fE(self)&&(self.worker=new Tn(self)),Tn}),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,S){performance.measure(M,g,S)}};function m(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 f,x={},y=function(){if(f)return x;function M(P){return!g(P)}function g(P){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var H,G,ee=new Blob([""],{type:"text/javascript"}),ie=URL.createObjectURL(ee);try{G=new Worker(ie),H=!0}catch{H=!1}return G&&G.terminate(),URL.revokeObjectURL(ie),H}()?function(){var H=document.createElement("canvas");H.width=H.height=1;var G=H.getContext("2d");if(!G)return!1;var ee=G.getImageData(0,0,1,1);return ee&&ee.width===H.width}()?(S[z=P&&P.failIfMajorPerformanceCaveat]===void 0&&(S[z]=function(H){var G,ee=function(ie){var pe=document.createElement("canvas"),ye=Object.create(M.webGLContextAttributes);return ye.failIfMajorPerformanceCaveat=ie,pe.getContext("webgl2",ye)}(H);if(!ee)return!1;try{G=ee.createShader(ee.VERTEX_SHADER)}catch{return!1}return!(!G||ee.isContextLost())&&(ee.shaderSource(G,"void main() {}"),ee.compileShader(G),ee.getShaderParameter(G,ee.COMPILE_STATUS)===!0)}(z)),S[z]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var z}f=1,x.supported=M,x.notSupportedReason=g;var S={};return M.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},x}();function _(M,g,S){const P=document.createElement(M);return g!=null&&(P.className=g),S&&S.appendChild(P),P}function b(M,g,S){const P=document.createElementNS("http://www.w3.org/2000/svg",M);for(const z of Object.keys(g))P.setAttributeNS(null,z,String(g[z]));return S&&S.appendChild(P),P}const j=typeof document<"u"?document.documentElement&&document.documentElement.style:null,N=j&&j.userSelect!==void 0?"userSelect":"WebkitUserSelect";let C;function A(){j&&N&&(C=j[N],j[N]="none")}function E(){j&&N&&(j[N]=C)}function D(M){M.preventDefault(),M.stopPropagation(),window.removeEventListener("click",D,!0)}function R(){window.addEventListener("click",D,!0),window.setTimeout(()=>{window.removeEventListener("click",D,!0)},0)}function F(M,g){const S=M.getBoundingClientRect();return K(M,S,g)}function O(M,g){const S=M.getBoundingClientRect(),P=[];for(let z=0;zthis._skuTokenExpiresAt}transformRequest(g,S){return this._transformRequestFn&&this._transformRequestFn(g,S)||{url:g}}normalizeStyleURL(g,S){if(!o.e(g))return g;const P=ne(g);return P.params.push(`sdk=js-${c}`),P.path=`/styles/v1${P.path}`,this._makeAPIURL(P,this._customAccessToken||S)}normalizeGlyphsURL(g,S){if(!o.e(g))return g;const P=ne(g);return P.path=`/fonts/v1${P.path}`,this._makeAPIURL(P,this._customAccessToken||S)}normalizeModelURL(g,S){if(!o.e(g))return g;const P=ne(g);return P.path=`/models/v1${P.path}`,this._makeAPIURL(P,this._customAccessToken||S)}normalizeSourceURL(g,S,P,z){if(!o.e(g))return g;const H=ne(g);return H.path=`/v4/${H.authority}.json`,H.params.push("secure"),P&&H.params.push(`language=${P}`),z&&H.params.push(`worldview=${z}`),this._makeAPIURL(H,this._customAccessToken||S)}normalizeIconsetURL(g,S){const P=ne(g);return o.e(g)?(P.path=`/styles/v1${P.path}/iconset.pbf`,this._makeAPIURL(P,this._customAccessToken||S)):ae(P)}normalizeSpriteURL(g,S,P,z){const H=ne(g);return o.e(g)?(H.path=`/styles/v1${H.path}/sprite${S}${P}`,this._makeAPIURL(H,this._customAccessToken||z)):(H.path+=`${S}${P}`,ae(H))}normalizeTileURL(g,S,P){if(this._isSkuTokenExpired()&&this._createSkuToken(),g&&!o.e(g))return g;const z=ne(g);z.path=z.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${S||P&&z.authority!=="raster"&&P===512?"@2x":""}${o.k.supported?".webp":"$1"}`),z.authority==="raster"?z.path=`/${o.g.RASTER_URL_PREFIX}${z.path}`:z.authority==="rasterarrays"?z.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${z.path}`:z.authority==="3dtiles"?z.path=`/${o.g.TILES3D_URL_PREFIX}${z.path}`:(z.path=z.path.replace(/^.+\/v4\//,"/"),z.path=`/${o.g.TILE_URL_VERSION}${z.path}`);const H=this._customAccessToken||function(G){for(const ee of G){const ie=ee.match(/^access_token=(.*)$/);if(ie)return ie[1]}return null}(z.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&H&&this._skuToken&&z.params.push(`sku=${this._skuToken}`),this._makeAPIURL(z,H)}canonicalizeTileURL(g,S){const P=ne(g);if(!P.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!P.path.match(/\.[\w]+$/))return g;let z="mapbox://";P.path.match(/^\/raster\/v1\//)?z+=`raster/${P.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:P.path.match(/^\/rasterarrays\/v1\//)?z+=`rasterarrays/${P.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:z+=`tiles/${P.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let H=P.params;return S&&(H=H.filter(G=>!G.match(/^access_token=/))),H.length&&(z+=`?${H.join("&")}`),z}canonicalizeTileset(g,S){const P=!!S&&o.e(S),z=[];for(const H of g.tiles||[])o.f(H)?z.push(this.canonicalizeTileURL(H,P)):z.push(H);return z}_makeAPIURL(g,S){const P="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",z=ne(o.g.API_URL);if(g.protocol=z.protocol,g.authority=z.authority,g.protocol==="http"){const H=g.params.indexOf("secure");H>=0&&g.params.splice(H,1)}if(z.path!=="/"&&(g.path=`${z.path}${g.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return ae(g);if(S=S||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!S)throw new Error(`An API access token is required to use Mapbox GL. ${P}`);if(S[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${P}`)}return g.params=g.params.filter(H=>H.indexOf("access_token")===-1),g.params.push(`access_token=${S||""}`),ae(g)}}const te=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function ne(M){const g=M.match(te);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 ae(M){const g=M.params.length?`?${M.params.join("&")}`:"";return`${M.protocol}://${M.authority}${M.path}${g}`}const ue="mapbox.eventData";function me(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 de(M){return!(!o.g.EVENTS_URL||!M&&!o.g.ACCESS_TOKEN)}class fe{constructor(g){this.type=g,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(g){const S=me(o.g.ACCESS_TOKEN);let P="";return P=S&&S.u?o.j(S.u):o.g.ACCESS_TOKEN||"",g?`${ue}.${g}:${P}`:`${ue}:${P}`}fetchEventData(){const g=o.s("localStorage"),S=this.getStorageKey(),P=this.getStorageKey("uuid"),z=this.getStorageKey("uuidTimestamp");if(g)try{const H=localStorage.getItem(S);H&&(this.eventData=JSON.parse(H));const G=localStorage.getItem(P);G&&(this.anonId=G);const ee=localStorage.getItem(z);ee&&(this.anonIdTimestamp=Number(ee));const ie=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(S,JSON.stringify(this.eventData)),G&&localStorage.setItem(z,G.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(g){}postEvent(g,S,P,z){if(!o.g.EVENTS_URL)return;const H=ne(o.g.EVENTS_URL);H.params.push(`access_token=${z||o.g.ACCESS_TOKEN||""}`);const G={event:this.type,created:new Date(g).toISOString()},ee=S?Object.assign(G,S):G,ie={url:ae(H),headers:{"Content-Type":"text/plain"},body:JSON.stringify([ee])};this.pendingRequest=o.p(ie,pe=>{this.pendingRequest=null,P(pe),this.saveEventData(),this.processRequests(z)})}queueRequest(g,S){this.queue.push(g),this.processRequests(S)}}class je extends fe{constructor(g){super("metrics"),g&&(this.data=g)}postMetricsEvent(g){if(!de(g))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const S=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:S},g)}processRequests(g){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:S,payload:P}=this.queue.shift();this.postEvent(S,P,()=>{},g)}}const xe=new class extends fe{constructor(M){super("appUserTurnstile"),this._customAccessToken=M}postTurnstileEvent(M,g){de(g)&&Array.isArray(M)&&M.some(S=>o.e(S)||o.f(S))&&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=me(o.g.ACCESS_TOKEN),S=g?g.u:o.g.ACCESS_TOKEN;let P=S!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),P=!0);const z=this.queue.shift();if(this.eventData.lastSuccess){const H=new Date(this.eventData.lastSuccess),G=new Date(z),ee=(z-this.eventData.lastSuccess)/864e5;P=P||ee>=1||ee<-1||H.getDate()!==G.getDate()}else P=!0;P?this.postEvent(z,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:Z,"enabled.telemetry":!1,userId:this.anonId},H=>{H||(this.eventData.lastSuccess=z,this.eventData.tokenU=S)},M):this.processRequests()}},Ee=xe.postTurnstileEvent.bind(xe),Me=new class extends fe{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(M,g,S,P){this.skuToken=g,this.errorCb=P,o.g.EVENTS_URL&&(S||o.g.ACCESS_TOKEN?this.queueRequest({id:M,timestamp:Date.now()},S):this.errorCb(new Error(Q)))}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{id:g,timestamp:S}=this.queue.shift();g&&this.success[g]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(S,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:Z,skuToken:this.skuToken,userId:this.anonId},P=>{P?this.errorCb(P):g&&(this.success[g]=!0)},M))}remove(){this.errorCb=null}},Oe=Me.postMapLoadEvent.bind(Me),Ie=new class extends fe{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:S,style:P,importedStyles:z}=g;if(!de(M))return;const H=this.getMapInstanceId(S),G={mapInstanceId:H,eventId:this.getEventId(H),style:P};z.length&&(G.importedStyles=z),this.queueRequest({timestamp:Date.now(),payload:G},M)}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:g,payload:S}=this.queue.shift();this.postEvent(g,S,()=>{},M)}},ze=Ie.postStyleLoadEvent.bind(Ie),Ve=new je({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Le=Ve.postMetricsEvent.bind(Ve),$e=new je({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),ve=$e.postMetricsEvent.bind($e),Qe=new class extends fe{constructor(){super("gljs.performance")}postPerformanceEvent(M,g){de(M)&&this.queueRequest({timestamp:Date.now(),performanceData:g},M)}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:g,performanceData:S}=this.queue.shift(),P=function(z){const H=performance.getEntriesByType("resource"),G=performance.getEntriesByType("mark"),ee=function(Be){const tt={};if(Be){for(const Ye in Be)if(Ye!=="other")for(const ut of Be[Ye]){const dt=`${Ye}ResolveRangeMin`,jt=`${Ye}ResolveRangeMax`,Tt=`${Ye}RequestCount`,ft=`${Ye}RequestCachedCount`;tt[dt]=Math.min(tt[dt]||1/0,ut.startTime),tt[jt]=Math.max(tt[jt]||-1/0,ut.responseEnd);const Kt=Rt=>{tt[Rt]===void 0&&(tt[Rt]=0),++tt[Rt]};ut.transferSize!==void 0&&ut.transferSize===0&&Kt(ft),Kt(Tt)}}return tt}(function(Be,tt){const Ye={};if(Be)for(const ut of Be){const dt=tt(ut);Ye[dt]===void 0&&(Ye[dt]=[]),Ye[dt].push(ut)}return Ye}(H,m)),ie=window.devicePixelRatio,pe=navigator.connection||navigator.mozConnection||navigator.webkitConnection,ye=pe?pe.effectiveType:void 0,De={counters:[],metadata:[],attributes:[]},Ae=(Be,tt,Ye)=>{Ye!=null&&Be.push({name:tt,value:Ye.toString()})};for(const Be in ee)Ae(De.counters,Be,ee[Be]);if(z.interactionRange[0]!==1/0&&z.interactionRange[1]!==-1/0&&(Ae(De.counters,"interactionRangeMin",z.interactionRange[0]),Ae(De.counters,"interactionRangeMax",z.interactionRange[1])),G)for(const Be of Object.values(d)){const tt=G.find(Ye=>Ye.name===Be);tt&&Ae(De.counters,Be,tt.startTime)}return Ae(De.counters,"visibilityHidden",z.visibilityHidden),Ae(De.attributes,"style",function(Be){if(Be)for(const tt of Be){const Ye=tt.name.split("?")[0];if(o.i(Ye)){const ut=Ye.split("/").slice(-2);if(ut.length===2)return`mapbox://styles/${ut[0]}/${ut[1]}`}}}(H)),Ae(De.attributes,"terrainEnabled",z.terrainEnabled?"true":"false"),Ae(De.attributes,"fogEnabled",z.fogEnabled?"true":"false"),Ae(De.attributes,"projection",z.projection),Ae(De.attributes,"zoom",z.zoom),Ae(De.metadata,"devicePixelRatio",ie),Ae(De.metadata,"connectionEffectiveType",ye),Ae(De.metadata,"navigatorUserAgent",navigator.userAgent),Ae(De.metadata,"screenWidth",window.screen.width),Ae(De.metadata,"screenHeight",window.screen.height),Ae(De.metadata,"windowWidth",window.innerWidth),Ae(De.metadata,"windowHeight",window.innerHeight),Ae(De.metadata,"mapWidth",z.width/ie),Ae(De.metadata,"mapHeight",z.height/ie),Ae(De.metadata,"webglRenderer",z.renderer),Ae(De.metadata,"webglVendor",z.vendor),Ae(De.metadata,"sdkVersion",c),Ae(De.metadata,"sdkIdentifier","mapbox-gl-js"),De}(S);for(const z of P.metadata);for(const z of P.counters);for(const z of P.attributes);this.postEvent(g,P,()=>{},M)}},we=Qe.postPerformanceEvent.bind(Qe),nt=new class extends fe{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(M,g,S,P){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const z=ne(o.g.API_URL+o.g.SESSION_PATH);z.params.push(`sku=${g||""}`),z.params.push(`access_token=${P||o.g.ACCESS_TOKEN||""}`);const H={url:ae(z),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(H,G=>{this.pendingRequest=null,S(G),this.saveEventData(),this.processRequests(P)})}getSessionAPI(M,g,S,P){this.skuToken=g,this.errorCb=P,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(S||o.g.ACCESS_TOKEN?this.queueRequest({id:M,timestamp:Date.now()},S):this.errorCb(new Error(Q)))}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{id:g,timestamp:S}=this.queue.shift();g&&this.success[g]||this.getSession(S,this.skuToken,P=>{P?this.errorCb(P):g&&(this.success[g]=!0)},M)}remove(){this.errorCb=null}},Se=nt.getSessionAPI.bind(nt),Ge=new Set;function We(M,g){g?Ge.add(M):Ge.delete(M)}class Ce{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,S){this._updatedSourceCaches[g]=S,this.setDirty()}discardSourceCacheUpdate(g){delete this._updatedSourceCaches[g]}updateLayer(g){const S=g.scope;this._updatedLayers[S]=this._updatedLayers[S]||new Set,this._updatedLayers[S].add(g.id),this.setDirty()}removeLayer(g){const S=g.scope;this._removedLayers[S]=this._removedLayers[S]||{},this._updatedLayers[S]=this._updatedLayers[S]||new Set,this._removedLayers[S][g.id]=g,this._updatedLayers[S].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 S in this._updatedLayers)g[S]=g[S]||{},g[S].updatedIds=Array.from(this._updatedLayers[S].values());for(const S in this._removedLayers)g[S]=g[S]||{},g[S].removedIds=Object.keys(this._removedLayers[S]);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,S){this._updatedImages[S]=this._updatedImages[S]||new Set,this._updatedImages[S].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 qe(M){const{userImage:g}=M;return!!(g&&g.render&&g.render())&&(M.data.replace(new Uint8Array(g.data.buffer)),!0)}const et={workerUrl:"",workerClass:null,workerParams:void 0};function Ze(M){return et.workerClass!=null?new et.workerClass:new self.Worker(et.workerUrl,Object.assign({name:M},et.workerParams))}const rt="mapboxgl_preloaded_worker_pool";class ct{constructor(g){this.active={},this.name=g}acquire(g,S=ct.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{S.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[rt]}numActive(){return Object.keys(this.active).length}}ct.workerCount=2;class vt{constructor(g,S,P="Worker",z=ct.workerCount){this.workerPool=g,this.actors=[],this.currentActor=0,this.id=o.r();const H=this.workerPool.acquire(this.id,z);for(let G=0;G{this.ready=!0})}broadcast(g,S,P){o.t(this.actors,(z,H)=>{z.send(g,S,H)},P=P||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 kt,St;function Yt(){return kt||(kt=new ct),kt}vt.Actor=o.A;class es 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 vt((St||(St=new ct("ImageRasterizer")),St),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 S=this.atlasTexture.get(g);S&&(S.destroy(),this.atlasTexture.delete(g))}addImageProvider(g,S){this.imageProviders.has(S)||this.imageProviders.set(S,new Map),this.imageProviders.get(S).set(g.id,g)}removeImageProvider(g,S){this.imageProviders.has(S)&&this.imageProviders.get(S).delete(g)}getPendingImageProviders(){const g=[];for(const S of this.imageProviders.values())for(const P of S.values())P.hasPendingRequests()&&g.push(P);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,S){if(this.loaded.get(S)!==g&&(this.loaded.set(S,g),g)){for(const{ids:P,callback:z}of this.requestors)this._notify(P,S,z);this.requestors=[]}}hasImage(g,S){return!!this.getImage(g,S)}getImage(g,S){return this.images.get(S).get(g.toString())}addImage(g,S,P){if(this._validate(g,P)){this.images.get(S).set(g.toString(),P);const z=this.imageVersions.get(S),H=z.get(g.toString())||0;z.set(g.toString(),H+1)}}_validate(g,S){let P=!0;return this._validateStretch(S.stretchX,S.data&&S.data.width)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "stretchX" value`))),P=!1),this._validateStretch(S.stretchY,S.data&&S.data.height)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "stretchY" value`))),P=!1),this._validateContent(S.content,S)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "content" value`))),P=!1),P}_validateStretch(g,S){if(!g)return!0;let P=0;for(const z of g){if(z[0]o.I.from(S))}getImageVersions(g){const S=this.imageVersions.get(g);if(S)return S}getImages(g,S,P){const z=[],H=[],G=this.imageProviders.get(S);for(const ye of g){if(!ye.iconsetId){z.push(ye);continue}const De=G.get(ye.iconsetId);De&&(this.getImage(ye,S)?H.push(ye):De.addPendingRequest(ye))}if(z.length===0)return void this._notify(H,S,P);let ee=!0;const ie=!!this.loaded.get(S),pe=this.images.get(S);if(!ie)for(const ye of z)pe.has(ye.toString())||(ee=!1);ie||ee?this._notify(z,S,P):this.requestors.push({ids:z,scope:S,callback:P})}rasterizeImages(g,S){const P=new Map,{tasks:z,scope:H}=g;for(const[G,ee]of z.entries()){const ie=this.getImage(ee.id,H);ie&&P.set(G,{image:ie,imageVariant:ee})}this._rasterizeImages(H,P,S)}_rasterizeImages(g,S,P){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:S,scope:g},P);else{const z=new Map;for(const[H,{image:G,imageVariant:ee}]of S.entries())z.set(H,this.imageRasterizer.rasterize(ee,G,g,0));P(void 0,z)}}getUpdatedImages(g){return this.updatedImages.get(g)||new Set}_notify(g,S,P){const z=this.images.get(S),H=new Map;for(const G of g){if(!z.get(G.toString())){if(G.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:G.name}))}const ee=z.get(G.toString());if(!ee){o.w(`Image "${G.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 ie={data:ee.usvg?null:ee.data.clone(),pixelRatio:ee.pixelRatio,sdf:ee.sdf,usvg:ee.usvg,stretchX:ee.stretchX,stretchY:ee.stretchY,content:ee.content,hasRenderCallback:!!(ee.userImage&&ee.userImage.render)};ee.usvg&&Object.assign(ie,{width:ee.icon.usvg_tree.width,height:ee.icon.usvg_tree.height}),H.set(o.I.toString(G),ie)}P(null,{images:H,versions:this.getImageVersions(S)})}getPixelSize(g){const{width:S,height:P}=this.atlasImage.get(g);return{width:S,height:P}}getPattern(g,S,P){const z=g.toString(),H=this.patterns.get(S),G=H.get(z),ee=this.getImage(g,S);if(!ee)return null;if(G){if(G.position.version===ee.version)return G.position;G.position.version=ee.version}else{if(ee.usvg&&!ee.data){const ie=this.getPatternInFlightId(z,S);if(this.patternsInFlight.has(ie))return null;this.patternsInFlight.add(ie);const pe=new o.D(g).scaleSelf(o.o.devicePixelRatio),ye=new Map([[pe.toString(),{image:ee,imageVariant:pe}]]);return this._rasterizeImages(S,ye,(De,Ae)=>this.storePatternImage(pe,S,ee,P,Ae)),null}this.storePattern(g,S,ee)}return this._updatePatternAtlas(S,P),H.get(z).position}getPatternInFlightId(g,S){return o.F(g,S)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(g,S,P,z,H){const G=g.toString(),ee=H?H.get(G):void 0;ee&&(P.data=ee,this.storePattern(g.id,S,P),this._updatePatternAtlas(S,z),this.patternsInFlight.delete(this.getPatternInFlightId(g.id.toString(),S)))}storePattern(g,S,P){const z={w:P.data.width+2*o.G,h:P.data.height+2*o.G,x:0,y:0},H=new o.H(z,P,o.G);this.patterns.get(S).set(g.toString(),{bin:z,position:H})}destroyAtlasTextures(){for(const g of this.atlasTexture.values())g&&g.destroy();this.atlasTexture.clear()}bind(g,S){const P=g.gl;let z=this.atlasTexture.get(S);z?this.dirty&&(z.update(this.atlasImage.get(S)),this.dirty=!1):(z=new o.T(g,this.atlasImage.get(S),P.RGBA8),this.atlasTexture.set(S,z)),z.bind(P.LINEAR,P.CLAMP_TO_EDGE)}_updatePatternAtlas(g,S){const P=this.patterns.get(g),z=Array.from(P.values()).map(({bin:pe})=>pe),{w:H,h:G}=o.J(z),ee=this.atlasImage.get(g);ee.resize({width:H||1,height:G||1});const ie=this.images.get(g);for(const[pe,{bin:ye,position:De}]of P.entries()){let Ae=De.padding;const Be=ye.x+Ae,tt=ye.y+Ae,Ye=ie.get(pe).data,ut=Ye.width,dt=Ye.height;Ae=Ae>1?Ae-1:Ae,o.q.copy(Ye,ee,{x:0,y:0},{x:Be,y:tt},{width:ut,height:dt},S),o.q.copy(Ye,ee,{x:0,y:dt-Ae},{x:Be,y:tt-Ae},{width:ut,height:Ae},S),o.q.copy(Ye,ee,{x:0,y:0},{x:Be,y:tt+dt},{width:ut,height:Ae},S),o.q.copy(Ye,ee,{x:ut-Ae,y:0},{x:Be-Ae,y:tt},{width:Ae,height:dt},S),o.q.copy(Ye,ee,{x:0,y:0},{x:Be+ut,y:tt},{width:Ae,height:dt},S),o.q.copy(Ye,ee,{x:ut-Ae,y:dt-Ae},{x:Be-Ae,y:tt-Ae},{width:Ae,height:Ae},S),o.q.copy(Ye,ee,{x:0,y:dt-Ae},{x:Be+ut,y:tt-Ae},{width:Ae,height:Ae},S),o.q.copy(Ye,ee,{x:0,y:0},{x:Be+ut,y:tt+dt},{width:Ae,height:Ae},S),o.q.copy(Ye,ee,{x:ut-Ae,y:0},{x:Be-Ae,y:tt+dt},{width:Ae,height:Ae},S)}this.dirty=!0}beginFrame(){for(const g of this.images.keys())this.callbackDispatchedThisFrame.set(g,new Set)}dispatchRenderCallbacks(g,S){const P=this.images.get(S);for(const z of g){if(this.callbackDispatchedThisFrame.get(S).has(z.toString()))continue;this.callbackDispatchedThisFrame.get(S).add(z.toString());const H=P.get(z.toString());qe(H)&&this.updateImage(z,S,H)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function zs(M){const g=M.value,S=M.valueSpec,P=M.style,z=M.styleSpec,H=M.key,G=M.arrayElementValidator||In;if(!Array.isArray(g))return[new o.V(H,g,`array expected, ${o.M(g)} found`)];if(S.length&&g.length!==S.length)return[new o.V(H,g,`array length ${S.length} expected, length ${g.length} found`)];if(S["min-length"]&&g.lengthz)return[new o.V(g,S,`${S} is greater than the maximum value ${z}`)]}return[]}function ms(M){const g=M.key,S=M.value;if(!o.K(S))return[new o.V(g,S,`object expected, ${o.M(S)} found`)];const P=M.valueSpec,z=o.L(S.type);let H,G,ee,ie={};const pe=z!=="categorical"&&S.property===void 0,ye=!pe,De=function(Ye){const ut=Ye.stops;return Array.isArray(ut)&&Array.isArray(ut[0])&&o.K(ut[0][0])}(S),Ae=Br({key:M.key,value:M.value,valueSpec:M.styleSpec.function,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{stops:function(Ye){if(z==="identity")return[new o.V(Ye.key,Ye.value,'identity function may not have a "stops" property')];let ut=[];const dt=Ye.value;return ut=ut.concat(zs({key:Ye.key,value:dt,valueSpec:Ye.valueSpec,style:Ye.style,styleSpec:Ye.styleSpec,arrayElementValidator:Be})),Array.isArray(dt)&&dt.length===0&&ut.push(new o.V(Ye.key,dt,"array must have at least one stop")),ut},default:function(Ye){return In({key:Ye.key,value:Ye.value,valueSpec:P,style:Ye.style,styleSpec:Ye.styleSpec})}}});return z==="identity"&&pe&&Ae.push(new o.V(M.key,M.value,'missing required property "property"')),z==="identity"||S.stops||Ae.push(new o.V(M.key,M.value,'missing required property "stops"')),z==="exponential"&&P.expression&&!o.O(P)&&Ae.push(new o.V(M.key,M.value,"exponential functions not supported")),M.styleSpec.$version>=8&&(ye&&!o.Q(P)?Ae.push(new o.V(M.key,M.value,"property functions not supported")):pe&&!o.S(P)&&Ae.push(new o.V(M.key,M.value,"zoom functions not supported"))),z!=="categorical"&&!De||S.property!==void 0||Ae.push(new o.V(M.key,M.value,'"property" property is required')),Ae;function Be(Ye){let ut=[];const dt=Ye.value,jt=Ye.key;if(!Array.isArray(dt))return[new o.V(jt,dt,`array expected, ${o.M(dt)} found`)];if(dt.length!==2)return[new o.V(jt,dt,`array length 2 expected, length ${dt.length} found`)];if(De){if(!o.K(dt[0]))return[new o.V(jt,dt,`object expected, ${o.M(dt[0])} found`)];const Tt=dt[0];if(Tt.zoom===void 0)return[new o.V(jt,dt,"object stop key must have zoom")];if(Tt.value===void 0)return[new o.V(jt,dt,"object stop key must have value")];const ft=o.L(Tt.zoom);if(typeof ft!="number")return[new o.V(jt,Tt.zoom,"stop zoom values must be numbers")];if(ee&&ee>ft)return[new o.V(jt,Tt.zoom,"stop zoom values must appear in ascending order")];ft!==ee&&(ee=ft,G=void 0,ie={}),ut=ut.concat(Br({key:`${jt}[0]`,value:dt[0],valueSpec:{zoom:{}},style:Ye.style,styleSpec:Ye.styleSpec,objectElementValidators:{zoom:sr,value:tt}}))}else ut=ut.concat(tt({key:`${jt}[0]`,value:dt[0],style:Ye.style,styleSpec:Ye.styleSpec},dt));return o.U(o.W(dt[1]))?ut.concat([new o.V(`${jt}[1]`,dt[1],"expressions are not allowed in function stops.")]):ut.concat(In({key:`${jt}[1]`,value:dt[1],valueSpec:P,style:Ye.style,styleSpec:Ye.styleSpec}))}function tt(Ye,ut){const dt=o.M(Ye.value),jt=o.L(Ye.value),Tt=Ye.value!==null?Ye.value:ut;if(H){if(dt!==H)return[new o.V(Ye.key,Tt,`${dt} stop domain type must match previous stop domain type ${H}`)]}else H=dt;if(dt!=="number"&&dt!=="string"&&dt!=="boolean"&&typeof jt!="number"&&typeof jt!="string"&&typeof jt!="boolean")return[new o.V(Ye.key,Tt,"stop domain value must be a number, string, or boolean")];if(dt!=="number"&&z!=="categorical"){let ft=`number expected, ${dt} found`;return o.Q(P)&&z===void 0&&(ft+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(Ye.key,Tt,ft)]}return z!=="categorical"||dt!=="number"||typeof jt=="number"&&isFinite(jt)&&Math.floor(jt)===jt?z!=="categorical"&&dt==="number"&&typeof jt=="number"&&typeof G=="number"&&G!==void 0&&jtnew o.V(`${M.key}${P.key}`,M.value,P.message));const S=g.value.expression||g.value._styleExpression.expression;if(M.expressionContext==="property"&&M.propertyKey==="text-font"&&!S.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.$(S))return[new o.V(M.key,M.value,'"feature-state" data expressions are not supported with layout properties.')];if(M.expressionContext==="filter")return Ut(S,M);if(M.expressionContext==="appearance")return ht(S,M);if(M.expressionContext&&M.expressionContext.indexOf("cluster")===0){if(!o.Z(S,["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._(S))return[new o.V(M.key,M.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Ut(M,g){const S=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(g.valueSpec&&g.valueSpec.expression)for(const z of g.valueSpec.expression.parameters)S.delete(z);if(S.size===0)return[];const P=[];return M instanceof o.a0&&S.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(z=>{P.push(...Ut(z,g))}),P)}function ht(M,g){const S=new Set;if(g.valueSpec&&g.valueSpec.expression)for(const z of g.valueSpec.expression.parameters)S.add(z);if(S.size===0)return[];const P=[];return M instanceof o.a0&&!S.has(M.name)?[new o.V(g.key,g.value,`["${M.name}"] is not an allowed parameter`)]:(M.eachChild(z=>{P.push(...ht(z,g))}),P)}function Jt(M){const g=M.key,S=M.value,P=M.valueSpec,z=[];return Array.isArray(P.values)?P.values.indexOf(o.L(S))===-1&&z.push(new o.V(g,S,`expected one of [${P.values.join(", ")}], ${JSON.stringify(S)} found`)):Object.keys(P.values).indexOf(o.L(S))===-1&&z.push(new o.V(g,S,`expected one of [${Object.keys(P.values).join(", ")}], ${JSON.stringify(S)} found`)),z}function Ms(M){return o.a4(o.W(M.value))?gt(Object.assign({},M,{expressionContext:"filter",valueSpec:M.styleSpec[`filter_${M.layerType||"fill"}`]})):ts(M)}function ts(M){const g=M.value,S=M.key;if(!Array.isArray(g))return[new o.V(S,g,`array expected, ${o.M(g)} found`)];if(g.length<1)return[new o.V(S,g,"filter array must have at least 1 element")];const P=M.styleSpec;let z=Jt({key:`${S}[0]`,value:g[0],valueSpec:P.filter_operator});const H=()=>{g.length>=2&&(o.a2(g[1])||z.push(new o.V(`${S}[1]`,g[1],`string expected, ${o.M(g[1])} found`)));for(let G=2;G":case">=":g.length>=2&&o.L(g[1])==="$type"&&z.push(new o.V(S,g,`"$type" cannot be use with operator "${g[0]}"`)),g.length!==3&&z.push(new o.V(S,g,`filter array for operator "${g[0]}" must have 3 elements`)),H();break;case"==":case"!=":g.length!==3&&z.push(new o.V(S,g,`filter array for operator "${g[0]}" must have 3 elements`)),H();break;case"in":case"!in":H();break;case"any":case"all":case"none":for(let G=1;G{pe in S&&g.push(new o.V(P,S[pe],`"${pe}" is prohibited for ref layers`))}),z.layers.forEach(pe=>{o.L(pe.id)===ee&&(ie=pe)}),ie?ie.ref?g.push(new o.V(P,S.ref,"ref cannot reference another ref layer")):G=o.L(ie.type):typeof ee=="string"&&g.push(new o.V(P,S.ref,`ref layer "${ee}" not found`))}else if(G!=="background"&&G!=="sky"&&G!=="slot")if(S.source)if(o.a2(S.source)){const ie=z.sources&&z.sources[S.source],pe=ie&&o.L(ie.type);ie?pe==="vector"&&G==="raster"?g.push(new o.V(P,S.source,`layer "${S.id}" requires a raster source`)):pe==="raster"&&G!=="raster"?g.push(new o.V(P,S.source,`layer "${S.id}" requires a vector source`)):pe!=="vector"||S["source-layer"]?pe==="raster-dem"&&G!=="hillshade"?g.push(new o.V(P,S.source,"raster-dem source can only be used with layer type 'hillshade'.")):pe!=="raster-array"||["raster","raster-particle"].includes(G)?G==="line"&&S.paint&&(S.paint["line-gradient"]||S.paint["line-trim-offset"])&&pe==="geojson"&&!ie.lineMetrics?g.push(new o.V(P,S,`layer "${S.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):G==="raster-particle"&&pe!=="raster-array"&&g.push(new o.V(P,S.source,`layer "${S.id}" requires a 'raster-array' source.`)):g.push(new o.V(P,S.source,"raster-array source can only be used with layer type 'raster'.")):g.push(new o.V(P,S,`layer "${S.id}" must specify a "source-layer"`)):g.push(new o.V(P,S.source,`source "${S.source}" not found`))}else g.push(new o.V(`${P}.source`,S.source,'"source" must be a string'));else g.push(new o.V(P,S,'missing required property "source"'));return g=g.concat(Br({key:P,value:S,valueSpec:H.layer,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{"*":()=>[],type:()=>In({key:`${P}.type`,value:S.type,valueSpec:H.layer.type,style:M.style,styleSpec:M.styleSpec,object:S,objectKey:"type"}),filter:ie=>Ms(Object.assign({layerType:G},ie)),layout:ie=>Br({layer:S,key:ie.key,value:ie.value,valueSpec:{},style:ie.style,styleSpec:ie.styleSpec,objectElementValidators:{"*":pe=>$s(Object.assign({layerType:G},pe))}}),paint:ie=>Br({layer:S,key:ie.key,value:ie.value,valueSpec:{},style:ie.style,styleSpec:ie.styleSpec,objectElementValidators:{"*":pe=>js(Object.assign({layerType:G,layer:S},pe))}}),appearances(ie){const pe=zs({key:ie.key,value:ie.value,valueSpec:ie.valueSpec,style:ie.style,styleSpec:ie.styleSpec,arrayElementValidator:Ae=>function(Be){const{key:tt,layer:Ye,layerType:ut}=Be,dt=o.L(Be.value),jt=o.L(dt.name),Tt=o.L(dt.condition),ft=Br({key:tt,value:dt,valueSpec:Be.styleSpec.appearance,style:Be.style,styleSpec:Be.styleSpec,objectElementValidators:{condition:Kt=>function(Rt){const Wt=[];return Wt.push(...gt({key:Rt.key,value:Rt.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),Wt}(Object.assign({layer:Ye,layerType:ut},Kt)),properties:Kt=>function(Rt){const Wt=[],{styleSpec:Et,layer:Lt,layerType:Vt}=Rt,ds=Et[`paint_${Vt}`],Zt=Et[`layout_${Vt}`],Is=Rt.object[Rt.objectKey];for(const Ns in Is){const er=Ns in ds?"paint":Ns in Zt?"layout":void 0;if(!er){Wt.push(new o.V(Rt.key,Ns,`unknown property "${Ns}" for layer type "${Vt}"`));continue}const lr=Object.assign({},Rt,{key:`${Rt.key}.${Ns}`,object:Is,objectKey:Ns,layer:Lt,layerType:Vt,value:Is[Ns],valueSpec:er==="paint"?ds[Ns]:Zt[Ns]});Wt.push(...Xs(lr,er))}return Wt}(Object.assign({layer:Ye,layerType:ut},Kt))}});return jt!=="hidden"&&Tt===void 0&&ft.push(new o.V(Be.key,"name",'Appearance with name different than "hidden" must have a condition')),ft}(Object.assign({layerType:G,layer:S},Ae))}),ye=Array.isArray(ie.value)?ie.value:[],De=new Set;return ye.forEach((Ae,Be)=>{const tt=o.L(Ae.name);if(tt)if(De.has(tt)){const Ye=o.L(S.id);pe.push(new o.V(ie.key,tt,`Duplicated appearance name "${tt}" for layer "${Ye}"`))}else De.add(tt)}),pe}}})),g}function or({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:S}){if(o.a2(S))return or({key:g,value:S});if(Array.isArray(S)){const z=[],H=o.W(S),G=o.X(H);return G.result==="error"?(G.value.forEach(ee=>{z.push(new o.V(`${g}${ee.key}`,null,`${ee.message}`))}),z):(o.Z(G.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"])||z.push(new o.V(`${g}`,null,"promoteId expression should be only feature dependent")),z)}if(!o.K(S))return[new o.V(g,S,`string, expression or object expected, "${o.M(S)}" found`)];const P=[];for(const z in S)P.push(...M({key:`${g}.${z}`,value:S[z]}));return P}};function Sr(M){const g=M.value,S=M.key,P=M.styleSpec,z=M.style;if(!o.K(g))return[new o.V(S,g,`object expected, ${o.M(g)} found`)];if(!("type"in g))return[new o.V(S,g,'"type" is required')];const H=o.L(g.type);let G=[];switch(["vector","raster","raster-dem","raster-array"].includes(H)&&("url"in g||"tiles"in g||G.push(new o.a5(S,g,'Either "url" or "tiles" is required.'))),H){case"vector":case"raster":case"raster-dem":case"raster-array":return G=G.concat(Br({key:S,value:g,valueSpec:P[`source_${H.replace("-","_")}`],style:M.style,styleSpec:P,objectElementValidators:Er})),G;case"geojson":if(G=Br({key:S,value:g,valueSpec:P.source_geojson,style:z,styleSpec:P,objectElementValidators:Er}),"cluster"in g&&"clusterProperties"in g){if(!o.K(g.clusterProperties))return[new o.V(`${S}.clusterProperties`,g,`object expected, ${o.M(g)} found`)];for(const ee in g.clusterProperties){const ie=g.clusterProperties[ee];if(!Array.isArray(ie))return[new o.V(`${S}.clusterProperties.${ee}`,ie,"array expected")];const[pe,ye]=ie,De=typeof pe=="string"?[pe,["accumulated"],["get",ee]]:pe;G.push(...gt({key:`${S}.${ee}.map`,value:ye,expressionContext:"cluster-map"})),G.push(...gt({key:`${S}.${ee}.reduce`,value:De,expressionContext:"cluster-reduce"}))}}return G;case"video":return Br({key:S,value:g,valueSpec:P.source_video,style:z,styleSpec:P});case"image":return Br({key:S,value:g,valueSpec:P.source_image,style:z,styleSpec:P});case"canvas":return[new o.V(S,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Jt({key:`${S}.type`,value:g.type,valueSpec:{values:Gr(P)}})}}function Gr(M){return M.source.reduce((g,S)=>{const P=M[S];return P.type.type==="enum"&&(g=g.concat(Object.keys(P.type.values||{}))),g},[])}function Yr(M){const g=M.value,S=M.styleSpec,P=S.light,z=M.style;if(g===void 0)return[];if(!o.K(g))return[new o.V("light",g,`object expected, ${o.M(g)} found`)];let H=[];for(const G in g){const ee=G.match(/^(.*)-transition$/),ie=G.match(/^(.*)-use-theme$/);H=H.concat(ie&&P[ie[1]]?In({key:G,value:g[G],valueSpec:{type:"string"},style:z,styleSpec:S}):ee&&P[ee[1]]&&P[ee[1]].transition?In({key:G,value:g[G],valueSpec:S.transition,style:z,styleSpec:S}):P[G]?In({key:G,value:g[G],valueSpec:P[G],style:z,styleSpec:S}):[new o.V(G,g[G],`unknown property "${G}"`)])}return H}function Fn(M){const g=M.value;if(!g)return[];const S=M.key;if(!o.K(g))return[new o.V(S,g,`object expected, ${o.M(g)} found`)];let P=[];const z=M.styleSpec,H=z["light-3d"],G=M.style,ee=M.style.lights;for(const ye of["type","id"])if(!(ye in g))return P=P.concat([new o.V(S,g,`missing property "${ye}"`)]),P;if(!o.a2(g.type))return P=P.concat([new o.V(`${S}.type`,g.type,"string expected")]),P;if(ee)for(let ye=0;ye[],array:zs,boolean:function(M){const g=M.value,S=M.key;return o.a1(g)?[]:[new o.V(S,g,`boolean expected, ${o.M(g)} found`)]},number:sr,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:Jt,filter:Ms,function:ms,layer:Js,object:Br,source:Sr,model:o.a9,light:Yr,"light-3d":Fn,terrain:sa,fog:gs,string:or,formatted:function(M){return or(M).length===0?[]:gt(M)},resolvedImage:function(M){return or(M).length===0?[]:gt(M)},projection:function(M){const g=M.value,S=M.styleSpec,P=S.projection,z=M.style;if(o.K(g)){let H=[];for(const G in g)H=H.concat(In({key:G,value:g[G],valueSpec:P[G],style:z,styleSpec:S}));return H}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:S,styleSpec:P}=M;if(!o.K(S))return[new o.V(g,S,"import must be an object")];const{data:z,...H}=S;Object.defineProperty(H,"__line__",{value:S.__line__,enumerable:!1});let G=Br(Object.assign({},M,{value:H,valueSpec:P.import}));return o.L(H.id)===""&&G.push(new o.V(`${M.key}.id`,H,"import id can't be an empty string")),z&&(G=G.concat(Or(z,P,{key:`${M.key}.data`}))),G},iconset:function(M){const g=M.value,S=M.key,P=M.styleSpec,z=M.style;if(!o.K(g))return[new o.V(S,g,"object expected")];if(!g.type)return[new o.V(S,g,'"type" is required')];const H=o.L(g.type);let G=[];if(G=G.concat(Br({key:S,value:g,valueSpec:P[`iconset_${H}`],style:z,styleSpec:P})),function(ee,ie){return!(ee!=="source"||!ie.source)}(H,g)){const ee=z.sources&&z.sources[g.source],ie=ee&&o.L(ee.type);ee?ie!=="raster-array"&&G.push(new o.V(S,g.source,`iconset cannot be used with a source of type ${String(ie)}, it only be used with a "raster-array" source type`)):G.push(new o.V(S,g.source,`source "${g.source}" not found`))}return G}};function In(M,g=!1){const S=M.value,P=M.valueSpec,z=M.styleSpec;if(P.expression){if(o.a6(o.L(S)))return ms(M);if(o.U(o.W(S)))return gt(M)}if(P.type&&mi[P.type]){const H=mi[P.type](M);return g===!0&&H.length>0&&Array.isArray(M.value)?gt(M):H}return Br(Object.assign({},M,{valueSpec:P.type?z[P.type]:P}))}function Br(M){const g=M.key,S=M.value,P=M.valueSpec||{},z=M.objectElementValidators||{},H=M.style,G=M.styleSpec;if(!o.K(S))return[new o.V(g,S,`object expected, ${o.M(S)} found`)];let ee=[];for(const ie in S){const pe=ie.split(".")[0];let ye;z[pe]?ye=z[pe]:P[pe]?ye=In:z["*"]?ye=z["*"]:P["*"]&&(ye=In),ye?ee=ee.concat(ye({key:(g&&`${g}.`)+ie,value:S[ie],valueSpec:P[pe]||P["*"],style:H,styleSpec:G,object:S,objectKey:ie},S)):ee.push(new o.a5(g,S[ie],`unknown property "${ie}"`))}for(const ie in P){if(z[ie])continue;const pe=P[ie];pe.required&&pe.default===void 0&&S[ie]===void 0&&ee.push(new o.V(g,S,`missing required property "${ie}"`))}return ee}function ps({key:M,value:g}){const S=or({key:M,value:g});if(S.length)return S;const P=g;return P.indexOf("{fontstack}")===-1&&S.push(new o.V(M,g,'"glyphs" url must include a "{fontstack}" token')),P.indexOf("{range}")===-1&&S.push(new o.V(M,g,'"glyphs" url must include a "{range}" token')),S}function Or(M,g=o.a8,S={}){return Br({key:S.key||"",value:M,valueSpec:Object.assign(g.$root,{"*":{type:"*"}}),styleSpec:g,style:M,objectElementValidators:{glyphs:ps}})}function Qr(M,g=o.a8){return us(Or(M,g))}const Tn=M=>us(Sr(M)),Qt=M=>us(Yr(M)),Re=M=>us(Fn(M)),Ke=M=>us(sa(M)),at=M=>us(gs(M)),Nt=M=>us(function(g){const S=g.value,P=g.style,z=g.styleSpec,H=z.snow;if(S===void 0)return[];if(!o.K(S))return[new o.V("snow",S,`object expected, ${o.M(S)} found`)];let G=[];for(const ee in S){const ie=ee.match(/^(.*)-transition$/);G=G.concat(ie&&H[ie[1]]&&H[ie[1]].transition?In({key:ee,value:S[ee],valueSpec:z.transition,style:P,styleSpec:z}):H[ee]?In({key:ee,value:S[ee],valueSpec:H[ee],style:P,styleSpec:z}):[new o.a5(ee,S[ee],`unknown property "${ee}"`)])}return G}(M)),Ft=M=>us(function(g){const S=g.value,P=g.style,z=g.styleSpec,H=z.rain;if(S===void 0)return[];if(!o.K(S))return[new o.V("rain",S,`object expected, ${o.M(S)} found`)];let G=[];for(const ee in S){const ie=ee.match(/^(.*)-transition$/);G=G.concat(ie&&H[ie[1]]&&H[ie[1]].transition?In({key:ee,value:S[ee],valueSpec:z.transition,style:P,styleSpec:z}):H[ee]?In({key:ee,value:S[ee],valueSpec:H[ee],style:P,styleSpec:z}):[new o.a5(ee,S[ee],`unknown property "${ee}"`)])}return G}(M)),qt=M=>us(Js(M)),cs=M=>us(Ms(M)),it=M=>us(js(M)),Xt=M=>us($s(M)),Bs=M=>us(o.a9(M));function us(M){return M.slice().sort((g,S)=>g.line&&S.line?g.line-S.line:0)}function cr(M,g){let S=!1;if(g&&g.length)for(const P of g)P instanceof o.a5?o.w(P.message):(M.fire(new o.B(new Error(P.message))),S=!0);return S}const Ar=o.a8.light;let xr;class Kr extends o.E{constructor(g,S="flat"){super(),this._transitionable=new o.aa(xr||(xr=new o.ab({anchor:new o.ac(Ar.anchor),position:new o.ad(Ar.position),color:new o.ac(Ar.color),intensity:new o.ac(Ar.intensity)}))),this.setLight(g,S),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(g,S,P={}){this._validate(Qt,g,P)||(this._transitionable.setTransitionOrValue(g),this.id=S)}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,S,P){return(!P||P.validate!==!1)&&cr(this,g.call(Qr,Object.assign({value:S,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const mn=o.a8.terrain;let pn=class extends o.E{constructor(M,g,S,P,z){super(),this.scope=S,this._transitionable=new o.aa(new o.ab({source:new o.ac(mn.source),exaggeration:new o.ac(mn.exaggeration)}),S,P),this._transitionable.setTransitionOrValue(M,P),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=g,this.worldview=z}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 S=-1,P=-1,z=1;for(const H of g.zoomStops)z=g.evaluate(new o.ae(H,{worldview:this.worldview})),z>.01?(S=H,P=-1):P=H;return z<.01&&S>0&&P>S?[S,P]: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 wn=.05;function ca(M,g,S,P){const z=o.aj(45,65,S),[H,G]=Vi(M,P);let ee=1-Math.min(1,Math.exp((g-H)/(G-H)*-6));return ee*=ee*ee,ee=Math.min(1,1.00747*ee),ee*z*M.alpha}function Vi(M,g){const S=.5/Math.tan(.5*g);return[M.range[0]+S,M.range[1]+S]}function so(M,g,S,P,z){const H=o.ah([],[g,S,P],z.mercatorFogMatrix);return ca(M,o.ai(H),z.pitch,z._fov)}function Ka(M,g,S,P,z,H,G){const ee=[[S,P,0],[z,P,0],[z,H,0],[S,H,0]];let ie=Number.MAX_VALUE,pe=-Number.MAX_VALUE;for(const ye of ee){const De=o.ah([],ye,g),Ae=o.ai(De);ie=Math.min(ie,Ae),pe=Math.max(pe,Ae)}return[ca(M,ie,G.pitch,G._fov),ca(M,pe,G.pitch,G._fov)]}const kn=o.a8.fog;class Fi extends o.E{constructor(g,S,P,z){super();const H=new o.ab({range:new o.ac(kn.range),color:new o.ac(kn.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(kn["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(kn["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(kn["horizon-blend"]),"star-intensity":new o.ac(kn["star-intensity"]),"vertical-range":new o.ac(kn["vertical-range"])});this._transitionable=new o.aa(H,P,new Map(z)),this.set(g,z),this._transitioning=this._transitionable.untransitioned(),this._transform=S,this.properties=new o.ak(H),this.scope=P}get state(){const g=this._transform,S=g.projection.name==="globe",P=o.al(g.zoom),z=this.properties.get("range"),H=[.5,3];return{range:S?[o.am(H[0],z[0],P),o.am(H[1],z[1],P)]:z,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(g,S,P={}){if(this._validate(at,g,P))return;const z=Object.assign({},g);for(const H of Object.keys(kn))z[H]===void 0&&(z[H]=kn[H].default);this._options=z,this._transitionable.setTransitionOrValue(this._options,S)}getOpacity(g){if(!this._transform.projection.supportsFog)return 0;const S=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,g))*S.a}getOpacityAtLatLng(g,S){return this._transform.projection.supportsFog?function(P,z,H){const G=o.ag.fromLngLat(z),ee=H.elevation?H.elevation.getAtPointOrZero(G):0;return so(P,G.x,G.y,ee,H)}(this.state,g,S):0}getOpacityForTile(g){if(!this._transform.projection.supportsFog)return[1,1];const S=this._transform.calculateFogTileMatrix(g.toUnwrapped());return Ka(this.state,S,0,0,o.an,o.an,this._transform)}getOpacityForBounds(g,S,P,z,H){return this._transform.projection.supportsFog?Ka(this.state,g,S,P,z,H,this._transform):[1,1]}getFovAdjustedRange(g){return this._transform.projection.supportsFog?Vi(this.state,g):[0,1]}isVisibleOnFrustum(g){if(!this._transform.projection.supportsFog)return!1;const S=[4,5,6,7];for(const P of S){const z=g.points[P];let H;if(z[2]>=0)H=z;else{const G=g.points[P-4];H=o.ao(G,z,G[2]/(G[2]-z[2]))}if(so(this.state,H[0],H[1],0,this._transform)>=wn)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,S,P){return(!P||P.validate!==!1)&&cr(this,g.call(Qr,Object.assign({value:S,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let zi,Qa,Hi,Gi=class extends o.E{constructor(M,g,S,P){super();const z=zi||(zi=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(z,S,new Map(P)),this.set(M,P),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(z),this.scope=S}get state(){const M=this.properties.get("opacity"),g=this.properties.get("color"),S=this.properties.get("direction"),P=o.ap(S[0]),z=-Math.max(o.ap(S[1]),.01),H=[Math.cos(P)*Math.cos(z),Math.sin(P)*Math.cos(z),Math.sin(z)],G=this.properties.get("vignette"),ee=this.properties.get("vignette-color");return ee.a=G,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(g.r,g.g,g.b,g.a*M),direction:H,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:ee}}get(){return this._transitionable.serialize()}set(M,g,S={}){if(this._validate(Nt,M,S))return;const P=Object.assign({},M),z=o.a8.snow;for(const H of Object.keys(z))P[H]===void 0&&(P[H]=z[H].default);this._options=P,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,S){return(!S||S.validate!==!1)&&cr(this,M.call(Qr,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},Qn=class extends o.E{constructor(M,g,S,P){super();const z=Qa||(Qa=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(z,S,new Map(P)),this.set(M,P),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(z),this.scope=S}get state(){const M=this.properties.get("opacity"),g=this.properties.get("color"),S=this.properties.get("direction"),P=o.ap(S[0]),z=-Math.max(o.ap(S[1]),.01),H=[Math.cos(P)*Math.cos(z),Math.sin(P)*Math.cos(z),Math.sin(z)],G=this.properties.get("vignette-color");return G.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:H,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:G}}get(){return this._transitionable.serialize()}set(M,g,S={}){if(this._validate(Ft,M,S))return;const P=Object.assign({},M),z=o.a8.rain;for(const H of Object.keys(z))P[H]===void 0&&(P[H]=z[H].default);this._options=P,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,S){return(!S||S.validate!==!1)&&cr(this,M.call(Qr,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class vr extends o.E{constructor(g,S,P,z){super(),this.scope=P,this._options=g,this.properties=new o.ak(S),this._transitionable=new o.aa(S,P,new Map(z)),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,S){this._options=g,this._transitionable.setTransitionOrValue(g.properties,S)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const Ca=()=>Hi||(Hi=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 Ji;const Zo=()=>Ji||(Ji=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 vl{constructor(g,S,P){this.screenBounds=g,this.cameraPoint=P.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=S,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,P)}static createFromScreenPoints(g,S){let P,z;if(g instanceof o.P||typeof g[0]=="number"){const H=o.P.convert(g);P=[H],z=S.isPointAboveHorizon(H)}else{const H=o.P.convert(g[0]),G=o.P.convert(g[1]),ee=H.add(G)._div(2);P=[H,G],z=o.as(H,G).every(ie=>S.isPointAboveHorizon(ie))&&S.isPointAboveHorizon(ee)}return new vl(P,z,S)}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 S=this.screenBounds[0],P=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],z=o.as(S,P,0,!1);return this.cameraPoint.y>P.y&&(this.cameraPoint.x>S.x&&this.cameraPoint.x=P.x?z[2]=this.cameraPoint:this.cameraPoint.x<=S.x&&(z[3]=this.cameraPoint)),o.at(z,g)}bufferedCameraGeometryGlobe(g){const S=this.screenBounds[0],P=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],z=o.as(S,P,g),H=this.cameraPoint.clone(),G=+(H.x>S.x)+ +(H.x>P.x);switch(3*(+(H.y>S.y)+ +(H.y>P.y))+G){case 0:z[0]=H,z[4]=H.clone();break;case 1:z.splice(1,0,H);break;case 2:z[1]=H;break;case 3:z.splice(4,0,H);break;case 5:z.splice(2,0,H);break;case 6:z[3]=H;break;case 7:z.splice(3,0,H);break;case 8:z[2]=H}return z}containsTile(g,S,P,z=0){const H=Math.max(g.queryPadding,g.evaluateQueryRenderedFeaturePadding())/S._pixelsPerMercatorPixel+1,G=P?this._bufferedCameraMercator(H,S):this._bufferedScreenMercator(H,S);let ee=g.tileID.wrap+(G.unwrapped?z:0);const ie=G.polygon.map(ut=>o.au(g.tileTransform,ut,ee));if(!o.av(ie,0,0,o.an,o.an))return;ee=g.tileID.wrap+(this.screenGeometryMercator.unwrapped?z:0);const pe=this.screenGeometryMercator.polygon.map(ut=>o.aw(g.tileTransform,ut,ee)),ye=pe.map(ut=>new o.P(ut[0],ut[1])),De=S.getFreeCameraOptions().position||new o.ag(0,0,0),Ae=o.aw(g.tileTransform,De,ee),Be=pe.map(ut=>{const dt=o.ax(ut,ut,Ae);return o.ay(dt,dt),new o.az(Ae,dt)}),tt=o.aA(g,1,S.zoom)*S._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:ye,tilespaceRays:Be,bufferedTilespaceGeometry:ie,bufferedTilespaceBounds:(Ye=o.aB(ie),Ye.min.x=o.aC(Ye.min.x,0,o.an),Ye.min.y=o.aC(Ye.min.y,0,o.an),Ye.max.x=o.aC(Ye.max.x,0,o.an),Ye.max.y=o.aC(Ye.max.y,0,o.an),Ye),tile:g,tileID:g.tileID,pixelToTileUnitsFactor:tt};var Ye}_bufferedScreenMercator(g,S){const P=ju(g);if(this._screenRaycastCache[P])return this._screenRaycastCache[P];{let z;return z=S.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(g),S):{polygon:this.bufferedScreenGeometry(g).map(H=>S.pointCoordinate3D(H)),unwrapped:!0},this._screenRaycastCache[P]=z,z}}_bufferedCameraMercator(g,S){const P=ju(g);if(this._cameraRaycastCache[P])return this._cameraRaycastCache[P];{let z;return z=S.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(g),S):{polygon:this.bufferedCameraGeometry(g).map(H=>S.pointCoordinate3D(H)),unwrapped:!0},this._cameraRaycastCache[P]=z,z}}_projectAndResample(g,S){const P=function(H,G){const ee=o.aD([],G.pixelMatrix,G.globeMatrix),ie=[0,-o.aF,0,1],pe=[0,o.aF,0,1],ye=[0,0,0,1];o.aE(ie,ie,ee),o.aE(pe,pe,ee),o.aE(ye,ye,ee);const De=new o.P(ie[0]/ie[3],ie[1]/ie[3]),Ae=new o.P(pe[0]/pe[3],pe[1]/pe[3]),Be=o.aG(H,De)&&ie[3]1?vo(H.slice(0,ut),G):[],Tt=utnew o.P(hd(Wt.x),Wt.y)),Tt=Tt.map(Wt=>new o.P(hd(Wt.x),Wt.y));const ft=[...jt];ft.length===0&&ft.push(Tt[Tt.length-1]);const Kt=o.am(ft[ft.length-1].y,(Tt.length===0?jt[0]:Tt[0]).y,dt);let Rt;return Rt=Be?[new o.P(0,Kt),new o.P(0,0),new o.P(1,0),new o.P(1,Kt)]:[new o.P(1,Kt),new o.P(1,1),new o.P(0,1),new o.P(0,Kt)],ft.push(...Rt),Tt.length===0?ft.push(jt[0]):ft.push(...Tt),{polygon:ft.map(Wt=>new o.ag(Wt.x,Wt.y)),unwrapped:!1}}(g,S);if(P)return P;const z=function(H,G){let ee=!1,ie=-1/0,pe=0;for(let De=0;Deie&&(ie=H[De].x,pe=De);for(let De=0;De.5&&(Be.x{De.x-=1}),{polygon:H,unwrapped:ee}}(vo(g,S).map(H=>new o.P(hd(H.x),H.y)),S);return{polygon:z.polygon.map(H=>new o.ag(H.x,H.y)),unwrapped:z.unwrapped}}}function vo(M,g){return o.aI(M,S=>{const P=g.pointCoordinate3D(S);S.x=P.x,S.y=P.y},1/256)}function hd(M){return M<0?1+M%1:M%1}function ju(M){return 100*M|0}function sp(M,g,S){try{g=function(z){if(!z.variants)return z;if(!Array.isArray(z.variants))throw new Error("variants must be an array");for(const H of z.variants){if(H==null||typeof H!="object"||H.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(H.capabilities))throw new Error("capabilities must be an array");if(H.capabilities.length===1&&H.capabilities[0]==="meshopt")return Object.assign(z,H)}return z}(g)}catch(z){return new Error("Failed to process TileJSON variants",{cause:z})}const P=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&&(P.tiles=g.tiles),P.tiles=S.canonicalizeTileset(P,M.url),P}function Nu(M,g,S,P,z){const H=function(ee,ie){if(ee)return z(ee);if(ie){M.url&&ie.tiles&&M.tiles&&delete M.tiles;const pe=sp(M,ie,g);if(pe instanceof Error)return z(pe);z(null,pe)}},G=function(ee,ie,pe){if(!ee)return null;if(!ie&&!pe)return ee;pe=pe||ee.worldview_default;const ye=Object.values(ee.language||{});if(ye.length===0)return null;const De=Object.values(ee.worldview||{});if(De.length===0)return null;const Ae=ye.every(tt=>tt===ie),Be=De.every(tt=>tt===pe);return Ae&&Be?ee:ie in(ee.language_options||{})||pe in(ee.worldview_options||{})?null:ee.language_options&&ee.worldview_options?ee:null}(M.data,S,P);return G?o.o.frame(()=>H(null,G)):M.url?o.m(g.transformRequest(g.normalizeSourceURL(M.url,null,S,P),o.R.Source),H):o.o.frame(()=>{const{data:ee,...ie}=M;H(null,ie)})}function qh(M,g){const S=Math.pow(2,g.z),P=Math.floor(o.aH(M.getWest())*S),z=Math.floor(o.aL(M.getNorth())*S),H=Math.ceil(o.aH(M.getEast())*S),G=Math.ceil(o.aL(M.getSouth())*S);return g.x>=P&&g.x=z&&g.ythis.maxzoom||g.z{this._tileJSONRequest=null,this._loaded=!0,G?(S&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${S}`),P&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${P}`),this.fire(new o.B(G))):ee&&(this._setTileJSON(ee),Ee(ee.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(G)};this.provider=this._options.provider;const H=function(G){if("provider"in G&&!G.provider)return null;let ee=G.provider;if(!ee&&"url"in G&&G.url&&(ee=o.aM(G.url)),!ee)return null;const ie=o.g.TILE_PROVIDER_URLS[ee];if(!ie)return null;let pe;try{pe=new URL(ie,o.g.API_URL).href}catch{return o.w(`TileProvider "${ee}" has an invalid URL: "${ie}"`),null}return{name:ee,url:pe}}(this._options);if(this.provider&&!H)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(g&&g());this._tileJSONRequest=H?this._loadWithProvider(H,z):Nu(this._options,this.map._requestManager,S,P,z)}_loadWithProvider(g,S){this.provider=g.name;const P=new AbortController,z=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,H=z?Object.assign({},this._options,{url:z.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:g.name,url:g.url,source:this.id,scope:this.scope,type:this.type,options:H,request:z},(G,ee)=>{if(P.signal.aborted)return;if(G)return void S(G);const ie=ee?ee.find(pe=>pe!=null):null;if(ie){const pe=sp(this._options,ie,this.map._requestManager);pe instanceof Error?S(pe):S(null,pe)}else S(null,{tiles:this._options.tiles})}),{cancel:()=>{P.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 S of g.vector_layers)this.vectorLayerIds.push(S.id),g.worldview&&g.worldview[S.source]&&this.localizableLayerIds.add(S.id)}this.tileBounds=ku.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,S){const P=g.tileID.canonical.url(this.tiles,this.scheme),z=this.map._requestManager.normalizeTileURL(P),H=this.map._requestManager.transformRequest(z,o.R.Tile),G=this.map.style?this.map.style.getLut(this.scope):null,ee=G?{image:G.image.clone()}:null,ie={request:H,data:void 0,uid:g.uid,tileID:g.tileID,tileZoom:g.tileZoom,zoom:g.tileID.overscaledZ,maxZoom:this.maxzoom,lut:ee,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(P)&&(ie.localizableLayerIds=this.localizableLayerIds),ie.request.collectResourceTiming=this._collectResourceTiming,g.actor&&g.state!=="expired")g.state==="loading"?g.reloadCallback=S:g.request=g.actor.send("reloadTile",ie,pe.bind(this));else if(g.actor=this._tileWorkers[z]=this._tileWorkers[z]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)g.request=g.actor.send("loadTile",ie,pe.bind(this),void 0,!0);else{const ye=o.aO.call({deduped:this._deduped},ie,(De,Ae)=>{if(De||!Ae)pe.call(this,De);else{const Be=o.aP(Ae.responseHeaders);ie.data={rawData:Ae.rawData.slice(0),expires:Be.expires,cacheControl:Be.cacheControl},g.actor&&g.actor.send("loadTile",ie,pe.bind(this),void 0,!0)}},!0);g.request={cancel:ye}}function pe(ye,De){return delete g.request,g.aborted?S(null):ye?S(ye):(De&&De.resourceTiming&&(g.resourceTiming=De.resourceTiming),this.map._refreshExpiredTiles&&De&&g.setExpiryData(De),g.loadVectorData(De,this.map.painter),o.aQ(this.dispatcher),S(null,De),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,S){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 vv extends o.E{constructor(g,S,P,z){super(),this.id=g,this.dispatcher=P,this.setEventedParent(z),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"},S),Object.assign(this,o.aJ(S,["url","scheme","tileSize"]))}load(g){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const S=this.map.getWorldview();this._tileJSONRequest=Nu(this._options,this.map._requestManager,null,S,(P,z)=>{this._tileJSONRequest=null,this._loaded=!0,P?this.fire(new o.B(P)):z&&(Object.assign(this,z),z.raster_layers&&(this.rasterLayers=z.raster_layers,this.rasterLayerIds=this.rasterLayers.map(H=>H.id)),this.tileBounds=ku.fromTileJSON(z),Ee(z.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),g&&g(P)})}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,S){const P=o.o.devicePixelRatio>=2,z=this.map._requestManager.normalizeTileURL(g.tileID.canonical.url(this.tiles,this.scheme),P,this.tileSize);g.request=o.n(this.map._requestManager.transformRequest(z,o.R.Tile),(H,G,ee)=>{if(delete g.request,g.aborted)return g.state="unloaded",S(null);if(H)return g.state="errored",S(H);if(!G)return S(null);const ie=o.aP(ee);this.map._refreshExpiredTiles&&g.setExpiryData(ie),g.setTexture(G,this.map.painter),g.state="loaded",o.aQ(this.dispatcher),S(null)})}abortTile(g,S){g.request&&(g.request.cancel(),delete g.request),S&&S()}unloadTile(g,S){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(),S&&S()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function gw([M,g],S,P,{scaled:z=!0}={}){const{tileSize:H,buffer:G}=P,{x:ee,y:ie,z:pe}=S;if(!isFinite(ee)||!isFinite(ie)||!isFinite(pe))throw new Error("Invalid MRT header");const ye=2**pe,De=ye*o.aH(M),Ae=ye*o.aL(g);return function([Be,tt],Ye,{scaled:ut=!0}={}){if(!Ye)throw new Error("bandView is undefined");const{data:dt,tileSize:jt,buffer:Tt,offset:ft,scale:Kt,dimension:Rt}=Ye;if(Be<-Tt||Be>jt+Tt||tt<-Tt||tt>jt+Tt)throw new Error(`Point (${Be}, ${tt}) out of bounds for tileSize=${jt}, buffer=${Tt}`);const Wt=(tt+Tt)*(jt+2*Tt)+(Be+Tt);if(new Uint32Array(dt.buffer)[Wt]===4294967295)return null;let Et=[];Et=ut?[]:new Ye.data.constructor(Rt);for(let Lt=0;Lt{if(delete g.request,g.aborted)return g.state="unloaded",S(null);if(ee)return ee.name==="AbortError"?void 0:(g.state="errored",S(ee));if(this.map._refreshExpiredTiles&&ie){const ye=o.aP(pe);g.setExpiryData(ye)}if(this.partial&&g.state!=="expired")g.state="empty";else if(!this.partial){if(!ie)return S(null);g.state="loaded",g._isHeaderLoaded=!0,g._mrt=ie}S(null)};g.request=this.partial?g.fetchHeader(void 0,G.bind(this)):g.actor.send("loadTile",H,G.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,S){const P=g.texturePerLayer;if(g.flushAllQueues(),P.size){g.destroy(!1);for(const z of P.values())this.map.painter.saveTileTexture(z)}else g.destroy()}prepareTile(g,S,P,z){g._isHeaderLoaded&&(g.state!=="empty"&&(g.state="reloading"),g.fetchBandForRender(S,P,z,(H,G)=>{H?(g.state="errored",this.fire(new o.B(H))):G&&(g._isHeaderLoaded=!0,g.setTexturePerLayer(P,G,this.map.painter),g.state="loaded"),this.triggerRepaint(g)}))}getInitialBand(g){if(!this.rasterLayers)return 0;const S=this.rasterLayers.find(({id:H})=>H===g),P=S&&S.fields,z=P&&P.bands&&P.bands;return z?z[0]:0}getTextureDescriptor(g,S,P){if(!g)return;const z=S.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!z)return;let H=null;S instanceof o.aS?H=S.paint.get("raster-array-band"):S instanceof o.aT&&(H=S.paint.get("raster-particle-array-band"));const G=H||this.getInitialBand(z);if(G==null)return;if(!g.textureDescriptorPerLayer.get(S.id))return void this.prepareTile(g,z,S.id,G);if(g.updateNeeded(S.id,G)&&!P)return;const ee=g.textureDescriptorPerLayer.get(S.id);return Object.assign({},ee,{texture:g.texturePerLayer.get(S.id)})}getImages(g,S){const P=new Map;for(const z of g)for(const H of S){const[G,ee]=H.split("/"),ie=z.getLayer(G);if(!ie||!ie.hasBand(ee)||!ie.hasDataForBand(ee))continue;const{bytes:pe,tileSize:ye,buffer:De}=ie.getBandView(ee),Ae=ye+2*De,Be={data:new o.q({width:Ae,height:Ae},pe),pixelRatio:2,sdf:!1,usvg:!1,version:0};P.set(H,Be)}return P}queryRasterArrayValueByBandId(g,S,P){const z=S._mrt;return new Promise(H=>{const G={},ee=new Set;for(const[ie,pe]of Object.entries(z.layers)){if(P.layerName&&ie!==P.layerName)continue;const ye={};G[ie]=ye;for(const{bands:De}of pe.dataIndex)for(const Ae of De)P.bands&&!P.bands.includes(Ae)||(ee.add(o.F(ie,Ae)),S.fetchBand(ie,null,Ae,Be=>{o.o.frame(()=>{ye[Ae]=Be?null:gw([g.lng,g.lat],z,pe.getBandView(Ae)),ee.delete(o.F(ie,Ae)),ee.size===0&&H(G)})},!1))}ee.size===0&&H(G)})}_loadTileForQuery(g,S){if(this._loadTileLoaded[g.uid])return void S(null,g._mrt);if(this._loadTilePending[g.uid])return void this._loadTilePending[g.uid].push(S);this._loadTilePending[g.uid]=[S];const P=this.map._requestManager.normalizeTileURL(g.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),z=this.map._requestManager.transformRequest(P,o.R.Tile);g.actor.send("loadTile",{request:z,uid:g.uid,tileID:g.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(H,G,ee)=>{if(H)return this._loadTilePending[g.uid].forEach(ie=>ie(H,null)),void delete this._loadTilePending[g.uid];if(!G)return this._loadTilePending[g.uid].forEach(ie=>ie(null,null)),void delete this._loadTilePending[g.uid];if(this.map._refreshExpiredTiles&&G){const ie=o.aP(ee);g.setExpiryData(ie)}g._mrt=G,g._isHeaderLoaded=!0,g.state="loaded",this._loadTilePending[g.uid].forEach(ie=>ie(null,G)),this._loadTileLoaded[g.uid]=!0,delete this._loadTilePending[g.uid]},void 0,!0)}queryRasterArrayValueByAllBands(g,S,P){return new Promise((z,H)=>{this._loadTileForQuery(S,(G,ee)=>{G?H(G):z(ee?this.queryRasterArrayValueByBandId(g,S,P):null)})})}queryRasterArrayValue(g,S){const P=o.aU.convert(g),z=this.findLoadedParent(P);return z&&z._mrt?S.bands||!this.partial?this.queryRasterArrayValueByBandId(P,z,S):this.queryRasterArrayValueByAllBands(P,z,S):Promise.resolve(null)}findLoadedParent(g){const S=o.ag.fromLngLat(g,this.map.transform.tileSize),P=this.maxzoom+1,z=1<0&&(ee[new o.aR(M.overscaledZ,z,g.z,P,g.y-1).key]={backfilled:!1},ee[new o.aR(M.overscaledZ,M.wrap,g.z,g.x,g.y-1).key]={backfilled:!1},ee[new o.aR(M.overscaledZ,G,g.z,H,g.y-1).key]={backfilled:!1}),g.y+1{if(this._loaded=!0,this._pendingLoad=null,P)this.fire(new o.B(P));else{const H={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&z&&z.resourceTiming&&z.resourceTiming[this.id]&&(H.resourceTiming=z.resourceTiming[this.id]),M&&(this._partialReload=!0),this.fire(new o.C("data",H)),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 S=M.actor?"reloadTile":"loadTile";M.actor=this.actor;const P=this.map.style?this.map.style.getLut(this.scope):null,z=P?{image:P.image.clone()}:null,H=this._partialReload,G={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:z,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:H,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};M.request=this.actor.send(S,G,(ee,ie)=>H&&!ie?(M.state="loaded",g(null)):(delete M.request,M.destroy(!1),M.aborted?g(null):ee?g(ee):(M.loadVectorData(ie,this.map.painter,S==="reloadTile"),g(null))),void 0,S==="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,S,P){super(M,g,S,P),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,S)=>{this._loaded=!0,g?this.fire(new o.B(g)):S&&(this.video=S,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,S,P){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=S,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(P)}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,S=this.map.getWorldview();this._tileJSONRequest=Nu(this._options,this.map._requestManager,g,S,(P,z)=>{this._tileJSONRequest=null,this._loaded=!0,P?(g&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${g}`),S&&S.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${S}`),this.fire(new o.B(P))):z&&(Object.assign(this,z),z.bounds&&(this.tileBounds=new ku(z.bounds,this.minzoom,this.maxzoom)),Ee(z.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(P)})}hasTransition(){return!1}hasTile(M){return!this.tileBounds||this.tileBounds.contains(M.canonical)}loaded(){return this._loaded}loadTile(M,g){const S=this.map._requestManager.normalizeTileURL(M.tileID.canonical.url(this.tiles,this.scheme)),P={request:this.map._requestManager.transformRequest(S,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 H=Object.values(M.buckets);for(const G of H)G.dirty=!0;return void(M.state="loaded")}M.request=M.actor.send("reloadTile",P,z.bind(this))}else M.actor=this.dispatcher.getActor(),M.request=M.actor.send("loadTile",P,z.bind(this),void 0,!0);function z(H,G){return M.aborted?g(null):H&&H.status!==404?g(H):(this.map._refreshExpiredTiles&&G&&M.setExpiryData(G),M.loadModelData(G,this.map.painter),M.state="loaded",void g(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(M,g,S,P){super(M,g,S,P),g.coordinates?Array.isArray(g.coordinates)&&g.coordinates.length===4&&!g.coordinates.some(z=>!Array.isArray(z)||z.length!==2||z.some(H=>typeof H!="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,S,P){super(),this.id=M,this.type="custom",this._dataType="raster",this._dispatcher=S,this._implementation=g,this.setEventedParent(P),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 ku(this._implementation.bounds,this.minzoom,this.maxzoom));const z=g;z.update=this._update.bind(this),z.clearTiles=this._clearTiles.bind(this),z.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:S,z:P}=M.canonical;return this._implementation.hasTile({x:g,y:S,z:P})}return!this.tileBounds||this.tileBounds.contains(M.canonical)}loadTile(M,g){const{x:S,y:P,z}=M.tileID.canonical,H=new AbortController,G=Promise.resolve(this._implementation.loadTile({x:S,y:P,z},{signal:H.signal})).then((function(ee){return delete M.request,M.aborted?(M.state="unloaded",g(null)):ee===void 0?(M.state="errored",g(null)):ee===null?(this.loadTileData(M,{width:this.tileSize,height:this.tileSize,data:null}),M.state="loaded",g(null)):function(ie){return ie instanceof ImageData||ie instanceof HTMLCanvasElement||ie instanceof ImageBitmap||ie instanceof HTMLImageElement}(ee)?(this.loadTileData(M,ee),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(ee=>{ee.name!=="AbortError"&&(M.state="errored",g(ee))});G.cancel=()=>H.abort(),M.request=G}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:S,y:P,z}=M.tileID.canonical;this._implementation.unloadTile({x:S,y:P,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"}))}}},Y0=function(M,g,S,P){const z=new K0[g.type](M,g,S,P);if(z.id!==M)throw new Error(`Expected Source id to be ${M} instead of ${z.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],z),z};function rp(M,g,S=""){return`${S}:${g.id||""}:${g.layer.id}:${function(P){if("layerId"in P)return`layer:${P.layerId}`;{const{featuresetId:z,importId:H}=P;return`featureset:${z}${H?`:import:${H}`:""}`}}(M.target)}`}function Xu(M,g,S,P=""){if(M.uniqueFeatureID){const z=rp(M,g,P);if(S.has(z))return!0;S.add(z)}return!1}function Bp(M,g,S,P,z=!1,H=void 0){const G=g.sourceCache.transform,ee=g.sourceCache.tilesIn(M,g.has3DLayers,z);ee.sort(Hh);const ie=[];for(const pe of ee){const ye=pe.tile.queryRenderedFeatures(g,pe,S,P,G,z,H);Object.keys(ye).length&&ie.push({wrappedTileID:pe.tile.tileID.wrapped().key,queryResults:ye})}for(const pe in g.layers){const ye=g.layers[pe];if(ye.styleLayer){const De=ye.styleLayer.queryRenderedFeatures(M,g.sourceCache,P);Object.keys(De).length&&ie.push({wrappedTileID:0,queryResults:De})}}return ie.length===0?{}:function(pe){const ye={},De={};for(const Ae of pe){const Be=Ae.queryResults,tt=Ae.wrappedTileID,Ye=De[tt]=De[tt]||{};for(const ut in Be){const dt=Be[ut],jt=Ye[ut]=Ye[ut]||{},Tt=ye[ut]=ye[ut]||[];for(const ft of dt)jt[ft.featureIndex]||(jt[ft.featureIndex]=!0,Tt.push(ft))}}return ye}(ie)}function co(M,g,S,P,z,H){const G={},ee=P.queryRenderedSymbols(M),ie=[];for(const pe of Object.keys(ee).map(Number))ie.push(z[pe]);ie.sort(Hh);for(const pe of ie){const ye=pe.featureIndex.lookupSymbolFeatures(ee[pe.bucketInstanceId],pe.bucketIndex,pe.sourceLayerIndex,g,S,H);for(const De in ye){const Ae=G[De]=G[De]||[],Be=ye[De];Be.sort((tt,Ye)=>{const ut=pe.featureSortOrder;if(ut){const dt=ut.indexOf(tt.featureIndex);return ut.indexOf(Ye.featureIndex)-dt}return Ye.featureIndex-tt.featureIndex});for(const tt of Be)Ae.push(tt)}}return G}function X1(M,g){const S=M.getRenderableIds().map(H=>M.getTileByID(H)),P=[],z={};for(let H=0;H{if(H)S(H);else try{const ie=P.getHeaderLength(G);if(ie>g)return void(this.request=this.fetchHeader(ie,S));P.parseHeader(G),this._isHeaderLoaded=!0;let pe=0;for(const ye of Object.values(P.layers))pe=Math.max(pe,ye.dataIndex[ye.dataIndex.length-1].lastByte);G.byteLength>=pe&&(this.entireBuffer=G),S(null,this.entireBuffer||G,ee)}catch(ie){S(ie)}}),this.request}fetchBandForRender(g,S,P,z){this.fetchBand(g,S,P,H=>{if(H)return void z(H);this.updateTextureDescriptor(g,S,P);const G=this.textureDescriptorPerLayer.get(S);z(null,G?G.img:null)})}fetchBand(g,S,P,z,H=!0){const G=this._mrt;if(!this._isHeaderLoaded||!G)return void z(new Error("Tile header is not ready"));const ee=this.actor;if(!ee)return void z(new Error("Can't fetch tile band without an actor"));let ie;const pe=o.F(String(P),o.F(this.tileID.key,g));let ye=this._taskQueue.get(pe);ye?ye.add(z):(ye=new Set,ye.add(z),this._taskQueue.set(pe,ye));const De=(Ye,ut)=>{ie.complete(Ye,ut),Ye?z(Ye):(ye.forEach(dt=>dt(null,ut)),this._taskQueue.delete(pe))},Ae=(Ye,ut)=>{if(Ye)return z(Ye);const dt=ee.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:ut,task:ie},De,void 0,!0);if(S!==null){const jt=this._workQueuePerLayer.get(S)||[];jt.push(()=>{dt&&dt.cancel(),ie.cancel()}),this._workQueuePerLayer.has(S)||this._workQueuePerLayer.set(S,jt)}};let Be;try{Be=G.getLayer(g)}catch(Ye){if(this.state==="reloading")return;throw Ye}if(!Be)return void z(new Error(`Unknown sourceLayer "${g}"`));if(Be.hasDataForBand(P))return ye.forEach(Ye=>Ye(null,null)),void this._taskQueue.delete(pe);const tt=Be.getDataRange([P]);if(ie=G.createDecodingTask(tt),!ie||ie.tasks.length)if(S!==null&&this.flushQueues(S),this.entireBuffer)Ae(null,this.entireBuffer.slice(tt.firstByte,tt.lastByte+1));else{const Ye=Object.assign({},this.requestParams,{headers:{Range:`bytes=${tt.firstByte}-${tt.lastByte}`}}),ut=o.b1(Ye,Ae);if(S!==null){const dt=this._fetchQueuePerLayer.get(S)||[];dt.push(()=>{ut.cancel(),ie.cancel()}),this._fetchQueuePerLayer.has(S)||this._fetchQueuePerLayer.set(S,dt)}}}updateNeeded(g,S){return(!this.textureDescriptorPerLayer.get(g)||this.textureDescriptorPerLayer.get(g).band!==S||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(g,S,P){if(!this._mrt)return;const z=this._mrt.getLayer(g);if(!z||!z.hasBand(P)||!z.hasDataForBand(P))return;const{bytes:H,tileSize:G,buffer:ee,offset:ie,scale:pe}=z.getBandView(P),ye=G+2*ee,De=new o.q({width:ye,height:ye},H),Ae=this.texturePerLayer.get(S);Ae&&Ae instanceof o.T&&Ae.update(De,{premultiply:!1}),this.textureDescriptorPerLayer.set(S,{layer:g,band:P,img:De,buffer:ee,offset:ie,tileSize:G,format:z.pixelFormat,mix:[pe,256*pe,65536*pe,16777216*pe]})}destroy(g=!1){if(super.destroy(g),delete this._mrt,!g)for(const S of this.texturePerLayer.values())S&&S instanceof o.T&&S.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 $p{constructor(g,S){this.max=g,this.onRemove=S,this.reset()}reset(){for(const g in this.data)for(const S of this.data[g])S.timeout&&clearTimeout(S.timeout),this.onRemove(S.value);return this.data={},this.order=[],this}add(g,S,P){const z=g.wrapped().key;this.data[z]===void 0&&(this.data[z]=[]);const H={value:S,timeout:void 0};if(P!==void 0&&(H.timeout=setTimeout(()=>{this.remove(g,H)},P)),this.data[z].push(H),this.order.push(z),this.order.length>this.max){const G=this._getAndRemoveByKey(this.order[0]);G&&this.onRemove(G)}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 S=this.data[g].shift();return S.timeout&&clearTimeout(S.timeout),this.data[g].length===0&&delete this.data[g],this.order.splice(this.order.indexOf(g),1),S.value}getByKey(g){const S=this.data[g];return S?S[0].value:null}get(g){return this.has(g)?this.data[g.wrapped().key][0].value:null}remove(g,S){if(!this.has(g))return this;const P=g.wrapped().key,z=S===void 0?0:this.data[P].indexOf(S),H=this.data[P][z];return this.data[P].splice(z,1),H.timeout&&clearTimeout(H.timeout),this.data[P].length===0&&delete this.data[P],this.onRemove(H.value),this.order.splice(this.order.indexOf(P),1),this}setMaxSize(g){for(this.max=g;this.order.length>this.max;){const S=this._getAndRemoveByKey(this.order[0]);S&&this.onRemove(S)}return this}filter(g){const S=[];for(const P in this.data)for(const z of this.data[P])g(z.value)||S.push(z);for(const P of S)this.remove(P.value.tileID,P)}}class Su{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(g,S,P){const z=String(S);if(this.stateChanges[g]=this.stateChanges[g]||{},this.stateChanges[g][z]=this.stateChanges[g][z]||{},Object.assign(this.stateChanges[g][z],P),this.deletedStates[g]===null){this.deletedStates[g]={};for(const H in this.state[g])H!==z&&(this.deletedStates[g][H]=null)}else if(this.deletedStates[g]&&this.deletedStates[g][z]===null){this.deletedStates[g][z]={};for(const H in this.state[g][z])P[H]||(this.deletedStates[g][z][H]=null)}else for(const H in P)this.deletedStates[g]&&this.deletedStates[g][z]&&this.deletedStates[g][z][H]===null&&delete this.deletedStates[g][z][H]}removeFeatureState(g,S,P){if(this.deletedStates[g]===null)return;const z=String(S);if(this.deletedStates[g]=this.deletedStates[g]||{},P&&S!==void 0)this.deletedStates[g][z]!==null&&(this.deletedStates[g][z]=this.deletedStates[g][z]||{},this.deletedStates[g][z][P]=null);else if(S!==void 0)if(this.stateChanges[g]&&this.stateChanges[g][z])for(P in this.deletedStates[g][z]={},this.stateChanges[g][z])this.deletedStates[g][z][P]=null;else this.deletedStates[g][z]=null;else this.deletedStates[g]=null}getState(g,S){const P=this.state[g]||{},z=this.stateChanges[g]||{},H=this.deletedStates[g];if(H===null)return{};if(S!==void 0){const ee=String(S),ie=Object.assign({},P[ee],z[ee]);if(H){const pe=H[S];if(pe===null)return{};for(const ye in pe)delete ie[ye]}return ie}const G=Object.assign({},P,z);if(H)for(const ee in H)delete G[ee];return G}initializeTileState(g,S){g.refreshFeatureState(S)}coalesceChanges(g,S){const P={};for(const z in this.stateChanges){this.state[z]=this.state[z]||{};const H={};for(const G in this.stateChanges[z])this.state[z][G]||(this.state[z][G]={}),Object.assign(this.state[z][G],this.stateChanges[z][G]),H[G]=this.state[z][G];P[z]=H}for(const z in this.deletedStates){this.state[z]=this.state[z]||{};const H={};if(this.deletedStates[z]===null)for(const G in this.state[z])H[G]={},this.state[z][G]={};else for(const G in this.deletedStates[z]){if(this.deletedStates[z][G]===null)this.state[z][G]={};else if(this.state[z][G])for(const ee of Object.keys(this.deletedStates[z][G]))delete this.state[z][G][ee];H[G]=this.state[z][G]}P[z]=P[z]||{},Object.assign(P[z],H)}if(this.stateChanges={},this.deletedStates={},Object.keys(P).length!==0)for(const z in g)g[z].refreshFeatureState(S,P)}}class Xo extends o.E{constructor(g,S,P){super(),this.id=g,this._renderSourceType=P,this._maxzoomOverride=null,S.on("data",z=>{z.dataType==="source"&&z.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&z.dataType==="source"&&z.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),S.on("error",()=>{this._sourceErrored=!0}),this._source=S,this._tiles={},this._cache=new $p(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=S.minTileCacheSize,this._maxTileCacheSize=S.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Su,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,S){return g.renderSourceType=this._renderSourceType,g.isExtraShadowCaster=this._shadowCasterTiles[g.tileID.key],this._source.loadTile(g,S)}_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 S in this._tiles){const P=this._tiles[S];P.upload(g,this.map?this.map.painter:void 0),P.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(Pg).map(g=>g.key)}getRenderableIds(g,S){const P=[];for(const z in this._tiles)this._isIdRenderable(+z,g,S)&&P.push(this._tiles[z]);return g?P.sort((z,H)=>{const G=z.tileID,ee=H.tileID,ie=new o.P(G.canonical.x,G.canonical.y)._rotate(this.transform.angle),pe=new o.P(ee.canonical.x,ee.canonical.y)._rotate(this.transform.angle);return G.overscaledZ-ee.overscaledZ||pe.y-ie.y||pe.x-ie.x}).map(z=>z.tileID.key):P.map(z=>z.tileID).sort(Pg).map(z=>z.key)}hasRenderableParent(g){const S=this.findLoadedParent(g,0);return!!S&&this._isIdRenderable(S.tileID.key)}_isIdRenderable(g,S,P){return this._tiles[g]&&this._tiles[g].hasData()&&!this._coveredTiles[g]&&(S||!this._tiles[g].holdingForFade())&&(P||!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,S){const P=this._tiles[g];P&&(P.state!=="loading"&&(P.state=S),this._loadTile(P,this._tileLoaded.bind(this,P,g,S)))}_tileLoaded(g,S,P,z,H){if(z){if(g.state="errored",o.b2(z)){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 ee=this.map.painter.terrain;this.update(this.transform,ee.getScaledDemTileSize(),!0),ee.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(z,{tile:g}));return}g.timeAdded=o.o.now(),P==="expired"&&(g.refreshedUponExpiration=!0),this._setTileReloadTimer(S,g),this._source.type==="raster-dem"&&g.dem&&this._backfillDEM(g),this._state.initializeTileState(g,this.map?this.map.painter:null);let G=new Map;H&&H.responseHeaders&&(G=H.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:g,coord:g.tileID,sourceCacheId:this.id,responseHeaders:G}))}_hasTunnelGeometry(){for(const g in this._tiles){const S=this._tiles[g];if(S&&S.hasTunnelGeometry)return!0}return!1}_backfillDEM(g){const S=this.getRenderableIds();for(let z=0;z1||(Math.abs(G)>1&&(Math.abs(G+ie)===1?G+=ie:Math.abs(G-ie)===1&&(G-=ie)),H.dem&&z.dem&&(z.dem.backfillBorder(H.dem,G,ee),z.neighboringTiles&&z.neighboringTiles[pe]&&(z.neighboringTiles[pe].backfilled=!0)))}}getTile(g){return this.getTileByID(g.key)}getTileByID(g){return this._tiles[g]}_retainLoadedChildren(g,S,P,z){for(const H in this._tiles){let G=this._tiles[H];if(z[H]||!G.hasData()||G.tileID.overscaledZ<=S||G.tileID.overscaledZ>P)continue;let ee=G.tileID;for(;G&&G.tileID.overscaledZ>S+1;){const pe=G.tileID.scaledTo(G.tileID.overscaledZ-1);G=this._tiles[pe.key],G&&G.hasData()&&(ee=pe)}let ie=ee;for(;ie.overscaledZ>S;)if(ie=ie.scaledTo(ie.overscaledZ-1),g[ie.key]){z[ee.key]=ee;break}}}findLoadedParent(g,S){if(g.key in this._loadedParentTiles){const P=this._loadedParentTiles[g.key];return P&&P.tileID.overscaledZ>=S?P:null}for(let P=g.overscaledZ-1;P>=S;P--){const z=g.scaledTo(P),H=this._getLoadedTile(z);if(H)return H}}_getLoadedTile(g){const S=this._tiles[g.key];return S&&S.hasData()?S:this._cache.getByKey(this._source.reparseOverscaled?g.wrapped().key:g.canonical.key)}updateCacheSize(g,S){S=S||this._source.tileSize;const P=Math.ceil(g.width/S)+1,z=Math.ceil(g.height/S)+1,H=Math.floor(P*z*5),G=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,H):H,ee=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,G):G;this._cache.setMaxSize(ee)}handleWrapJump(g){const S=Math.round((g-(this._prevLng===void 0?g:this._prevLng))/360);if(this._prevLng=g,S){const P={};for(const z in this._tiles){const H=this._tiles[z];H.tileID=H.tileID.unwrapTo(H.tileID.wrap+S),P[H.tileID.key]=H}this._tiles=P;for(const z in this._timers)clearTimeout(this._timers[z]),delete this._timers[z];for(const z in this._tiles)this._setTileReloadTimer(+z,this._tiles[z])}}update(g,S,P,z,H){if(this.transform=g,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!P)return;this.updateCacheSize(g,S),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const G=this._source.type==="batched-model";let ee,ie=this._source.maxzoom;this._maxzoomOverride!==null&&(ie=Math.min(ie,this._maxzoomOverride));const pe=this.map&&this.map.painter?this.map.painter._terrain:null;if(pe&&pe.sourceCache===this&&pe.attenuationRange()){const Be=pe.attenuationRange()[0],tt=Math.floor(Be)-Math.log2(pe.getDemUpscale());ie>tt&&(ie=tt)}const ye=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)ee=g.getVisibleUnwrappedCoordinates(this._source.tileID).map(Be=>new o.aR(Be.canonical.z,Be.wrap,Be.canonical.z,Be.canonical.x,Be.canonical.y));else if(this.tileCoverLift!==0){const Be=g.clone();Be.tileCoverLift=this.tileCoverLift,ee=Be.coveringTiles({tileSize:S||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ie,roundZoom:this._source.roundZoom&&!P,reparseOverscaled:ye,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:G}),this._source.minzoom<=1&&g.projection.name==="globe"&&(ee.push(new o.aR(1,0,1,0,0)),ee.push(new o.aR(1,0,1,1,0)),ee.push(new o.aR(1,0,1,0,1)),ee.push(new o.aR(1,0,1,1,1)))}else if(ee=g.coveringTiles({tileSize:S||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ie,roundZoom:this._source.roundZoom&&!P,reparseOverscaled:ye,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:G}),this._source.hasTile){const Be=this._source.hasTile.bind(this._source);ee=ee.filter(tt=>Be(tt))}}else ee=[];if(ee.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const Be=g.coveringZoomLevel({tileSize:S||this._source.tileSize,roundZoom:this._source.roundZoom&&!P}),tt=Math.min(Be,ie);if(G){const Ye=g.extendTileCover(ee,tt);for(const ut of Ye)ee.push(ut)}else if(H){const Ye=this.transform.getFrustum(tt),ut=g.extendTileCoverToNearPlane(ee,Ye,tt);for(const dt of ut)ee.push(dt);if(tt>=18&&this._hasTunnelGeometry()){const dt=g.extendTileCoverForTunnels(ee,Ye,tt,20);for(const jt of dt)ee.push(jt)}}else if(this.castsShadows&&z){const Ye=g.extendTileCover(ee,tt,z,16);for(const ut of Ye)this._shadowCasterTiles[ut.key]=!0,ee.push(ut)}}const De=this._updateRetainedTiles(ee);if(this._supportsFading&&ee.length!==0){const Be={},tt={},Ye=o.o.now(),ut=Object.keys(De);for(const jt of ut){const Tt=De[jt],ft=this._tiles[jt];if(!ft||ft.fadeEndTime!==void 0&&ft.fadeEndTime<=Ye)continue;const Kt=this.findLoadedParent(Tt,Math.max(Tt.overscaledZ-Xo.maxOverzooming,this._source.minzoom));Kt&&(this._addTile(Kt.tileID),Be[Kt.tileID.key]=Kt.tileID),tt[jt]=Tt}const dt=ee[ee.length-1].overscaledZ;for(const jt in this._tiles){const Tt=this._tiles[jt];if(De[jt]||!Tt.hasData())continue;let ft=Tt.tileID;for(;ft.overscaledZ>dt;){ft=ft.scaledTo(ft.overscaledZ-1);const Kt=this._tiles[ft.key];if(Kt&&Kt.hasData()&&tt[ft.key]){De[jt]=Tt.tileID;break}}}for(const jt in Be)De[jt]||(this._coveredTiles[jt]=!0,De[jt]=Be[jt])}for(const Be in De)this._tiles[Be].clearFadeHold();const Ae=o.b3(this._tiles,De);for(const Be of Ae){const tt=this._tiles[Be];tt.hasSymbolBuckets&&!tt.holdingForFade()?tt.setHoldDuration(this.map._fadeDuration):tt.hasSymbolBuckets&&!tt.symbolFadeFinished()||this._removeTile(+Be)}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 S={};if(g.length===0)return S;const P={},z=g.reduce((pe,ye)=>Math.min(pe,ye.overscaledZ),1/0),H=g[0].overscaledZ,G=Math.max(H-Xo.maxOverzooming,this._source.minzoom),ee=Math.max(H+Xo.maxUnderzooming,this._source.minzoom),ie={};for(const pe of g){const ye=this._addTile(pe);S[pe.key]=pe,ye.hasData()||z=this._source.maxzoom){const Ae=pe.children(this._source.maxzoom)[0],Be=this.getTile(Ae);if(Be&&Be.hasData()){S[Ae.key]=Ae;continue}}else{const Ae=pe.children(this._source.maxzoom);if(S[Ae[0].key]&&S[Ae[1].key]&&S[Ae[2].key]&&S[Ae[3].key])continue}let De=ye.wasRequested();for(let Ae=pe.overscaledZ-1;Ae>=G;--Ae){const Be=pe.scaledTo(Ae);if(P[Be.key]||(P[Be.key]=!0,ye=this.getTile(Be),!ye&&De&&(ye=this._addTile(Be)),ye&&(S[Be.key]=Be,De=ye.wasRequested(),ye.hasData())))break}}return S}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const g in this._tiles){const S=[];let P,z=this._tiles[g].tileID;for(;z.overscaledZ>0;){if(z.key in this._loadedParentTiles){P=this._loadedParentTiles[z.key];break}S.push(z.key);const H=z.scaledTo(z.overscaledZ-1);if(P=this._getLoadedTile(H),P)break;z=H}for(const H of S)this._loadedParentTiles[H]=P}}_addTile(g){let S=this._tiles[g.key];if(S)return S.isExtraShadowCaster!==!0||this._shadowCasterTiles[g.key]||this._reloadTile(g.key,"reloading"),S;S=this._cache.getAndRemove(g),S&&(this._setTileReloadTimer(g.key,S),S.tileID=g,this._state.initializeTileState(S,this.map?this.map.painter:null),this._cacheTimers[g.key]&&(clearTimeout(this._cacheTimers[g.key]),delete this._cacheTimers[g.key],this._setTileReloadTimer(g.key,S)));const P=!!S;if(!P){const z=this.map?this.map.painter:null,H=this._source.tileSize*g.overscaleFactor();S=this._source.type==="raster-array"?new vh(g,H,this.transform.tileZoom,z,this._isRaster):new o.b0(g,H,this.transform.tileZoom,z,this._isRaster,this._source.worldview),this._loadTile(S,this._tileLoaded.bind(this,S,g.key,S.state))}return S.uses++,this._tiles[g.key]=S,P||this._source.fire(new o.C("dataloading",{tile:S,coord:S.tileID,dataType:"source"})),S}_setTileReloadTimer(g,S){g in this._timers&&(clearTimeout(this._timers[g]),delete this._timers[g]);const P=S.getExpiryTimeout();P&&(this._timers[g]=setTimeout(()=>{this._reloadTile(g,"expired"),delete this._timers[g]},P))}_removeTile(g){const S=this._tiles[g];S&&(S.uses--,delete this._tiles[g],this._timers[g]&&(clearTimeout(this._timers[g]),delete this._timers[g]),S.uses>0||(S.hasData()&&S.state!=="reloading"||S.state==="empty"?this._cache.add(S.tileID,S,S.getExpiryTimeout()):(S.aborted=!0,this._abortTile(S),this._unloadTile(S))))}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,S,P){const z=[],H=this.transform;if(!H)return z;const G=H.projection.name==="globe",ee=o.aH(H.center.lng);for(const ie in this._tiles){const pe=this._tiles[ie];if(P&&pe.clearQueryDebugViz(),pe.holdingForFade())continue;let ye;if(G){const De=pe.tileID.canonical;if(De.z===0){const Ae=[Math.abs(o.aC(ee,...Xd(De,-1))-ee),Math.abs(o.aC(ee,...Xd(De,1))-ee)];ye=[0,2*Ae.indexOf(Math.min(...Ae))-1]}else{const Ae=[Math.abs(o.aC(ee,...Xd(De,-1))-ee),Math.abs(o.aC(ee,...Xd(De,0))-ee),Math.abs(o.aC(ee,...Xd(De,1))-ee)];ye=[Ae.indexOf(Math.min(...Ae))-1]}}else ye=[0];for(const De of ye){const Ae=g.containsTile(pe,H,S,De);Ae&&z.push(Ae)}}return z}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(g){return this._getRenderableCoordinates(g)}_getRenderableCoordinates(g,S){const P=this.getRenderableIds(g,S).map(H=>this._tiles[H].tileID),z=this.transform.projection.name==="globe";for(const H of P)H.projMatrix=this.transform.calculateProjMatrix(H.toUnwrapped()),H.expandedProjMatrix=z?this.transform.calculateProjMatrix(H.toUnwrapped(),!1,!0):H.projMatrix;return P}sortCoordinatesByDistance(g){const S=g.slice(),P=this.transform._camera.position,z=this.transform._camera.forward(),H={};for(const G of S){const ee=1/(1<H[G.key]-H[ee.key]),S}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const g=o.o.now();for(const S in this._tiles){const P=this._tiles[S];if(P.fadeEndTime!==void 0&&P.fadeEndTime>=g)return!0}}return!1}setFeatureState(g,S,P){this._state.updateState(g=g||"_geojsonTileLayer",S,P)}removeFeatureState(g,S,P){this._state.removeFeatureState(g=g||"_geojsonTileLayer",S,P)}getFeatureState(g,S){return this._state.getState(g=g||"_geojsonTileLayer",S)}setDependencies(g,S,P){const z=this._tiles[g];z&&z.setDependencies(S,P)}reloadTilesForDependencies(g,S){for(const P in this._tiles)this._tiles[P].hasDependency(g,S)&&this._reloadTile(+P,"reloading");this._cache.filter(P=>!P.hasDependency(g,S))}_preloadTiles(g,S){if(!this._sourceLoaded){const ie=()=>{this._sourceLoaded&&(this._source.off("data",ie),this._preloadTiles(g,S))};return void this._source.on("data",ie)}const P=new Map,z=Array.isArray(g)?g:[g],H=this.map.painter.terrain,G=this.usedForTerrain&&H?H.getScaledDemTileSize():this._source.tileSize;for(const ie of z){const pe=ie.coveringTiles({tileSize:G,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const ye of pe)P.set(ye.key,ye);this.usedForTerrain&&ie.updateElevation(!1)}const ee=Array.from(P.values());o.t(ee,(ie,pe)=>{const ye=new o.b0(ie,this._source.tileSize*ie.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(ye,De=>{this._source.type==="raster-dem"&&ye.dem&&this._backfillDEM(ye),pe(De,ye)})},S)}}function Pg(M,g){const S=Math.abs(2*M.wrap)-+(M.wrap<0),P=Math.abs(2*g.wrap)-+(g.wrap<0);return M.overscaledZ-g.overscaledZ||P-S||g.canonical.y-M.canonical.y||g.canonical.x-M.canonical.x}function Xd(M,g){const S=1<0:P.type==="building"?z=!P.isHidden(g)&&P.paint.get("building-opacity")>0:P.type==="model"&&(z=!P.isHidden(g)&&P.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!z&&S.visible,S.visible=z}}updateZOffset(g,S){this.currentBuildingBuckets=[];for(const z of this.layers){const H=z.layer,G=this.style.getLayerSourceCache(H);let ee=1;H.type==="fill-extrusion"?ee=z.visible?H.paint.get("fill-extrusion-vertical-scale"):0:H.type==="building"&&(ee=z.visible?H.paint.get("building-vertical-scale"):0);let ie=G?G.getTile(S):null;if(!ie&&G)for(const pe in G._tiles){const ye=G._tiles[pe];if(S.canonical.isChildOf(ye.tileID.canonical)){ie=ye;break}}this.currentBuildingBuckets.push({bucket:ie?ie.getBucket(H):null,tileID:ie?ie.tileID:S,verticalScale:ee})}g.hasAnyZOffset=!1;let P=!1;for(let z=0;z{P in g&&(S[P]=g[P])}),S}function np(M){M=M.slice();const g=Object.create(null);for(const S of M)g[S.id]=S;for(let S=0;S0?(z-G)/ee:0;return this.points[H].mult(1-ie).add(this.points[S].mult(ie))}}class Q0{constructor(g,S,P){const z=this.boxCells=[],H=this.circleCells=[];this.xCellCount=Math.ceil(g/P),this.yCellCount=Math.ceil(S/P);for(let G=0;Gthis.width||z<0||S>this.height)return!H&&[];const ee=[];if(g<=0&&S<=0&&this.width<=P&&this.height<=z){if(H)return!0;for(let ie=0;ie0:ee}_queryCircle(g,S,P,z,H){const G=g-P,ee=g+P,ie=S-P,pe=S+P;if(ee<0||G>this.width||pe<0||ie>this.height)return!z&&[];const ye=[];return this._forEachCell(G,ie,ee,pe,this._queryCellCircle,ye,{hitTest:z,circle:{x:g,y:S,radius:P},seenUids:{box:{},circle:{}}},H),z?ye.length>0:ye}query(g,S,P,z,H){return this._query(g,S,P,z,!1,H)}hitTest(g,S,P,z,H){return this._query(g,S,P,z,!0,H)}hitTestCircle(g,S,P,z){return this._queryCircle(g,S,P,!0,z)}_queryCell(g,S,P,z,H,G,ee,ie){const pe=ee.seenUids,ye=this.boxCells[H];if(ye!==null){const Ae=this.bboxes;for(const Be of ye)if(!pe.box[Be]){pe.box[Be]=!0;const tt=4*Be;if(g<=Ae[tt+2]&&S<=Ae[tt+3]&&P>=Ae[tt+0]&&z>=Ae[tt+1]&&(!ie||ie(this.boxKeys[Be]))){if(ee.hitTest)return G.push(!0),!0;G.push({key:this.boxKeys[Be],x1:Ae[tt],y1:Ae[tt+1],x2:Ae[tt+2],y2:Ae[tt+3]})}}}const De=this.circleCells[H];if(De!==null){const Ae=this.circles;for(const Be of De)if(!pe.circle[Be]){pe.circle[Be]=!0;const tt=3*Be;if(this._circleAndRectCollide(Ae[tt],Ae[tt+1],Ae[tt+2],g,S,P,z)&&(!ie||ie(this.circleKeys[Be]))){if(ee.hitTest)return G.push(!0),!0;{const Ye=Ae[tt],ut=Ae[tt+1],dt=Ae[tt+2];G.push({key:this.circleKeys[Be],x1:Ye-dt,y1:ut-dt,x2:Ye+dt,y2:ut+dt})}}}}}_queryCellCircle(g,S,P,z,H,G,ee,ie){const pe=ee.circle,ye=ee.seenUids,De=this.boxCells[H];if(De!==null){const Be=this.bboxes;for(const tt of De)if(!ye.box[tt]){ye.box[tt]=!0;const Ye=4*tt;if(this._circleAndRectCollide(pe.x,pe.y,pe.radius,Be[Ye+0],Be[Ye+1],Be[Ye+2],Be[Ye+3])&&(!ie||ie(this.boxKeys[tt])))return G.push(!0),!0}}const Ae=this.circleCells[H];if(Ae!==null){const Be=this.circles;for(const tt of Ae)if(!ye.circle[tt]){ye.circle[tt]=!0;const Ye=3*tt;if(this._circlesCollide(Be[Ye],Be[Ye+1],Be[Ye+2],pe.x,pe.y,pe.radius)&&(!ie||ie(this.circleKeys[tt])))return G.push(!0),!0}}}_forEachCell(g,S,P,z,H,G,ee,ie){const pe=this._convertToXCellCoord(g),ye=this._convertToYCellCoord(S),De=this._convertToXCellCoord(P),Ae=this._convertToYCellCoord(z);for(let Be=pe;Be<=De;Be++)for(let tt=ye;tt<=Ae;tt++)if(H.call(this,g,S,P,z,this.xCellCount*tt+Be,G,ee,ie))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,S,P,z,H,G){const ee=z-g,ie=H-S,pe=P+G;return pe*pe>ee*ee+ie*ie}_circleAndRectCollide(g,S,P,z,H,G,ee){const ie=(G-z)/2,pe=Math.abs(g-(z+ie));if(pe>ie+P)return!1;const ye=(ee-H)/2,De=Math.abs(S-(H+ye));if(De>ye+P)return!1;if(pe<=ie||De<=ye)return!0;const Ae=pe-ie,Be=De-ye;return Ae*Ae+Be*Be<=P*P}}const J1=Math.tan(85*Math.PI/180);function md(M,g,S,P,z,H,G){const ee=o.bb();if(S)if(H.name==="globe"){const ie=o.bc(z,g);o.aD(ee,ee,ie)}else{const ie=o.bd([],G);ee[0]=ie[0],ee[1]=ie[1],ee[4]=ie[2],ee[5]=ie[3],P||o.ba(ee,ee,z.angle)}else o.aD(ee,z.labelPlaneMatrix,M);return ee}function _c(M,g,S,P,z,H,G){const ee=md(M,g,S,P,z,H,G);return H.name==="globe"&&S||(ee[2]=ee[6]=ee[10]=ee[14]=0),ee}function Lm(M,g,S,P,z,H,G){if(S){if(H.name==="globe"){const ee=md(M,g,S,P,z,H,G);return o.b7(ee,ee),o.aD(ee,M,ee),ee}{const ee=o.b8(M),ie=o.b9([]);return ie[0]=G[0],ie[1]=G[1],ie[4]=G[2],ie[5]=G[3],o.aD(ee,ee,ie),P||o.ba(ee,ee,-z.angle),ee}}return z.glCoordMatrix}function Mc(M,g,S,P){const z=[M,g,S,1];S?o.aE(z,z,P):An(z,z,P);const H=z[3];return z[0]/=H,z[1]/=H,z[2]/=H,z}function Dm(M,g){return Math.min(.5+M/g*.5,1.5)}function xf(M,g){const S=M[0]/M[3],P=M[1]/M[3];return S>=-g[0]&&S<=g[0]&&P>=-g[1]&&P<=g[1]}function It(M,g,S,P,z,H,G,ee,ie,pe,ye=1){const De=S.transform,Ae=P?M.textSizeData:M.iconSizeData,Be=o.bj(Ae,S.transform.zoom,ye),tt=De.projection.name==="globe",Ye=[256/S.width*2+1,256/S.height*2+1],ut=P?M.text.dynamicLayoutVertexArray:M.icon.dynamicLayoutVertexArray;ut.clear();let dt=null;tt&&(dt=P?M.text.globeExtVertexArray:M.icon.globeExtVertexArray);const jt=M.lineVertexArray,Tt=P?M.text.placedSymbolArray:M.icon.placedSymbolArray,ft=S.transform.width/S.transform.height;let Kt,Rt=!1;for(let Wt=0;WtMath.abs(S)?{useVertical:!0}:M===o.bk.vertical?P>0?{needsFlipping:!0}:null:g!==0&&function(z,H){return z===0||Math.abs(H/z)>J1}(S,P)?g===1?{needsFlipping:!0}:null:S<0?{needsFlipping:!0}:null}function Sn(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut,dt,jt,Tt){const ft=g/24,Kt=M.lineOffsetX*ft,Rt=M.lineOffsetY*ft,{lineStartIndex:Wt,glyphStartIndex:Et,numGlyphs:Lt,segment:Vt,writingMode:ds,flipState:Zt}=M,Is=Wt+M.lineLength,Ns=er=>{if(ye){const[Ts,Rs,qs]=er.up,Cr=pe.length;o.bm(ye,Cr+0,Ts,Rs,qs),o.bm(ye,Cr+1,Ts,Rs,qs),o.bm(ye,Cr+2,Ts,Rs,qs),o.bm(ye,Cr+3,Ts,Rs,qs)}const[lr,hs,ss]=er.point;o.bn(pe,lr,hs,ss,er.angle)};if(Lt>1){const er=ar(ft,ee,Kt,Rt,S,De,Ae,M,ie,H,Be,Ye,!1,ut,dt,jt,Tt);if(!er)return{notEnoughRoom:!0};if(P&&!S){let[lr,hs,ss]=er.first.point,[Ts,Rs,qs]=er.last.point;[lr,hs]=Mc(lr,hs,ss,G),[Ts,Rs]=Mc(Ts,Rs,qs,G);const Cr=Pr(ds,Zt,(Ts-lr)*tt,Rs-hs);if(M.flipState=Cr&&Cr.needsFlipping?1:2,Cr)return Cr}Ns(er.first);for(let lr=Et+1;lr0?Ts:na(Ae,ss,lr,1,z,void 0,ut,dt.canonical),qs=Pr(ds,Zt,(Rs[0]-lr[0])*tt,Rs[1]-lr[1]);if(M.flipState=qs&&qs.needsFlipping?1:2,qs)return qs}const er=Va(ft*ee.getoffsetX(Et),Kt,Rt,S,De,Ae,Vt,Wt,Is,ie,H,Be,Ye,!1,!1,ut,dt,jt,Tt);if(!er)return{notEnoughRoom:!0};Ns(er)}return{}}function Vr(M,g,S,P,z){const{x:H,y:G,z:ee}=P.projectTilePoint(M.x,M.y,g);if(!z)return Mc(H,G,ee,S);const[ie,pe,ye]=z.getElevation(M,z.elevation,z.elevationFeature);return Mc(H+ie,G+pe,ee+ye,S)}function na(M,g,S,P,z,H,G,ee){const ie=Vr(M.sub(g)._unit()._add(M),ee,z,G,H);return o.ax(ie,S,ie),o.ay(ie,ie),o.bg(ie,S,ie,P)}function Va(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut,dt,jt){const Tt=P?M-g:M+g;let ft=Tt>0?1:-1,Kt=0;P&&(ft*=-1,Kt=Math.PI),ft<0&&(Kt+=Math.PI);let Rt=ee+G+(ft>0?0:1)|0,Wt=z,Et=z,Lt=0,Vt=0;const ds=Math.abs(Tt),Zt=[],Is=[];let Ns=H,er=Ns,lr=o.be([]);const hs=()=>na(er,Ns,Et,ds-Lt+1,ye,Ae,Ye,ut.canonical);for(;Lt+Vt<=ds;){if(Rt+=ft,Rt=ie)return null;if(Et=Wt,er=Ns,Zt.push(Et),Be&&Is.push(er),Ns=new o.P(pe.getx(Rt),pe.gety(Rt)),Wt=De[Rt],!Wt){const gn=Vr(Ns,ut.canonical,ye,Ye,Ae);Wt=gn[3]>0?De[Rt]=gn:hs()}Lt+=Vt;const nr=o.ax([],Wt,Et),on=o.bf(Et,Wt);if(S&&on>0&&Vt>0&&o.bi(lr,nr)/(Vt*on)0,Tt),Wt=pe*Rt.perspectiveRatio,Et=(P.x1*S+ee.x-P.padding)*Wt+Rt.point.x,Lt=(P.y1*S+ee.y-P.padding)*Wt+Rt.point.y,Vt=(P.x2*S+ee.x+P.padding)*Wt+Rt.point.x,ds=(P.y2*S+ee.y+P.padding)*Wt+Rt.point.y,Zt=Rt.perspectiveRatio<=.55||Rt.occluded;return!this.isInsideGrid(Et,Lt,Vt,ds)||!ie&&this.grid.hitTest(Et,Lt,Vt,ds,De)||Zt?{box:[],offscreen:!1,occluded:Rt.occluded}:{box:[Et,Lt,Vt,ds],offscreen:this.isOffscreen(Et,Lt,Vt,ds),occluded:!1}}placeCollisionCircles(g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut){const dt=[],jt=this.transform.elevation,Tt=g.getProjection(),ft=g.elevationType==="road",Kt=!!jt||ft,Rt=o.bu.getAtTileOffsetFunc(ut,this.transform.center.lat,this.transform.worldSize,Tt),Wt=new o.P(P.tileAnchorX,P.tileAnchorY),Et=new o.P(P.tileAnchorX,P.tileAnchorY);let{x:Lt,y:Vt,z:ds}=Tt.projectTilePoint(Et.x,Et.y,ut.canonical),Zt=null;if(Kt){const on=ft?g.getElevationFeatureForText(z):null;Zt={getElevation:Rt,elevation:jt,elevationFeature:on};const[gn,en,nn]=Rt(Wt,jt,on);Lt+=gn,Vt+=en,ds+=nn}const Is=Tt.name==="globe",Ns=this.projectAndGetPerspectiveRatio(ie,Lt,Vt,ds,ut,Is||!!jt||this.transform.pitch>0,Tt),{perspectiveRatio:er}=Ns,lr=(Ae?ee/er:ee*er)/o.by,hs=Mc(Lt,Vt,ds,pe),ss=P.lineOffsetX*lr,Ts=P.lineOffsetY*lr,Rs=o.ap(g.layers[0].layout.get("text-max-angle")),qs=Math.cos(Rs),Cr=Ns.signedDistanceFromCamera>0?ar(lr,G,ss,Ts,ft&&P.flipState===1,hs,Et,P,H,pe,{},Kt&&!Ae?Zt:null,Ae&&Kt,Tt,ut,Ae,qs):null;let br=!1,_r=!1,nr=!0;if(Cr&&!Ns.occluded){const on=.5*tt*er+Ye,gn=new o.P(-100,-100),en=new o.P(this.screenRightBoundary,this.screenBottomBoundary),nn=new ap,{first:Gn,last:ma}=Cr,aa=Gn.path.length;let Oa=[];for(let ia=aa-1;ia>=1;ia--)Oa.push(Gn.path[ia]);for(let ia=1;ia(Kt&&!Is&&(mo=Rt(mlia[3]<=0)&&(Oa=[]));let Fa=[];if(Oa.length>0){let ia=1/0,ji=-1/0,mo=1/0,ml=-1/0;for(const No of Oa)ia=Math.min(ia,No[0]),mo=Math.min(mo,No[1]),ji=Math.max(ji,No[0]),ml=Math.max(ml,No[1]);ji>=gn.x&&ia<=en.x&&ml>=gn.y&&mo<=en.y&&(Fa=[Oa.map(No=>new o.P(No[0],No[1]))],(iaen.x||moen.y)&&(Fa=o.bv(Fa,gn.x,gn.y,en.x,en.y)))}for(const ia of Fa){nn.reset(ia,.25*on);let ji=0;ji=nn.length<=.5*on?1:Math.ceil(nn.paddedLength/zn)+1;for(let mo=0;mo0?(o.aE(ie,ie,g),this.fogState&&H&&ee.name!=="globe"&&(pe=function(Ae,Be,tt,Ye,ut,dt){const jt=dt.calculateFogTileMatrix(ut),Tt=[Be,tt,Ye];return o.ah(Tt,Tt,jt),ca(Ae,o.ai(Tt),dt.pitch,dt._fov)}(this.fogState,S,P,z,H.toUnwrapped(),this.transform)>.9)):An(ie,ie,g);const ye=ie[3];return{point:new o.P((ie[0]/ye+1)/2*this.transform.width+fd,(-ie[1]/ye+1)/2*this.transform.height+fd),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(ee)/ye*.5,1.5),signedDistanceFromCamera:ye,occluded:G&&ie[2]>ye||pe}}isOffscreen(g,S,P,z){return P=this.screenRightBoundary||zthis.screenBottomBoundary}isInsideGrid(g,S,P,z){return P>=0&&g=0&&SP.collisionGroupID===S}}return this.collisionGroups[g]}}function bh(M,g,S,P,z){const{horizontalAlign:H,verticalAlign:G}=o.bF(M),ee=-(H-.5)*g,ie=-(G-.5)*S,pe=o.bG(M,P);return new o.P(ee+pe[0]*z,ie+pe[1]*z)}function qp(M,g,S,P,z){const H=new o.P(M,g);return S&&H._rotate(P?z:-z),H}class Zi{constructor(g,S,P,z,H,G){this.transform=g.clone(),this.projection=g.projection.name,this.collisionIndex=new Gh(this.transform,H),this.buildingIndex=G,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=S,this.retainedQueryData={},this.collisionGroups=new Bi(P),this.collisionCircleArrays={},this.prevPlacement=z,z&&(z.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(g,S,P,z,H=1){const G=P.getBucket(S),ee=P.latestFeatureIndex;if(!G||!ee||S.fqid!==G.layerIds[0])return;const ie=G.layers[0].layout,pe=G.layers[0].paint,ye=P.collisionBoxArray,De=Math.pow(2,this.transform.zoom-P.tileID.overscaledZ),Ae=P.tileSize/o.an,Be=P.tileID.toUnwrapped();this.transform.setProjection(G.projection);const tt=(Ye=P.tileID,ut=G.getProjection(),dt=this.transform,ut.name===this.projection?dt.calculateProjMatrix(Ye.toUnwrapped()):Q1(dt,ut,Ye));var Ye,ut,dt;const jt=ie.get("text-pitch-alignment")==="map",Tt=ie.get("text-rotation-alignment")==="map";S.compileFilter(S.options);const ft=S.dynamicFilter(),Kt=S.dynamicFilterNeedsFeature(),Rt=S.dynamicFilterNeedsGeometry(),Wt=this.transform.calculatePixelsToTileUnitsMatrix(P),Et=_c(tt,P.tileID.canonical,jt,Tt,this.transform,G.getProjection(),Wt);let Lt=null;const Vt=G.getProjection().createInversionMatrix(this.transform,P.tileID.canonical);if(jt){const Ts=Lm(tt,P.tileID.canonical,jt,Tt,this.transform,G.getProjection(),Wt);Lt=o.aD([],this.transform.labelPlaneMatrix,Ts)}let ds=null;ft&&P.latestFeatureIndex&&(ds={unwrappedTileID:Be,dynamicFilter:ft,dynamicFilterNeedsFeature:Kt,needGeometry:Rt}),this.retainedQueryData[G.bucketInstanceId]=new wi(G.bucketInstanceId,ee,G.sourceLayerIndex,G.index,P.tileID);const[Zt,Is]=G.layers[0].layout.get("text-size-scale-range"),Ns=o.aC(H,Zt,Is),[er,lr]=ie.get("icon-size-scale-range"),hs=o.aC(H,er,lr),ss={bucket:G,layout:ie,paint:pe,posMatrix:tt,invMatrix:Vt,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:Et,labelToScreenMatrix:Lt,clippingData:ds,scale:De,textPixelRatio:Ae,holdingForFade:P.holdingForFade(),collisionBoxArray:ye,partiallyEvaluatedTextSize:o.bj(G.textSizeData,this.transform.zoom,Ns),partiallyEvaluatedIconSize:o.bj(G.iconSizeData,this.transform.zoom,hs),collisionGroup:this.collisionGroups.get(G.sourceID),latestFeatureIndex:P.latestFeatureIndex};if(z)for(const Ts of G.sortKeyRanges){const{sortKey:Rs,symbolInstanceStart:qs,symbolInstanceEnd:Cr}=Ts;g.push({sortKey:Rs,symbolInstanceStart:qs,symbolInstanceEnd:Cr,parameters:ss})}else g.push({symbolInstanceStart:0,symbolInstanceEnd:G.symbolInstances.length,parameters:ss})}attemptAnchorPlacement(g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut,dt,jt,Tt,ft,Kt){const{textOffset0:Rt,textOffset1:Wt,crossTileID:Et}=Ye,Lt=[Rt,Wt],Vt=bh(g,G,ee,Lt,ie),ds=this.collisionIndex.placeCollisionBox(dt,ie,S,P,z,H,qp(Vt.x,Vt.y,pe,ye,this.transform.angle),tt,De,Ae,Be.predicate);if(Tt){const Zt=dt.getSymbolInstanceIconSize(Kt,this.transform.zoom,Ye.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(dt,Zt,Tt,P,z,H,qp(Vt.x,Vt.y,pe,ye,this.transform.angle),tt,De,Ae,Be.predicate).box.length===0)return}if(ds.box.length>0){let Zt;return this.prevPlacement&&this.prevPlacement.variableOffsets[Et]&&this.prevPlacement.placements[Et]&&this.prevPlacement.placements[Et].text&&(Zt=this.prevPlacement.variableOffsets[Et].anchor),this.variableOffsets[Et]={textOffset:Lt,width:G,height:ee,anchor:g,textScale:ie,prevAnchor:Zt},this.markUsedJustification(dt,g,Ye,jt),dt.allowVerticalPlacement&&(this.markUsedOrientation(dt,jt,Ye),this.placedOrientations[Et]=jt),{shift:Vt,placedGlyphBoxes:ds}}}placeLayerBucketPart(g,S,P,z,H=1){const{bucket:G,layout:ee,paint:ie,posMatrix:pe,textLabelPlaneMatrix:ye,labelToScreenMatrix:De,clippingData:Ae,textPixelRatio:Be,mercatorCenter:tt,invMatrix:Ye,holdingForFade:ut,collisionBoxArray:dt,partiallyEvaluatedTextSize:jt,partiallyEvaluatedIconSize:Tt,collisionGroup:ft,latestFeatureIndex:Kt}=g.parameters,Rt=ee.get("text-optional"),Wt=ee.get("icon-optional"),Et=ee.get("text-allow-overlap"),Lt=ee.get("icon-allow-overlap"),Vt=ee.get("text-rotation-alignment")==="map",ds=ee.get("icon-rotation-alignment")==="map",Zt=ee.get("text-pitch-alignment")==="map",Is=ie.get("symbol-z-offset"),Ns=ee.get("symbol-elevation-reference")==="sea",er=ee.get("symbol-placement"),[lr,hs]=ee.get("text-size-scale-range"),[ss,Ts]=ee.get("icon-size-scale-range"),Rs=o.aC(H,lr,hs),qs=o.aC(H,ss,Ts),Cr=ee.get("text-variable-anchor"),br=Vt&&er!=="point",_r=ds&&er!=="point",nr=Cr&&G.hasTextData(),on=G.hasIconTextFit()&&nr&&G.hasIconData();this.transform.setProjection(G.projection);const gn=nr||br,en=_r||on;let nn=Et&&(Lt||!G.hasIconData()||Wt),Gn=Lt&&(Et||!G.hasTextData()||Rt);const ma=!Is.isConstant();!G.collisionArrays&&dt&&G.deserializeCollisionBoxes(dt),P&&z&&G.updateCollisionDebugBuffers(this.transform.zoom,dt,Rs,qs);const aa=(zn,Fa,ia)=>{const{crossTileID:ji,numVerticalGlyphVertices:mo}=zn;let ml=null;if(Ae&&Ae.dynamicFilterNeedsFeature||ma){const To=this.retainedQueryData[G.bucketInstanceId],Po=Kt.loadFeature({featureIndex:zn.featureIndex,bucketIndex:To.bucketIndex,sourceLayerIndex:To.sourceLayerIndex,layoutVertexArrayOffset:0}),ao=Po.properties?Po.properties.worldview:null;if(G.localizable&&G.worldview&&typeof ao=="string")if(ao==="all")Po.properties.$localized=!0;else{if(!ao.split(",").includes(G.worldview))return;Po.properties.$localized=!0,Po.properties.worldview=G.worldview}ml=Ae&&Ae.needGeometry?o.bD(Po,!0):Po}if(Ae&&!(0,Ae.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:G.worldview},ml,this.retainedQueryData[G.bucketInstanceId].tileID.canonical,new o.P(zn.tileAnchorX,zn.tileAnchorY),this.transform.calculateDistanceTileData(Ae.unwrappedTileID)))return this.placements[ji]=new ip(!1,!1,!1,!0),void S.add(ji);const No=Is.evaluate(ml,{});if((zn.zOffset||0)+(No||0)>0&&this.frontCutoffStart>0){const To=2*this.frontCutoffStart-1,Po=[zn.tileAnchorX,zn.tileAnchorY,0,1],ao=o.aE(o.bE(),Po,pe);if(ao[1]/ao[3]{To.tileID=this.retainedQueryData[G.bucketInstanceId].tileID;const Po=this.transform.elevation;To.elevation=Ns?No:No+o.bu.getAtTileOffset(To.tileID,new o.P(To.tileAnchorX,To.tileAnchorY),Po,Qc),To.elevation+=zn.zOffset},pp=ia.textBox;if(pp){Jd(pp);const To=ao=>{let tc=o.bk.horizontal;if(G.allowVerticalPlacement&&!ao&&this.prevPlacement){const Sh=this.prevPlacement.placedOrientations[ji];Sh&&(this.placedOrientations[ji]=Sh,tc=Sh,this.markUsedOrientation(G,tc,zn))}return tc},Po=(ao,tc)=>{if(G.allowVerticalPlacement&&mo>0&&ia.verticalTextBox){for(const Sh of G.writingModes)if(Sh===o.bk.vertical?(ya=tc(),al=ya):ya=ao(),ya&&ya.box&&ya.box.length)break}else ya=ao()};if(Cr){let ao=Cr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[ji]){const Pl=this.prevPlacement.variableOffsets[ji];ao.indexOf(Pl.anchor)>0&&(ao=ao.filter(xp=>xp!==Pl.anchor),ao.unshift(Pl.anchor))}const tc=(Pl,xp,Nb)=>{const sj=G.getSymbolInstanceTextSize(jt,zn,this.transform.zoom,Fa),rj=(Pl.x2-Pl.x1)*sj+2*Pl.padding,bN=(Pl.y2-Pl.y1)*sj+2*Pl.padding,Uv=zn.hasIconTextFit&&!Lt?xp:null;Uv&&Jd(Uv);let py={box:[],offscreen:!1,occluded:!1};const _N=Et?2*ao.length:ao.length;for(let Tf=0;Tf<_N;++Tf){const kb=this.attemptAnchorPlacement(ao[Tf%ao.length],Pl,tt,Ye,gn,rj,bN,sj,Vt,Zt,Be,pe,ft,Tf>=ao.length,zn,Fa,G,Nb,Uv,jt,Tt);if(kb&&(py=kb.placedGlyphBoxes,py&&py.box&&py.box.length)){Ii=!0,Pi=kb.shift;break}}return py};Po(()=>tc(pp,ia.iconBox,o.bk.horizontal),()=>{const Pl=ia.verticalTextBox;return Pl&&Jd(Pl),G.allowVerticalPlacement&&!(ya&&ya.box&&ya.box.length)&&mo>0&&Pl?tc(Pl,ia.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),ya&&(Ii=ya.box,Ea=ya.offscreen,ko=ya.occluded);const Sh=To(!(!ya||!ya.box));if(!Ii&&this.prevPlacement){const Pl=this.prevPlacement.variableOffsets[ji];Pl&&(this.variableOffsets[ji]=Pl,this.markUsedJustification(G,Pl.anchor,zn,Sh))}}else{const ao=(tc,Sh)=>{const Pl=G.getSymbolInstanceTextSize(jt,zn,this.transform.zoom,Fa),xp=this.collisionIndex.placeCollisionBox(G,Pl,tc,tt,Ye,gn,new o.P(0,0),Et,Be,pe,ft.predicate);return xp&&xp.box&&xp.box.length&&(this.markUsedOrientation(G,Sh,zn),this.placedOrientations[ji]=Sh),xp};Po(()=>ao(pp,o.bk.horizontal),()=>{const tc=ia.verticalTextBox;return G.allowVerticalPlacement&&mo>0&&tc?(Jd(tc),ao(tc,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),To(!!(ya&&ya.box&&ya.box.length))}}if(fo=ya,Ii=fo&&fo.box&&fo.box.length>0,Ea=fo&&fo.offscreen,ko=fo&&fo.occluded,zn.useRuntimeCollisionCircles){const To=zn.centerJustifiedTextSymbolIndex>=0?zn.centerJustifiedTextSymbolIndex:zn.verticalPlacedTextSymbolIndex,Po=G.text.placedSymbolArray.get(To),ao=o.bl(G.textSizeData,jt,Po),tc=ee.get("text-padding");lc=this.collisionIndex.placeCollisionCircles(G,Et,Po,To,G.lineVertexArray,G.glyphOffsetArray,ao,pe,ye,De,P,Zt,ft.predicate,zn.collisionCircleDiameter*ao/o.by,tc,this.retainedQueryData[G.bucketInstanceId].tileID),Ii=Et||lc.circles.length>0&&!lc.collisionDetected,Ea=Ea&&lc.offscreen,ko=lc.occluded}if(ia.iconFeatureIndex&&(th=ia.iconFeatureIndex),ia.iconBox){const To=Po=>{Jd(Po);const ao=zn.hasIconTextFit&&Pi?qp(Pi.x,Pi.y,Vt,Zt,this.transform.angle):new o.P(0,0),tc=G.getSymbolInstanceIconSize(Tt,this.transform.zoom,zn.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(G,tc,Po,tt,Ye,en,ao,Lt,Be,pe,ft.predicate)};al&&al.box&&al.box.length&&ia.verticalIconBox?(ni=To(ia.verticalIconBox),Ta=ni.box.length>0):(ni=To(ia.iconBox),Ta=ni.box.length>0),Ea=Ea&&ni.offscreen,bl=ni.occluded}const Xi=Rt||zn.numHorizontalGlyphVertices===0&&mo===0,ex=Wt||zn.numIconVertices===0;if(Xi||ex?ex?Xi||(Ta=Ta&&Ii):Ii=Ta&&Ii:Ta=Ii=Ta&&Ii,Ii&&fo&&fo.box&&this.collisionIndex.insertCollisionBox(fo.box,ee.get("text-ignore-placement"),G.bucketInstanceId,al&&al.box&&Pc?Pc:bo,ft.ID),Ta&&ni&&this.collisionIndex.insertCollisionBox(ni.box,ee.get("icon-ignore-placement"),G.bucketInstanceId,th,ft.ID),lc&&(Ii&&this.collisionIndex.insertCollisionCircles(lc.circles,ee.get("text-ignore-placement"),G.bucketInstanceId,bo,ft.ID),P)){const To=G.bucketInstanceId;let Po=this.collisionCircleArrays[To];Po===void 0&&(Po=this.collisionCircleArrays[To]=new yn);for(let ao=0;ao=0;--Fa){const ia=zn[Fa];aa(G.symbolInstances.get(ia),ia,G.collisionArrays[ia])}G.hasAnyZOffset&&o.w(`${G.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(G.hasAnyZOffset){const zn=G.getSortedIndexesByZOffset();for(let Fa=0;Fa=0&&(g.text.placedSymbolArray.get(H).crossTileID=De>=0&&H!==De?0:pe),G>=0&&(g.text.placedSymbolArray.get(G).crossTileID=De>=0&&G!==De?0:pe),ee>=0&&(g.text.placedSymbolArray.get(ee).crossTileID=De>=0&&ee!==De?0:pe),ie>=0&&(g.text.placedSymbolArray.get(ie).crossTileID=De>=0&&ie!==De?0:pe)}markUsedOrientation(g,S,P){const z=S===o.bk.horizontal||S===o.bk.horizontalOnly?S:0,H=S===o.bk.vertical?S:0,{leftJustifiedTextSymbolIndex:G,centerJustifiedTextSymbolIndex:ee,rightJustifiedTextSymbolIndex:ie,verticalPlacedTextSymbolIndex:pe}=P,ye=g.text.placedSymbolArray;G>=0&&(ye.get(G).placedOrientation=z),ee>=0&&(ye.get(ee).placedOrientation=z),ie>=0&&(ye.get(ie).placedOrientation=z),pe>=0&&(ye.get(pe).placedOrientation=H)}commit(g){this.commitTime=g,this.zoomAtLastRecencyCheck=this.transform.zoom;const S=this.prevPlacement;let P=!1;this.prevZoomAdjustment=S?S.zoomAdjustment(this.transform.zoom):0;const z=S?S.symbolFadeChange(g):1,H=S?S.opacities:{},G=S?S.variableOffsets:{},ee=S?S.placedOrientations:{};for(const ie in this.placements){const pe=this.placements[ie],ye=H[ie];ye?(this.opacities[ie]=new Ox(ye,z,pe.text,pe.icon,null,pe.clipped),P=P||pe.text!==ye.text.placed||pe.icon!==ye.icon.placed):(this.opacities[ie]=new Ox(null,z,pe.text,pe.icon,pe.skipFade,pe.clipped),P=P||pe.text||pe.icon)}for(const ie in H){const pe=H[ie];if(!this.opacities[ie]){const ye=new Ox(pe,z,!1,!1);ye.isHidden()||(this.opacities[ie]=ye,P=P||pe.text.placed||pe.icon.placed)}}for(const ie in G)this.variableOffsets[ie]||!this.opacities[ie]||this.opacities[ie].isHidden()||(this.variableOffsets[ie]=G[ie]);for(const ie in ee)this.placedOrientations[ie]||!this.opacities[ie]||this.opacities[ie].isHidden()||(this.placedOrientations[ie]=ee[ie]);P?this.lastPlacementChangeTime=g:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=S?S.lastPlacementChangeTime:g)}updateLayerOpacities(g,S,P,z){z&&(this.lastReplacementSourceUpdateTime=z.updateTime);const H=new Set;for(const G of S){const ee=G.getBucket(g);ee&&G.latestFeatureIndex&&g.fqid===ee.layerIds[0]&&(this.updateBucketOpacities(ee,H,G,G.collisionBoxArray,P,z,G.tileID,g.scope),ee.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(ee,G.tileID),ee.elevationType==="road"&&ee.updateRoadElevation(G.tileID.canonical),ee.updateZOffset())}}updateBucketOpacities(g,S,P,z,H,G,ee,ie){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 pe=g.layers[0].layout,ye=g.layers[0].paint,De=!!g.layers[0].dynamicFilter(),Ae=new Ox(null,0,!1,!1,!0),Be=pe.get("text-allow-overlap"),tt=pe.get("icon-allow-overlap"),Ye=pe.get("text-variable-anchor"),ut=pe.get("text-rotation-alignment")==="map",dt=pe.get("text-pitch-alignment")==="map",jt=ye.get("symbol-z-offset"),Tt=pe.get("symbol-elevation-reference")==="sea",ft=!jt.isConstant(),Kt=new Ox(null,0,Be&&(tt||!g.hasIconData()||pe.get("icon-optional")),tt&&(Be||!g.hasTextData()||pe.get("text-optional")),!0);!g.collisionArrays&&z&&(g.hasIconCollisionBoxData()||g.hasTextCollisionBoxData())&&g.deserializeCollisionBoxes(z);const Rt=(Et,Lt,Vt)=>{for(let ds=0;ds0||ds>0,Cr=Is>0,br=this.placedOrientations[Zt],_r=br===o.bk.vertical,nr=br===o.bk.horizontal||br===o.bk.horizontalOnly;!qs&&!Cr||Rs.isHidden()||Wt++;let on=!1;if((qs||Cr)&&G)for(const gn of g.activeReplacements){if(o.bz(gn,H,o.bA.Symbol,ie)||gn.min.x>Ns||Ns>gn.max.x||gn.min.y>er||er>gn.max.y)continue;const en=o.bB(Ns,er,ee.canonical,gn.footprintTileId.canonical);if(on=o.bC(en,gn.footprint),on)break}if(on&&this.collisionIndex.markSymbolAsClipped(g.bucketInstanceId,Lt.featureIndex),qs){const gn=on?Gp:Hp(Rs.text);Rt(g.text,Vt,_r?Gp:gn),Rt(g.text,ds,nr?Gp:gn);const en=Rs.text.isHidden(),{leftJustifiedTextSymbolIndex:nn,centerJustifiedTextSymbolIndex:Gn,rightJustifiedTextSymbolIndex:ma,verticalPlacedTextSymbolIndex:aa}=Lt,Oa=g.text.placedSymbolArray,zn=en||_r?1:0;nn>=0&&(Oa.get(nn).hidden=zn),Gn>=0&&(Oa.get(Gn).hidden=zn),ma>=0&&(Oa.get(ma).hidden=zn),aa>=0&&(Oa.get(aa).hidden=en||nr?1:0);const Fa=this.variableOffsets[Zt];Fa&&this.markUsedJustification(g,Fa.anchor,Lt,br);const ia=this.placedOrientations[Zt];ia&&(this.markUsedJustification(g,"left",Lt,ia),this.markUsedOrientation(g,ia,Lt))}if(Cr){const gn=on?Gp:Hp(Rs.icon),{placedIconSymbolIndex:en,verticalPlacedIconSymbolIndex:nn}=Lt,Gn=g.icon.placedSymbolArray,ma=Rs.icon.isHidden()?1:0;en>=0&&(Rt(g.icon,Is,_r?Gp:gn),Gn.get(en).hidden=ma),nn>=0&&(Rt(g.icon,Lt.numVerticalIconVertices,nr?Gp:gn),Gn.get(nn).hidden=ma)}if(g.hasIconCollisionBoxData()||g.hasTextCollisionBoxData()){const gn=g.collisionArrays[Et];if(gn){let en=new o.P(0,0),nn=!0;if(gn.textBox||gn.verticalTextBox){if(Ye){const ma=this.variableOffsets[Zt];ma?(en=bh(ma.anchor,ma.width,ma.height,ma.textOffset,ma.textScale),ut&&en._rotate(dt?this.transform.angle:-this.transform.angle)):nn=!1}De&&(nn=!Rs.clipped),gn.textBox&&Vp(g.textCollisionBox.collisionVertexArray,Rs.text.placed,!nn||_r,ss,Tt,en.x,en.y),gn.verticalTextBox&&Vp(g.textCollisionBox.collisionVertexArray,Rs.text.placed,!nn||nr,ss,Tt,en.x,en.y)}const Gn=nn&&!!(!nr&&gn.verticalIconBox);gn.iconBox&&Vp(g.iconCollisionBox.collisionVertexArray,Rs.icon.placed,Gn,ss,Tt,Lt.hasIconTextFit?en.x:0,Lt.hasIconTextFit?en.y:0),gn.verticalIconBox&&Vp(g.iconCollisionBox.collisionVertexArray,Rs.icon.placed,!Gn,ss,Tt,Lt.hasIconTextFit?en.x:0,Lt.hasIconTextFit?en.y:0)}}}if(g.fullyClipped=Wt===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 Et=this.collisionCircleArrays[g.bucketInstanceId];g.placementInvProjMatrix=Et.invProjMatrix,g.placementViewportMatrix=Et.viewportMatrix,g.collisionCircleArray=Et.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 Vp(M,g,S,P,z,H,G){M.emplaceBack(g?1:0,S?1:0,H||0,G||0,P,z?1:0),M.emplaceBack(g?1:0,S?1:0,H||0,G||0,P,z?1:0),M.emplaceBack(g?1:0,S?1:0,H||0,G||0,P,z?1:0),M.emplaceBack(g?1:0,S?1:0,H||0,G||0,P,z?1:0)}const J0=Math.pow(2,25),eb=Math.pow(2,24),Tu=Math.pow(2,17),Il=Math.pow(2,16),xM=Math.pow(2,9),ey=Math.pow(2,8),tb=Math.pow(2,1);function Hp(M){if(M.opacity===0&&!M.placed)return 0;if(M.opacity===1&&M.placed)return 4294967295;const g=M.placed?1:0,S=Math.floor(127*M.opacity);return S*J0+g*eb+S*Tu+g*Il+S*xM+g*ey+S*tb+g}const Gp=0;class vw{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,S,P,z,H,G){const ee=this._bucketParts;for(;this._currentTileIndexie.sortKey-pe.sortKey));this._currentPartIndex{const ie=o.o.now()-G;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&ie>2};for(;this._currentPlacementIndex>=0;){const ie=S[g[this._currentPlacementIndex]],pe=this.placement.collisionIndex.transform.zoom;if(ie.type==="symbol"&&ie.visibility!=="none"&&(!ie.minzoom||ie.minzoom<=pe)&&(!ie.maxzoom||ie.maxzoom>pe)){const ye=ie,De=ye.layout.get("symbol-z-elevate"),Ae=ye.layout.get("symbol-sort-key").constantOr(1)!==void 0,Be=ye.layout.get("symbol-z-order"),tt=Be==="viewport-y"||Be==="auto"&&!(Be!=="viewport-y"&&Ae),Ye=ye.layout.get("text-allow-overlap")||ye.layout.get("icon-allow-overlap")||ye.layout.get("text-ignore-placement")||ye.layout.get("icon-ignore-placement"),ut=tt&&Ye,dt=this._inProgressLayer=this._inProgressLayer||new vw(ye),jt=o.F(ie.source,ie.scope);if(dt.continuePlacement(De||ut?z[jt]:P[jt],this.placement,this._showCollisionBoxes,ie,ee,H))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(g){return this.placement.commit(g),this.placement}}const Td=512/o.an/2;class Rm{constructor(g,S,P){this.tileID=g,this.bucketInstanceId=P,this.index=new o.bI(S.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const z=g.canonical.x*o.an,H=g.canonical.y*o.an;for(let G=0;Gut-dt);for(const ut of Ye){const dt=this.crossTileIDs[ut];if(this.keys[ut]===ye&&!P.has(dt)){P.add(dt),pe.crossTileID=dt;break}}}}}class Ed{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class gf{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(g){const S=Math.round((g-this.lng)/360);if(S!==0)for(const P in this.indexes){const z=this.indexes[P],H={};for(const G in z){const ee=z[G];ee.tileID=ee.tileID.unwrapTo(ee.tileID.wrap+S),H[ee.tileID.key]=ee}this.indexes[P]=H}this.lng=g}addBucket(g,S,P){if(this.indexes[g.overscaledZ]&&this.indexes[g.overscaledZ][g.key]){if(this.indexes[g.overscaledZ][g.key].bucketInstanceId===S.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(g.overscaledZ,this.indexes[g.overscaledZ][g.key])}for(let H=0;Hg.overscaledZ)for(const ee in G){const ie=G[ee];ie.tileID.isChildOf(g)&&ie.findMatches(S.symbolInstances,g,z)}else{const ee=G[g.scaledTo(Number(H)).key];ee&&ee.findMatches(S.symbolInstances,g,z)}}for(let H=0;H{S[P]=!0});for(const P in this.layerIndexes)S[P]||delete this.layerIndexes[P]}}const kl=771;class Hn{constructor(g,S,P,z){this.blendFunction=g,this.blendColor=S.toNonPremultipliedRenderColor(null),this.mask=P,this.blendEquation=z}}Hn.Replace=[1,0,1,0],Hn.disabled=new Hn(Hn.Replace,o.aq.transparent,[!1,!1,!1,!1]),Hn.unblended=new Hn(Hn.Replace,o.aq.transparent,[!0,!0,!0,!0]),Hn.alphaBlended=new Hn([1,kl,1,kl],o.aq.transparent,[!0,!0,!0,!0]),Hn.alphaBlendedNonPremultiplied=new Hn([770,kl,770,kl],o.aq.transparent,[!0,!0,!0,!0]),Hn.multiply=new Hn([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),Hn.multiplyAccumulateAlpha=new Hn([774,0,1,kl],o.aq.transparent,[!0,!0,!0,!0]),Hn.additive=new Hn([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class Jr{constructor(g,S,P){this.func=g,this.mask=S,this.range=P}}Jr.ReadOnly=!1,Jr.ReadWrite=!0,Jr.disabled=new Jr(519,Jr.ReadOnly,[0,1]);const hl=7680;class Xn{constructor(g,S,P,z,H,G){this.test=g,this.ref=S,this.mask=P,this.fail=z,this.depthFail=H,this.pass=G}}Xn.disabled=new Xn({func:519,mask:0},0,0,hl,hl,hl);const Om=1029,Wh=2305;class Cn{constructor(g,S,P){this.enable=g,this.mode=S,this.frontFace=P}}function ty(M,g){const S=o.bO(M,3);o.bR(M,g),o.bW(M,3,S)}function bw(M,g){const S=o.bL([]);return o.bM(S,S,-g),o.bN(S,S,-M),S}function bv(M,g){const S=[M[0],M[1],0],P=[g[0],g[1],0];if(o.ai(S)>=1e-15){const G=o.ay([],S);o.bJ(P,G,o.bi(P,G)),g[0]=P[0],g[1]=P[1]}const z=o.bh([],g,M);if(o.bK(z)<1e-15)return null;const H=Math.atan2(-z[1],z[0]);return bw(Math.atan2(Math.sqrt(M[0]*M[0]+M[1]*M[1]),-M[2]),H)}Cn.disabled=new Cn(!1,Om,Wh),Cn.backCCW=new Cn(!0,Om,Wh),Cn.backCW=new Cn(!0,Om,2304),Cn.frontCW=new Cn(!0,1028,2304),Cn.frontCCW=new Cn(!0,1028,Wh);class rb{constructor(g,S){this.position=g,this.orientation=S}get position(){return this._position}set position(g){if(g){const S=g instanceof o.ag?g:new o.ag(g[0],g[1],g[2]);this._renderWorldCopies&&(S.x=o.bs(S.x,0,1)),this._position=S}else this._position=null}lookAtPoint(g,S,P){if(this.orientation=null,!this.position)return;const z=this.position,H=P||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(g)):0),G=o.ag.fromLngLat(g,H),ee=[G.x-z.x,G.y-z.y,G.z-z.z];S||(S=[0,0,1]),S[2]=Math.abs(S[2]),this.orientation=bv(ee,S)}setPitchBearing(g,S){this.orientation=bw(o.ap(g),o.ap(-S))}}class Dg{constructor(g,S){this._transform=o.b9([]),this.orientation=S,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 S;g&&o.bW(this._transform,3,[(S=g)[0],S[1],S[2],1])}get orientation(){return this._orientation}set orientation(g){this._orientation=g||o.bL([]),g&&ty(this._transform,this._orientation)}getPitchBearing(){const g=this.forward(),S=this.right();return{bearing:Math.atan2(-S[1],S[0]),pitch:Math.atan2(Math.sqrt(g[0]*g[0]+g[1]*g[1]),-g[2])}}setPitchBearing(g,S){this._orientation=bw(g,S),ty(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,S){const P=new Float64Array(16);return o.b7(P,this.getWorldToCamera(g,S)),P}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(g,S,P){const z=this.position;o.bJ(z,z,-g);const H=new Float64Array(16);return o.bP(H,[P,P,P]),o.bx(H,H,z),H[10]*=S,H}getWorldToCamera(g,S){const P=new Float64Array(16),z=new Float64Array(4),H=this.position;return o.bQ(z,this._orientation),o.bJ(H,H,-g),o.bR(P,z),o.bx(P,P,H),P[1]*=-1,P[5]*=-1,P[9]*=-1,P[13]*=-1,P[8]*=S,P[9]*=S,P[10]*=S,P[11]*=S,P}getCameraToClipPerspective(g,S,P,z){const H=new Float64Array(16);return o.bS(H,g,S,P,z),H}getCameraToClipOrthographic(g,S,P,z,H,G){const ee=new Float64Array(16);return o.bT(ee,g,S,P,z,H,G),ee}getDistanceToElevation(g,S=!1){const P=g===0?0:o.bU(g,S?o.bV(this.position[1]):this.position[1]),z=this.forward();return(P-this.position[2])/z[2]}clone(){return new Dg([...this.position],[...this.orientation])}}const lp=(M,g)=>({u_matrix:M,u_ground_shadow_factor:g});class Kh{constructor(g=0,S=0,P=0,z=0){if(isNaN(g)||g<0||isNaN(S)||S<0||isNaN(P)||P<0||isNaN(z)||z<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=g,this.bottom=S,this.left=P,this.right=z}interpolate(g,S,P){return S.top!=null&&g.top!=null&&(this.top=o.am(g.top,S.top,P)),S.bottom!=null&&g.bottom!=null&&(this.bottom=o.am(g.bottom,S.bottom,P)),S.left!=null&&g.left!=null&&(this.left=o.am(g.left,S.left,P)),S.right!=null&&g.right!=null&&(this.right=o.am(g.right,S.right,P)),this}getCenter(g,S){const P=o.aC((this.left+g-this.right)/2,0,g),z=o.aC((this.top+S-this.bottom)/2,0,S);return new o.P(P,z)}equals(g){return this.top===g.top&&this.bottom===g.bottom&&this.left===g.left&&this.right===g.right}clone(){return new Kh(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const cp=15;class Fm{constructor(g,S,P,z,H,G,ee){this.tileSize=512,this._renderWorldCopies=H===void 0||H,this._minZoom=g||0,this._maxZoom=S||22,this._minPitch=P??0,this._maxPitch=z??60,this.setProjection(G),this.setMaxBounds(ee),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 Kh,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new Dg,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 Fm(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&&(!S||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const P=this._elevation;S||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&P.exaggeration()&&this._centerAltitudeValidForExaggeration!==P.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*P.exaggeration(),this._centerAltitudeValidForExaggeration=P.exaggeration()):(this._centerAltitude=g||0,this._centerAltitudeValidForExaggeration=P.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,S=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],P=this.horizonLineFromTop();let z=0,H=0;for(let G=0;G{const ut=o.ck(Ae,De,Be,tt,Ye);ie.has(ut)||(H.push(new o.aR(De,Ae,Be,tt,Ye)),ie.add(ut))};for(let De=0;DeAe.canonical.z)continue;const Be=Ae.canonical,tt=Ae.overscaledZ,Ye=Ae.wrap,ut=1<0,Tt=Be.y+10,Kt=Ae.wrap-(jt?0:1),Rt=Ae.wrap+(dt?0:1),Wt=jt?Be.x-1:ut-1,Et=dt?Be.x+1:0;if(G)P[0]<0?(pe(tt,Rt,Be.z,Et,Be.y),P[1]<0&&Tt&&(pe(tt,Ye,Be.z,Be.x,Be.y+1),pe(tt,Rt,Be.z,Et,Be.y+1)),P[1]>0&&ft&&(pe(tt,Ye,Be.z,Be.x,Be.y-1),pe(tt,Rt,Be.z,Et,Be.y-1))):P[0]>0?(pe(tt,Kt,Be.z,Wt,Be.y),P[1]<0&&Tt&&(pe(tt,Ye,Be.z,Be.x,Be.y+1),pe(tt,Kt,Be.z,Wt,Be.y+1)),P[1]>0&&ft&&(pe(tt,Ye,Be.z,Be.x,Be.y-1),pe(tt,Kt,Be.z,Wt,Be.y-1))):P[1]<0&&Tt?pe(tt,Ye,Be.z,Be.x,Be.y+1):ft&&pe(tt,Ye,Be.z,Be.x,Be.y-1);else{const Lt=Ae.visibleQuadrants;1&Lt&&(pe(tt,Kt,Be.z,Wt,Be.y),ft&&(pe(tt,Ye,Be.z,Be.x,Be.y-1),pe(tt,Kt,Be.z,Wt,Be.y-1))),2&Lt&&(pe(tt,Rt,Be.z,Et,Be.y),ft&&(pe(tt,Ye,Be.z,Be.x,Be.y-1),pe(tt,Rt,Be.z,Et,Be.y-1))),4&Lt&&(pe(tt,Kt,Be.z,Wt,Be.y),Tt&&(pe(tt,Ye,Be.z,Be.x,Be.y+1),pe(tt,Kt,Be.z,Wt,Be.y+1))),8&Lt&&(pe(tt,Rt,Be.z,Et,Be.y),Tt&&(pe(tt,Ye,Be.z,Be.x,Be.y+1),pe(tt,Rt,Be.z,Et,Be.y+1)))}}const ye=[];for(const De of H)H.some(Ae=>De.isChildOf(Ae))||ye.push(De);if(H=ye.filter(De=>!g.some(Ae=>!!(De.overscaledZ{const dt=ut.canonical.x+.5-Be[0],jt=ut.canonical.y+.5-Be[1];return dt*dt+jt*jt{const Wt=o.ck(Tt,jt,ft,Kt,Rt);H.has(Wt)||(z.push(new o.aR(jt,Tt,ft,Kt,Rt)),H.add(Wt))},ee=g.reduce((jt,Tt)=>Math.max(jt,Tt.overscaledZ),P),ie=1<{const ft=Math.floor(jt[0]),Kt=Math.floor(jt[1]),Rt=(jt[0]-ft)*o.an,Wt=(jt[1]-Kt)*o.an,Et=Math.floor(Tt[0]),Lt=Math.floor(Tt[1]),Vt=(Tt[0]-Et)*o.an,ds=(Tt[1]-Lt)*o.an;for(let Zt=-1;Zt<=1;Zt++){const Is=ft+Zt;if(!(Is<0||Is>=ie)){ye.x=Rt-Zt*o.an,De.x=Vt-(Is-Et)*o.an;for(let Ns=-1;Ns<=1;Ns++){const er=Kt+Ns;ye.y=Wt-Ns*o.an,De.y=ds-(er-Lt)*o.an,o.cI(ye,De,pe)&&G(ee,0,P,Is,er)}}}},Be=S.points,tt=Be[o.c9],Ye=Be[o.ca],ut=this._projectToGround(tt,Be[o.cb]),dt=this._projectToGround(Ye,Be[o.cc]);return Ae(tt,ut),Ae(Ye,dt),z}_projectToGround(g,S){return o.cd(o.ce(),g,S,g[2]/(g[2]-S[2]))}_projectToZ(g,S,P){const z=g[2]-S[2];return Math.abs(z)<1e-6?o.cf(g):o.cd(o.ce(),g,S,(g[2]-P)/z)}extendTileCoverForTunnels(g,S,P,z){if(P<18)return[];const H=S.points,G=H[o.cg],ee=H[o.ch],ie=H[o.ci],pe=H[o.cj];if(ie[2]>=0&&pe[2]>=0||G[2]<=0||ee[2]<=0)return[];const ye=ie[2]<0?this._projectToZ(G,ie,0):ie,De=pe[2]<0?this._projectToZ(ee,pe,0):pe,Ae=-z,Be=ie[2]3&&(Ye.length=3),Ye}_findExtensionTilesInQuad(g,S,P,z){const H=[],G=new Set;for(const Et of g)G.add(Et.key);const ee=g.reduce((Et,Lt)=>Math.max(Et,Lt.overscaledZ),S),ie=1<{const Vt=Et.canonical.x+.5-Rt,ds=Et.canonical.y+.5-Wt,Zt=Lt.canonical.x+.5-Rt,Is=Lt.canonical.y+.5-Wt;return Vt*Vt+ds*ds-(Zt*Zt+Is*Is)||Et.canonical.x-Lt.canonical.x||Et.canonical.y-Lt.canonical.y}),H}coveringTiles(g){let S=this.coveringZoomLevel(g);const P=S,z=this.elevation&&this.elevation.exaggeration(),H=z&&!g.isTerrainDEM,G=this.projection.name==="mercator";if(g.minzoom!==void 0&&Sg.maxzoom&&(S=g.maxzoom);const ee=this.locationCoordinate(this.center),ie=this.center.lat,pe=1<{const Rs=new o.ag(ss.x+25e-6,ss.y,ss.z),qs=new o.ag(ss.x,ss.y+25e-6,ss.z),Cr=ss.toLngLat(),br=Rs.toLngLat(),_r=qs.toLngLat(),nr=this.locationCoordinate(Cr),on=this.locationCoordinate(br),gn=this.locationCoordinate(_r),en=Math.hypot(on.x-nr.x,on.y-nr.y),nn=Math.hypot(gn.x-nr.x,gn.y-nr.y);return Math.sqrt(en*nn)*Wt/25e-6},Lt=ss=>{const Ts=Kt,Rs=Rt;return{aabb:o.cp(this,pe,0,0,0,ss,Rs,Ts,this.projection),zoom:0,x:0,y:0,minZ:Rs,maxZ:Ts,wrap:ss,fullyVisible:!1}},Vt=[];let ds=[];const Zt=S,Is=g.reparseOverscaled?P:S,Ns=(ut-this._centerAltitude)*Ye,er=ss=>{if(!this._elevation||!ss.tileID||!G)return;const Ts=this._elevation.getMinMaxForTile(ss.tileID),Rs=ss.aabb;Ts?(Rs.min[2]=Ts.min,Rs.max[2]=Ts.max,Rs.center[2]=(Rs.min[2]+Rs.max[2])/2):(ss.shouldSplit=hs(ss),ss.shouldSplit||(Rs.min[2]=Rs.max[2]=Rs.center[2]=this._centerAltitude))},lr=(ss,Ts)=>{if(.707*Ts{if(ss.zoom=.9)return!0}else if(H&&(qs=ss.aabb.distanceZ(dt)*Ye),this.projection.isReprojectedInTileSpace&&P<=5){const nn=Math.pow(2,ss.zoom),Gn=Et(new o.ag((ss.x+.5)/nn,(ss.y+.5)/nn));Cr=Gn>.85?1:Gn}if(!G&&!De){const nn=Math.sqrt(Ts*Ts+Rs*Rs+qs*qs);let Gn=(1<0;){const ss=Vt.pop(),Ts=ss.x,Rs=ss.y;let qs=ss.fullyVisible;const Cr=()=>this.projection.name==="globe"&&(ss.y===0||ss.y===(1<br)continue;let _r=0;if(!qs){let en=jt?ss.aabb.intersectsPrecise(Be):ss.aabb.intersectsPreciseFlat(Be);if(en===0&&Cr()){const nn=new o.cn(ss.zoom,Ts,Rs);en=o.co(this,pe,nn,!0).intersectsPrecise(Be)}if(en===0)continue;if(g.calculateQuadrantVisibility)if(Be.containsPoint(ss.aabb.center))_r=15;else for(let nn=0;nn<4;nn++)ss.aabb.quadrant(nn).intersects(Be)!==0&&(_r|=1<>1),on={aabb:G?ss.aabb.quadrant(br):o.cp(this,pe,ss.zoom+1,_r,nr,ss.wrap,ss.minZ,ss.maxZ,this.projection),zoom:ss.zoom+1,x:_r,y:nr,wrap:ss.wrap,fullyVisible:qs,tileID:void 0,shouldSplit:void 0,minZ:ss.minZ,maxZ:ss.maxZ};H&&!De&&(on.tileID=new o.aR(ss.zoom+1===Zt?Is:ss.zoom+1,ss.wrap,ss.zoom+1,_r,nr),er(on)),Vt.push(on)}}if(this.fogCullDistSq){const ss=this.fogCullDistSq,Ts=this.horizonLineFromTop();ds=ds.filter(Rs=>{const qs=[0,0,0,1],Cr=[o.an,o.an,0,1],br=this.calculateFogTileMatrix(Rs.tileID.toUnwrapped());o.aE(qs,qs,br),o.aE(Cr,Cr,br);const _r=o.cq([],qs,Cr),nr=o.cr([],qs,Cr),on=o.cK(_r,nr);if(on===0)return!0;let gn=!1;const en=this._elevation;if(en&&on>ss&&Ts!==0){const nn=this.calculateProjMatrix(Rs.tileID.toUnwrapped());let Gn;g.isTerrainDEM||(Gn=en.getMinMaxForTile(Rs.tileID)),Gn||(Gn={min:Rt,max:Kt});const ma=o.cs(this.rotation),aa=[ma[0]*o.an,ma[1]*o.an,Gn.max];o.ah(aa,aa,nn),gn=(1-aa[1])*this.height*.5ss.distanceSq-Ts.distanceSq).map(ss=>ss.tileID)}resize(g,S){this.width=g,this.height=S,this.pixelsToGLUnits=[2/g,-2/S],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 S=o.aC(g.lat,-o.ct,o.ct),P=this.projection.project(g.lng,S);return new o.P(P.x*this.worldSize,P.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,S){let P,z;const H=this.centerPoint;if(this.projection.name==="globe"){const ee=this.worldSize;P=(S.x-H.x)/ee,z=(S.y-H.y)/ee}else{const ee=this.pointCoordinate(S),ie=this.pointCoordinate(H);P=ee.x-ie.x,z=ee.y-ie.y}const G=this.locationCoordinate(g);this.setLocation(new o.ag(G.x-P,G.y-z))}setLocation(g){this.center=this.coordinateLocation(g),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(g,S){return this.projection.locationPoint(this,g,S)}locationPoint3D(g,S){return this.projection.locationPoint(this,g,S,!0)}pointLocation(g){return this.coordinateLocation(this.pointCoordinate(g))}pointLocation3D(g,S){return this.coordinateLocation(this.pointCoordinate3D(g,S))}locationCoordinate(g,S){const P=S?o.bU(S,g.lat):void 0,z=this.projection.project(g.lng,g.lat);return new o.ag(z.x,z.y,P)}coordinateLocation(g){return this.projection.unproject(g.x,g.y)}pointRayIntersection(g,S){const P=S??this._centerAltitude,z=[g.x,g.y,0,1],H=[g.x,g.y,1,1];o.aE(z,z,this.pixelMatrixInverse),o.aE(H,H,this.pixelMatrixInverse);const G=H[3];o.cu(z,z,1/z[3]),o.cu(H,H,1/G);const ee=z[2],ie=H[2];return{p0:z,p1:H,t:ee===ie?0:(P-ee)/(ie-ee)}}screenPointToMercatorRay(g){const S=[g.x,g.y,0,1],P=[g.x,g.y,1,1];return o.aE(S,S,this.pixelMatrixInverse),o.aE(P,P,this.pixelMatrixInverse),o.cu(S,S,1/S[3]),o.cu(P,P,1/P[3]),S[2]=o.bU(S[2],this._center.lat)*this.worldSize,P[2]=o.bU(P[2],this._center.lat)*this.worldSize,o.cu(S,S,1/this.worldSize),o.cu(P,P,1/this.worldSize),new o.az([S[0],S[1],S[2]],o.ay([],o.ax([],P,S)))}rayIntersectionCoordinate(g){const{p0:S,p1:P,t:z}=g,H=o.bU(S[2],this._center.lat),G=o.bU(P[2],this._center.lat);return new o.ag(o.am(S[0],P[0],z)/this.worldSize,o.am(S[1],P[1],z)/this.worldSize,o.am(H,G,z))}pointCoordinate(g,S=this._centerAltitude){return this.projection.pointCoordinate(this,g.x,g.y,S)}pointCoordinate3D(g,S){if(!this.elevation)return this.pointCoordinate(g,S);let P=this.projection.pointCoordinate3D(this,g.x,g.y);if(P)return new o.ag(P[0],P[1],P[2]);let z=0,H=this.horizonLineFromTop();if(g.y>H)return this.pointCoordinate(g,S);const G=.02*H,ee=g.clone();for(let ie=0;ie<10&&H-z>G;ie++){ee.y=o.am(z,H,.66);const pe=this.projection.pointCoordinate3D(this,ee.x,ee.y);pe?(H=ee.y,P=pe):z=ee.y}return P?new o.ag(P[0],P[1],P[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 S=this.pointCoordinate(g);return S.y>=0&&S.y<=1}_coordinatePoint(g,S){const P=S&&this.elevation?this.elevation.getAtPointOrZero(g,this._centerAltitude):this._centerAltitude,z=[g.x*this.worldSize,g.y*this.worldSize,P+g.toAltitude(),1];return o.aE(z,z,this.pixelMatrix),z[3]>0?new o.P(z[0]/z[3],z[1]/z[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:g,left:S}=this._edgeInsets,P=this.height-this._edgeInsets.bottom,z=this.width-this._edgeInsets.right,H=this.pointLocation3D(new o.P(S,g)),G=this.pointLocation3D(new o.P(z,g)),ee=this.pointLocation3D(new o.P(z,P)),ie=this.pointLocation3D(new o.P(S,P));let pe=Math.min(H.lng,G.lng,ee.lng,ie.lng),ye=Math.max(H.lng,G.lng,ee.lng,ie.lng),De=Math.min(H.lat,G.lat,ee.lat,ie.lat),Ae=Math.max(H.lat,G.lat,ee.lat,ie.lat);const Be=Math.pow(2,-this.zoom)/16*270,tt=this.projection.name==="globe"?1:4,Ye=(ut,dt,jt,Tt,ft)=>{const Kt=(ut+jt)/2,Rt=(dt+Tt)/2,Wt=new o.P(Kt,Rt),{lng:Et,lat:Lt}=this.pointLocation3D(Wt),Vt=Math.max(0,pe-Et,De-Lt,Et-ye,Lt-Ae);pe=Math.min(pe,Et),ye=Math.max(ye,Et),De=Math.min(De,Lt),Ae=Math.max(Ae,Lt),(ftBe)&&(Ye(ut,dt,Kt,Rt,ft+1),Ye(Kt,Rt,jt,Tt,ft+1))};if(Ye(S,g,z,g,1),Ye(z,g,z,P,1),Ye(z,P,S,P,1),Ye(S,P,S,g,1),this.projection.name==="globe"){const[ut,dt]=o.cw(this);ut?(Ae=90,ye=180,pe=-180):dt&&(De=-90,ye=180,pe=-180)}return new o.aK(new o.aU(pe,De),new o.aU(ye,Ae))}_getBoundsRectangular(g,S){const{top:P,left:z}=this._edgeInsets,H=this.height-this._edgeInsets.bottom,G=this.width-this._edgeInsets.right,ee=new o.P(z,P),ie=new o.P(G,P),pe=new o.P(G,H),ye=new o.P(z,H);let De=this.pointCoordinate(ee,g),Ae=this.pointCoordinate(ie,g);const Be=this.pointCoordinate(pe,S),tt=this.pointCoordinate(ye,S),Ye=(ut,dt)=>(dt.y-ut.y)/(dt.x-ut.x);return De.y>1&&Ae.y>=0?De=new o.ag((1-tt.y)/Ye(tt,De)+tt.x,1):De.y<0&&Ae.y<=1&&(De=new o.ag(-tt.y/Ye(tt,De)+tt.x,0)),Ae.y>1&&De.y>=0?Ae=new o.ag((1-Be.y)/Ye(Be,Ae)+Be.x,1):Ae.y<0&&De.y<=1&&(Ae=new o.ag(-Be.y/Ye(Be,Ae)+Be.x,0)),new o.aK().extend(this.coordinateLocation(De)).extend(this.coordinateLocation(Ae)).extend(this.coordinateLocation(tt)).extend(this.coordinateLocation(Be))}_getBoundsRectangularTerrain(){const g=this.elevation;if(!g.visibleDemTiles.length||g.isUsingMockSource())return this._getBoundsRectangular(0,0);const S=g.visibleDemTiles.reduce((P,z)=>{if(z.dem){const H=z.dem.tree;P.min=Math.min(P.min,H.minimums[0]),P.max=Math.max(P.max,H.maximums[0])}return P},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(S.min*g.exaggeration(),S.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 S=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,P=this.height/2-S*(1-this._horizonShift);return g?Math.max(0,P):P}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.maxLngDe&&(ee=De-pe),De-yeBe&&(G=Be-ie),Be-Ae{for(let hs=0;hs<16;hs++)Is[hs]=o.am(Ns[hs],er[hs],lr)})(ee,ee,ie,o.cL(this.pitch>=cp?1:this.pitch/cp))}else ee=ie;const pe=o.cz([],ie,G);let ye=o.cz([],ee,G);if(this.projection.isReprojectedInTileSpace){const Lt=this.locationCoordinate(this.center),Vt=o.b9([]);o.bx(Vt,Vt,[Lt.x*this.worldSize,Lt.y*this.worldSize,0]),o.aD(Vt,Vt,o.cA(this)),o.bx(Vt,Vt,[-Lt.x*this.worldSize,-Lt.y*this.worldSize,0]),o.aD(ye,ye,Vt),o.aD(pe,pe,Vt),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],ye,[this.worldSize,this.worldSize,this.worldSize/H,1]),this.projMatrix=ye,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),S){const Lt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Lt[8]=2*-g.x/this.width,Lt[9]=2*g.y/this.height,this.expandedFarZProjMatrix=o.cz([],Lt,G)}else this.expandedFarZProjMatrix=this.projMatrix;const De=o.b7([],ee);this.frustumCorners=o.cD.fromInvProjectionMatrix(De,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!S);const Ae=new Float32Array(16);o.b9(Ae),o.cC(Ae,Ae,[1,-1,1]),o.cE(Ae,Ae,this._pitch),o.ba(Ae,Ae,this.angle);const Be=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(Be);const tt=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;Be[8]=2*-g.x/this.width,Be[9]=2*(g.y+tt)/this.height,this.skyboxMatrix=o.aD(Ae,Be,Ae);const Ye=this.point,ut=Ye.x,dt=Ye.y,jt=this.width%2/2,Tt=this.height%2/2,ft=Math.cos(this.angle),Kt=Math.sin(this.angle),Rt=ut-Math.round(ut)+ft*jt+Kt*Tt,Wt=dt-Math.round(dt)+ft*Tt+Kt*jt,Et=new Float64Array(ye);if(o.bx(Et,Et,[Rt>.5?Rt-1:Rt,Wt>.5?Wt-1:Wt,0]),this.alignedProjMatrix=Et,ye=o.bb(),o.cC(ye,ye,[this.width/2,-this.height/2,1]),o.bx(ye,ye,[1,-1,0]),this.labelPlaneMatrix=ye,ye=o.bb(),o.cC(ye,ye,[1,-1,1]),o.bx(ye,ye,[-1,-1,0]),o.cC(ye,ye,[2/this.width,2/this.height,1]),this.glCoordMatrix=ye,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,pe),this._calcFogMatrices(),this._distanceTileDataCache={},ye=o.b7(new Float64Array(16),this.pixelMatrix),!ye)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=ye,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const Lt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(Lt,Lt,G),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=ye;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const g=this.cameraWorldSizeForFog,S=this.cameraPixelsPerMeter,P=this._camera.position,z=1/this.height/this._pixelsPerMercatorPixel,H=[g,g,S];o.bJ(H,H,z),o.bJ(P,P,-1),o.cG(P,P,H);const G=o.bb();o.bx(G,G,P),o.cC(G,G,H),this.mercatorFogMatrix=G,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(g,S,z)}_computeCameraPosition(g){const S=(g=g||this.pixelsPerMeter)/this.pixelsPerMeter,P=this._camera.forward(),z=this.point,H=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*S-g/this.worldSize*this._centerAltitude;return[z.x/this.worldSize-P[0]*H,z.y/this.worldSize-P[1]*H,g/this.worldSize*this._centerAltitude-P[2]*H]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(g){const S=this._maxCameraBoundsDistance()*Math.cos(this._pitch),P=this._camera.position[2],z=g[2];let H=1;this.projection.wrap&&(this.center=this.center.wrap()),z>0&&(H=Math.min((S-P)/z,1)),this._camera.position=o.bg([],this._camera.position,g,H),this._updateStateFromCamera()}_updateStateFromCamera(){const g=this._camera.position,S=this._camera.forward(),{pitch:P,bearing:z}=this._camera.getPitchBearing(),H=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,G=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),ee=Math.max((g[2]-H)/Math.cos(P),G),ie=this._zoomFromMercatorZ(ee);o.bg(g,g,S,ee),this._pitch=o.aC(P,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(z,-Math.PI,Math.PI),this._setZoom(o.aC(ie,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 S=0,P=o.cv,z=0,H=1/0;for(;P-S>1e-6&&P>S;){const G=S+.5*(P-S),ee=this.tileSize*Math.pow(2,G),ie=this.getCameraToCenterDistance(this.projection,G,ee),pe=this.scaleZoom(ie/(Math.max(0,g)*this.tileSize)),ye=Math.abs(G-pe);yepe||Ae.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,S){const P=o.ai(o.ax([],this._camera.position,g)),z=this._zoomFromMercatorZ(P)+S;return P-this._mercatorZfromZoom(z)}getCameraPoint(){if(this.projection.name==="globe"){const g=function([S,P,z],H){const G=[S,P,z,1];o.aE(G,G,H);const ee=G[3]=Math.max(G[3],1e-6);return G[0]/=ee,G[1]/=ee,G[2]/=ee,G}([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,S=this.zoom,P=this.worldSize){const z=o.cy(g,S,this.width,this.height,1024),H=g.pixelSpaceConversion(this.center.lat,P,z);let G=.5/Math.tan(.5*this._fov)*this.height*H;return this.isOrthographic&&(G=o.am(1,G,o.cL(this.pitch>=cp?1:this.pitch/cp))),G}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 wc=(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 S=M.transform,P=S.pitch,z=S.isLODDisabled(!1)?60:30;if(P0,uniformValues:{u_cutoff_params:[S._nearZ,S._farZ,(ye-S._nearZ)/H,(ye-Ae-S._nearZ)/H]}}},yf=2048;class _w{constructor(g,S){this.aabb=g,this.lastCascade=S}}class H2{add(g,S){const P=this.receivers[g.key];P!==void 0?(P.aabb.min[0]=Math.min(P.aabb.min[0],S.min[0]),P.aabb.min[1]=Math.min(P.aabb.min[1],S.min[1]),P.aabb.min[2]=Math.min(P.aabb.min[2],S.min[2]),P.aabb.max[0]=Math.max(P.aabb.max[0],S.max[0]),P.aabb.max[1]=Math.max(P.aabb.max[1],S.max[1]),P.aabb.max[2]=Math.max(P.aabb.max[2],S.max[2])):this.receivers[g.key]=new _w(S,null)}clear(){this.receivers={}}get(g){return this.receivers[g.key]}computeRequiredCascades(g,S,P){const z=o.cU.fromPoints(g.points);let H=0;for(const G in this.receivers){const ee=this.receivers[G];if(!ee||!z.intersectsAabb(ee.aabb))continue;ee.aabb.min=z.closestPoint(ee.aabb.min),ee.aabb.max=z.closestPoint(ee.aabb.max);const ie=ee.aabb.getCorners();for(let pe=0;pe1||Ae[1]<-1||Ae[1]>1){ye=!1;break}}if(ee.lastCascade=pe,H=Math.max(H,pe),ye)break}}return H+1}}class Vl{constructor(g){this.painter=g,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new H2,this._depthMode=new Jr(g.context.gl.LEQUAL,Jr.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,S){const P=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!S||!S.properties)return;const z=S.properties.get("shadow-intensity"),H=S.properties.get("shadow-draw-before-layer");if(!S.shadowsEnabled()||z<=0)return;let G=-1,ee=0;for(const dt of P.style.order){const jt=P.style._mergedLayers[dt];jt.hasShadowPass()&&!jt.isHidden(g.zoom)&&(G=ee),!H||H!==dt&&H!==jt.slot||(this._drawShadowAfterLayer=ee>0?ee-1:0),ee+=1}if(this._enabled=G>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=G);const ie=P.context,pe=yf,ye=yf;if(this._cascades.length===0||yf!==this._cascades[0].texture.size[0]){this._cascades=[];for(let dt=0;dt<2;++dt){const jt=ie.gl,Tt=ie.createFramebuffer(pe,ye,0,"texture"),ft=new o.T(ie,{width:pe,height:ye,data:null},jt.DEPTH_COMPONENT16);Tt.depthAttachment.set(ft.texture),this._cascades.push({framebuffer:Tt,texture:ft,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=G2(S);let De=0;if(g.elevation){const dt=g.elevation,jt=[1e4,-1e4];dt.visibleDemTiles.filter(Tt=>Tt.dem).forEach(Tt=>{const ft=Tt.dem.tree;jt[0]=Math.min(jt[0],ft.minimums[0]),jt[1]=Math.max(jt[1],ft.maximums[0])}),jt[0]!==1e4&&(De=(jt[1]-jt[0])*dt.exaggeration())}const Ae=1.5*g.cameraToCenterDistance,Be=3*Ae,tt=new Float64Array(16);for(let dt=0;dt=0)return{};const H=function(ie,pe,ye){const De=ye/(1<0&&(o.cT(H[1],H[1],[z[0]*G,0,0]),o.cT(H[2],H[2],[z[0]*G,0,0])),z[1]<0?(o.cT(H[0],H[0],[0,z[1]*G,0]),o.cT(H[1],H[1],[0,z[1]*G,0])):z[1]>0&&(o.cT(H[2],H[2],[0,z[1]*G,0]),o.cT(H[3],H[3],[0,z[1]*G,0]));const ee={};return ee.vertices=H,ee.planes=[_v(H[1],H[0],H[4]),_v(H[2],H[1],H[5]),_v(H[3],H[2],H[6]),_v(H[0],H[3],H[7])],ee}addShadowReceiver(g,S,P){this._receivers.add(g,o.cU.fromTileIdAndHeight(g,S,P))}getMaxCascadeForTile(g){const S=this._receivers.get(g);return S&&S.lastCascade?S.lastCascade:0}}function _v(M,g,S){const P=o.ax([],S,g),z=o.ax([],M,g),H=o.bh([],P,z),G=o.ai(H);return G===0?[0,0,1,0]:(o.bJ(H,H,1/G),[H[0],H[1],H[2],-o.bi(H,g)])}function G2(M){const g=M.properties.get("direction"),S=o.cP(g.x,g.y,g.z);S[2]=o.aC(S[2],0,75);const P=o.cR([S[0],S[1],S[2]]);return o.cQ(P.x,P.y,P.z)}function vf(M,g,S){const P=g.properties.get("color-use-theme")==="none",z=g.properties.get("color"),H=g.properties.get("intensity"),G=g.properties.get("direction"),ee=[G.x,G.y,G.z],ie=S.properties.get("color-use-theme")==="none",pe=S.properties.get("color"),ye=S.properties.get("intensity"),De=Math.max(o.bi([0,0,1],ee),0),Ae=[0,0,0];o.bJ(Ae,pe.toPremultipliedRenderColor(ie?null:M.getLut(g.scope)).toArray01Linear().slice(0,3),ye);const Be=[0,0,0];return o.bJ(Be,z.toPremultipliedRenderColor(P?null:M.getLut(S.scope)).toArray01Linear().slice(0,3),De*H),o.cW([Ae[0]>0?Ae[0]/(Ae[0]+Be[0]):0,Ae[1]>0?Ae[1]/(Ae[1]+Be[1]):0,Ae[2]>0?Ae[2]/(Ae[2]+Be[2]):0])}function sy(M,g,S,P,z,H){const G=M.zoom,ee=M.scale,ie=M.worldSize,pe=1/ie,ye=M.aspect,De=Math.sqrt(1+ye*ye)*Math.tan(.5*M.fovX),Ae=De*De,Be=P-S,tt=P+S;let Ye,ut;Ae>Be/tt?(Ye=P,ut=P*De):(Ye=.5*tt*(1+Ae),ut=.5*Math.sqrt(Be*Be+2*(P*P+S*S)*Ae+tt*tt*Ae*Ae));const dt=M.projection.pixelsPerMeter(M.center.lat,ie),jt=M._camera.getCameraToWorldMercator(),Tt=[0,0,-Ye*pe];o.ah(Tt,Tt,jt);let ft=ut*pe;const Kt=function(qs){return qs[0]/=ee,qs[1]/=ee,qs[2]=o.bU(qs[2],M._center.lat),qs},Rt=M._edgeInsets;if(!(Rt.left===0&&Rt.top===0&&Rt.right===0&&Rt.bottom===0||Rt.left===Rt.right&&Rt.top===Rt.bottom)){const qs=M._camera.getWorldToCamera(M.worldSize,M.projection.zAxisUnit==="meters"?dt:1),Cr=M._camera.getCameraToClipPerspective(M._fov,M.width/M.height,S,P);Cr[8]=2*-M.centerOffset.x/M.width,Cr[9]=2*M.centerOffset.y/M.height;const br=new Float64Array(16);o.cz(br,Cr,qs);const _r=new Float64Array(16);o.b7(_r,br);const nr=o.cl.fromInvProjectionMatrix(_r,ie,G,!0);for(const on of nr.points){const gn=Kt(on);ft=Math.max(ft,o.bK(o.cV([],Tt,gn)))}}ft*=z/(z-1);const Wt=Math.acos(g[2]),Et=Math.atan2(-g[0],-g[1]),Lt=new Dg;Lt.position=Tt,Lt.setPitchBearing(Wt,Et);const Vt=Lt.getWorldToCamera(ie,dt),ds=ft*ie,Zt=Math.min(M._mercatorZfromZoom(17)*ie*-2,-2*ds),Is=Lt.getCameraToClipOrthographic(-ds,ds,-ds,ds,Zt,(ds+H*dt)/g[2]),Ns=new Float64Array(16);o.aD(Ns,Is,Vt);const er=o.cQ(Math.floor(1e6*Tt[0])/1e6*ie,Math.floor(1e6*Tt[1])/1e6*ie,0),lr=.5*z,hs=[0,0,0];o.ah(hs,er,Ns),o.bJ(hs,hs,lr);const ss=[Math.floor(hs[0]),Math.floor(hs[1]),Math.floor(hs[2])],Ts=[0,0,0];o.ax(Ts,hs,ss),o.bJ(Ts,Ts,-1/lr);const Rs=new Float64Array(16);return o.b9(Rs),o.bx(Rs,Rs,Ts),o.aD(Ns,Rs,Ns),[Ns,ds]}class v4 extends o.E{constructor(g){super(),this.requestManager=g,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(g,S){return o.cX(this.requestManager.transformRequest(S,o.R.Model).url).then(P=>{const z=o.cY(P),H=new o.cZ(g,S,void 0,void 0,z);return H.computeBoundsAndApplyParent(),H}).catch(P=>{if(P&&P.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${g} from ${S}: ${P.message}`)))})}load(g,S,P={forceReload:!1}){this.models[S]||(this.models[S]={});const z=Object.keys(g),H=[],G=[];for(const ee of z){const ie=g[ee];this.hasURLBeenRequested(ie)&&!P.forceReload||(this.modelByURL[ie]={modelId:ee,scope:S},H.push(this.loadModel(ee,ie)),G.push(ee)),this.models[S][ee]||(this.models[S][ee]={model:null,numReferences:1})}this.numModelsLoading[S]=(this.numModelsLoading[S]||0)+G.length,Promise.allSettled(H).then(ee=>{for(let ie=0;ie{this.fire(new o.B(new Error(`Could not load models: ${ee.message}`)))})}isLoaded(){for(const g in this.numModelsLoading)if(this.numModelsLoading[g]>0)return!1;return!0}hasModel(g,S,P={exactIdMatch:!1}){return!!(P.exactIdMatch?this.getModel(g,S):this.getModelByURL(this.modelUris[S][g]))}getModel(g,S){return this.models[S]||(this.models[S]={}),this.models[S][g]?this.models[S][g].model:void 0}getModelByURL(g){if(!g)return null;const S=this.modelByURL[g];return S?this.models[S.scope][S.modelId].model:null}hasModelBeenAdded(g,S){return this.models[S]&&this.models[S][g]!==void 0}getModelURIs(g){return this.modelUris[g]||{}}addModel(g,S,P){this.models[P]||(this.models[P]={}),this.modelUris[P]||(this.modelUris[P]={});const z=this.requestManager.normalizeModelURL(S);if((this.hasModel(g,P,{exactIdMatch:!0})||this.hasModelBeenAdded(g,P))&&this.modelUris[P][g]===z)this.models[P][g].numReferences++;else if(this.hasURLBeenRequested(z)){const{scope:H,modelId:G}=this.modelByURL[z];this.models[H][G].numReferences++}else this.modelUris[P][g]=z,this.load({[g]:this.modelUris[P][g]},P)}addModelURLs(g,S){this.models[S]||(this.models[S]={}),this.modelUris[S]||(this.modelUris[S]={});const P=this.modelUris[S];for(const z in g)P[z]=this.requestManager.normalizeModelURL(g[z])}reloadModels(g){this.load(this.modelUris[g],g,{forceReload:!0})}addModelsFromBucket(g,S){this.models[S]||(this.models[S]={}),this.modelUris[S]||(this.modelUris[S]={});const P={};for(const z of g)this.hasModel(z,S,{exactIdMatch:!0})||this.hasURLBeenRequested(z)?this.models[S][z].numReferences++:this.modelUris[S][z]&&!this.hasURLBeenRequested(z)?P[z]=this.modelUris[S][z]:!this.hasURLBeenRequested(z)&&o.c_(z,!1)&&(this.modelUris[S][z]=this.requestManager.normalizeModelURL(z),P[z]=this.modelUris[S][z]);this.load(P,S)}hasURLBeenRequested(g){return this.modelByURL[g]!==void 0}removeModel(g,S,P=!1,z=!1){if(this.models[S]&&this.models[S][g]&&(this.models[S][g].numReferences--,this.models[S][g].numReferences===0||z)){const H=this.modelUris[S][g];P||delete this.modelUris[S][g],delete this.modelByURL[H];const G=this.models[S][g].model;if(!G)return;delete this.models[S][g],G.destroy()}}destroy(){for(const g of Object.keys(this.models))for(const S of Object.keys(this.models[g])){const P=this.models[g][S].model;delete this.models[g][S],P&&P.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,S){this.models[S]||(this.models[S]={});for(const P in this.models[S])this.models[S][P].model&&this.models[S][P].model.upload(g.context)}}const Rg=o.a8.colorTheme,zl=new o.ab({data:new o.ac(Rg.data)});function Ad(M){if(!M.metadata||!M.metadata.content_area)return;const g=o.o.devicePixelRatio,{left:S,top:P,width:z,height:H}=M.metadata.content_area,G=S*g,ee=P*g;return[G,ee,G+z*g,ee+H*g]}function Kc(M){if(M)return M.map(([g,S])=>[g*o.o.devicePixelRatio,S*o.o.devicePixelRatio])}class nb{constructor(g,S,P){this.id=g,this.scope=S,this.sourceCache=P,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 S=this.sourceCache.getVisibleCoordinates();if(S.length===0)return g;const P=this.sourceCache.getSource();if(!(P instanceof Vh))return g;const z=S.map(G=>this.sourceCache.getTile(G)),H=P.getImages(z,Array.from(this.pendingRequests));for(const[G,ee]of H)g.set(o.I.from({name:G,iconsetId:this.id}),ee),this.pendingRequests.delete(G);for(const G of this.pendingRequests)this.missingRequests.add(G);return this.pendingRequests.clear(),g}}class dp{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(g,S,P,z,H){if(Pie*this._hysteresisRatio&&(G=this._previousClosestBuildingId):pe&&!G&&(G=this._previousClosestBuildingId),this._previousClosestBuildingId=G,G}_calculateDistance(g,S){if(!S.center)return Number.MAX_VALUE;const P=g.lat-S.center[1],z=g.lng-S.center[0];return P*P+z*z}_isBuildingVisible(g,S,P){if(!P)return!1;for(const z of g.floorIds){const H=g.floors[z];if(!H.geometry)continue;const G=H.geometry;if(G.type==="Polygon"){const ee=this._convertRingToPoints(G.coordinates[0]);if(o.bw(ee,P))return!0}else if(G.type==="MultiPolygon"){const ee=this._convertMultiPolygonToPoints(G.coordinates);if(o.d0(P,ee))return!0}}return!1}_convertRingToPoints(g){return g.map(S=>new o.P(S[0],S[1]))}_convertMultiPolygonToPoints(g){return g.map(S=>S.length===0?[]:S[0].map(P=>new o.P(P[0],P[1])))}}class ww 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 dp,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 S=!1;for(const[P,z]of Object.entries(g.buildings))if(this._buildings[P])for(const H of z.floorIds)this._buildings[P].floorIds.add(H),this._buildings[P].floors[H]?this._mergeFloors(this._buildings[P].floors[H],z.floors[H]):(this._buildings[P].floors[H]=z.floors[H],S=!0);else this._buildings[P]=z,S=!0;S&&this._recalculateActiveFloors()}getIndoorTileOptions(g,S){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(g,S),indoorState:this._indoorState}:null}getControlState(){const g=this._buildings,S=this._closestBuildingId,P=S&&g?g[S]:void 0;if(!P)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let z=null;for(const G of P.floorIds)if(this._activeFloors&&this._activeFloors.has(G)){z=G;break}const H=Array.from(P.floorIds).map(G=>({id:G,name:P.floors[G].name,zIndex:P.floors[G].zIndex})).sort((G,ee)=>ee.zIndex-G.zIndex).filter((G,ee,ie)=>ee===0||G.zIndex!==ie[ee-1].zIndex);return{selectedFloorId:z,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:H}}_updateUI(){this._initialLoadDone=!0;const g=this._style.map.transform,S=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,g.center,g.zoom,g.getBounds(),this._makeViewportPolygon());if(S!==this._closestBuildingId){const P=this._closestBuildingId;this._closestBuildingId=S,this._onBuildingTransition(P,S),this._updateIndoorSelector()}}_onBuildingTransition(g,S){if(!this._indoorState)return;!S&&g?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!S&&!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(S,P){if(S===P)return!0;if(!S||!P||S.size!==P.size)return!1;for(const z of S)if(!P.has(z))return!1;return!0})(g,this._activeFloors)||(this._activeFloors=g,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(g,S){S.geometry&&(g.geometry?(g.geometry.type==="Polygon"&&(g.geometry={type:"MultiPolygon",coordinates:[g.geometry.coordinates]}),S.geometry.type==="Polygon"?g.geometry.coordinates.push(S.geometry.coordinates):S.geometry.type==="MultiPolygon"&&g.geometry.coordinates.push(...S.geometry.coordinates)):g.geometry=S.geometry)}_makeViewportPolygon(){const g=this._style.map.transform,S=g.width,P=g.height;return[g.pointLocation(new o.P(0,0)),g.pointLocation(new o.P(S,0)),g.pointLocation(new o.P(S,P)),g.pointLocation(new o.P(0,P))].map(z=>new o.P(z.lng,z.lat))}}const wv=(M,g)=>cr(M,g&&g.filter(S=>S.identifier!=="source.canvas")),_h=o.aJ(qa,["addLayer","removeLayer","setLights","setPaintProperty","setLayoutProperty","setLayerProperty","setSlot","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData","setTerrain","setFog","setSnow","setRain","setProjection","setCamera","addImport","removeImport","updateImport","addIconset","removeIconset"]),W2=o.aJ(qa,["setCenter","setZoom","setBearing","setPitch"]),jw=new Set(["background","sky","slot","custom"]),ab={version:8,layers:[],sources:{}},up={duration:300,delay:0};class Ic extends o.E{constructor(g,S={}){if(super(),this.map=g,this.scope=S.scope||"",this.globalId=null,this.fragments=[],this.importDepth=S.importDepth||0,this.importsCache=S.importsCache||new Map,this.resolvedImports=S.resolvedImports||new Set,this.transition=Object.assign({},up),this._buildingIndex=new Lg(this),this.crossTileSymbolIndex=new op,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=S.styleChanges||new Ce,this._hasDataDrivenEmissive=!1,this.indoorManager=new ww(this),this.dispatcher=S.dispatcher?S.dispatcher:new vt(Yt(),this),this.map.painter&&this.map.painter.context){const z=this.map.painter.context.maxUniformBufferBindings,H=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:z,maxUniformBlockSizeDwords:H,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}S.imageManager?this.imageManager=S.imageManager:(this.imageManager=new es(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=S.glyphManager?S.glyphManager:new o.d2(g._requestManager,S.localFontFamily?o.d3.all:S.localIdeographFontFamily?o.d3.ideographs:o.d3.none,S.localFontFamily||S.localIdeographFontFamily,S.useServerFontComposition),S.modelManager?this.modelManager=S.modelManager:(this.modelManager=new v4(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=S.configOptions?S.configOptions:new Map,this._configDependentLayers=S.configDependentLayers?S.configDependentLayers:new Set,this._indoorDependentLayers=S.indoorDependentLayers?S.indoorDependentLayers:new Set,this._config=S.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:S.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=S.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const P=this;this._rtlTextPluginCallback=Ic.registerForPluginStateChange(z=>{P.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:z.pluginStatus,pluginURL:z.pluginURL},(H,G)=>{if(o.d6(H),G&&G.every(ee=>ee))for(const ee in P._sourceCaches){const ie=P._sourceCaches[ee],pe=ie.getSource().type;pe!=="vector"&&pe!=="geojson"||ie.reload()}})}),this.on("data",z=>{if(z.dataType!=="source"||z.sourceDataType!=="metadata")return;const H=this.getOwnSource(z.sourceId);if(H&&H.vectorLayerIds)for(const G in this._layers){const ee=this._layers[G];ee.source===H.id&&this._validateLayer(ee)}})}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 S=o.d7(g);if(!S.startsWith("http"))try{return new URL(S,location.href).toString()}catch{return S}return S}return`json://${o.d8(JSON.stringify(g))}`}_diffStyle(g,S,P){this.globalId=this._getGlobalId(g);const z=(H,G)=>{try{G(null,this.setState(H,P))}catch(ee){G(ee,!1)}};if(typeof g=="string"){const H=this.map._requestManager.normalizeStyleURL(g),G=this.map._requestManager.transformRequest(H,o.R.Style);o.m(G,(ee,ie)=>{ee?this.fire(new o.B(ee)):ie&&z(ie,S)})}else typeof g=="object"&&z(g,S)}loadURL(g,S={}){this.fire(new o.C("dataloading",{dataType:"style"}));const P=typeof S.validate=="boolean"?S.validate:!o.e(g);this.globalId=this._getGlobalId(g),g=this.map._requestManager.normalizeStyleURL(g,S.accessToken),this.resolvedImports.add(g);const z=this.importsCache.get(g);if(z)return this._load(z,P);const H=this.map._requestManager.transformRequest(g,o.R.Style);this._request=o.m(H,(G,ee)=>{if(this._request=null,G)this.fire(new o.B(G));else if(ee)return this.importsCache.set(g,ee),this._load(ee,P)})}loadJSON(g,S={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(g),this._request=o.o.frame(()=>{this._request=null,this._load(g,S.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(ab,!1)}_loadImports(g,S,P){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const z=[];for(const H of g){const G=this._createFragmentStyle(H),ee=new Promise(ye=>{G.once("style.import.load",ye),G.once("error",ye)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(z.push(ee),this.resolvedImports.has(H.url)){G.loadEmpty();continue}const ie=H.data||this.importsCache.get(H.url);ie?(H.data?(G.fire(new o.C("dataloading",{dataType:"style"})),G.globalId=G._getGlobalId(ie),queueMicrotask(()=>G._load(ie,S))):G.loadJSON(ie,{validate:S}),this._isInternalStyle(ie)&&(G.globalId=null)):H.url?G.loadURL(H.url,{validate:S}):G.loadEmpty();const pe={style:G,id:H.id,config:H.config};if(P){const ye=this.fragments.findIndex(({id:De})=>De===P);this.fragments=this.fragments.slice(0,ye).concat(pe).concat(this.fragments.slice(ye))}else this.fragments.push(pe)}return Promise.allSettled(z)}getImportGlobalIds(g=this,S=new Set){for(const P of g.fragments)P.style.globalId&&S.add(P.style.globalId),this.getImportGlobalIds(P.style,S);return[...S.values()]}_createFragmentStyle(g){const S=this.scope?o.F(g.id,this.scope):g.id;let P;const z=this._initialConfig&&this._initialConfig[S];(g.config||z)&&(P=Object.assign({},g.config,z));const H=new Ic(this.map,{scope:S,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:P,configOptions:this.options,colorThemeOverride:g["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return H.setEventedParent(this.map,{style:H}),H}_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,S){if(this._isInternalStyle(g)){const H=Object.assign({},ab,{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(H,S)}if(this.updateConfig(this._config,g.schema),S&&wv(this,Qr(g)))return;this._loaded=!0;for(const H in g.sources)this.addSource(H,g.sources[H],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(g);const P=()=>{if(g.iconsets)for(const ie in g.iconsets)this.addIconset(ie,g.iconsets[ie]);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 H=np(this.stylesheet.layers);if(this._order=H.map(ie=>ie.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 ie=this.stylesheet.lights[0];this.light=new Kr(ie.properties,ie.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Kr(this.stylesheet.light)),this._layers={};for(const ie of H){const pe=o.de(ie,this.scope,this._styleColorTheme.lut,this.options);pe.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(pe.fqid),pe.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(pe.fqid),this._hasAppearances=this._hasAppearances||pe.getAppearances().length!==0,pe.setEventedParent(this,{layer:{id:pe.id}}),this._layers[pe.id]=pe;const ye=this.getOwnLayerSourceCache(pe),De=!!this.directionalLight&&this.directionalLight.shadowsEnabled();ye&&pe.canCastShadows()&&De&&(ye.castsShadows=!0)}if(this.glyphManager.url){const ie=new Set;for(const pe in this._layers){const ye=this._layers[pe];if(ye.type==="symbol"&&ye.layout){const De=ye.layout.get("text-font");De&&De.value&&De.value.kind==="constant"&&ie.add(De.value.value.join(","))}}for(const pe of ie)this.glyphManager.prefetchRange(pe,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const G=this.stylesheet.terrain;G&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(G,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 ee=this.isRootStyle();g.imports?this._loadImports(g.imports,S).then(()=>{this._reloadImports(),this.fire(new o.C(ee?"style.load":"style.import.load"))}).catch(ie=>{this.fire(new o.B(new Error("Failed to load imports",ie))),this.fire(new o.C(ee?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(ee?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const z=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(z){const H=this._evaluateColorThemeData(z);this._loadColorTheme(H).then(()=>{P()}).catch(G=>{o.w(`Couldn't load color theme from the stylesheet: ${G}`),P()})}else this._styleColorTheme.lut=null,P()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(g=>g.style.hasAppearances())}mergeAll(){let g,S,P,z,H,G,ee,ie,pe,ye;const De={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Ae=>{if(Ae.stylesheet){if(Ae.light!=null&&(g=Ae.light),Ae.stylesheet.lights)for(const Be of Ae.stylesheet.lights)Be.type==="ambient"&&Ae.ambientLight!=null&&(S=Ae.ambientLight),Be.type==="directional"&&Ae.directionalLight!=null&&(P=Ae.directionalLight);z=this._prioritizeTerrain(z,Ae.terrain,Ae.stylesheet.terrain),Ae.stylesheet.fog&&Ae.fog!=null&&(H=Ae.fog),Ae.stylesheet.snow&&Ae.snow!=null&&(G=Ae.snow),Ae.stylesheet.rain&&Ae.rain!=null&&(ee=Ae.rain),Ae.stylesheet.camera!=null&&(ye=Ae.stylesheet.camera),Ae.stylesheet.projection!=null&&(ie=Ae.stylesheet.projection),Ae.stylesheet.transition!=null&&(pe=Ae.stylesheet.transition),De[Ae.scope]=Ae._styleColorTheme}}),this.light=g,this.ambientLight=S,this.directionalLight=P,this.fog=H,this.snow=G,this.rain=ee,this._styleColorThemeForScope=De,z===null?delete this.terrain:this.terrain=z,this.camera=ye||{"camera-projection":"perspective"},this.projection=ie||{name:"mercator"},this.transition=Object.assign({},up,pe),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(g){const S=P=>{for(const z of P.fragments)S(z.style);g(P)};S(this)}_prioritizeTerrain(g,S,P){const z=g&&g.drapeRenderMode===0;return P===null?S&&S.drapeRenderMode===0?S:z?g:null:S!=null&&(!g||z||S&&S.drapeRenderMode===1)?S:g}mergeTerrain(){let g;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(S=>{g=this._prioritizeTerrain(g,S.terrain,S.stylesheet.terrain)}),g===null?delete this.terrain:this.terrain=g}mergeProjection(){let g;this.forEachFragmentStyle(S=>{S.stylesheet.projection!=null&&(g=S.stylesheet.projection)}),this.projection=g||{name:"mercator"}}mergeSources(){const g={},S={},P={},z={};this.forEachFragmentStyle(H=>{for(const G in H._sourceCaches){const ee=o.F(G,H.scope);g[ee]=H._sourceCaches[G]}for(const G in H._otherSourceCaches){const ee=o.F(G,H.scope);S[ee]=H._otherSourceCaches[G]}for(const G in H._symbolSourceCaches){const ee=o.F(G,H.scope);P[ee]=H._symbolSourceCaches[G]}for(const G in H._fillExtrusionSourceCaches){const ee=o.F(G,H.scope);z[ee]=H._fillExtrusionSourceCaches[G]}}),this._mergedSourceCaches=g,this._mergedOtherSourceCaches=S,this._mergedSymbolSourceCaches=P,this._mergedFillExtrusionSourceCaches=z}mergeIndoor(){this.forEachFragmentStyle(g=>{if(g.stylesheet&&g.stylesheet.indoor)for(const S of Object.values(g.stylesheet.indoor)){const P=S,z=o.F(P.sourceId,g.scope);this._mergedIndoor[z]=new Set(P.sourceLayers||[])}})}mergeLayers(){const g={},S=[],P={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(G=>{for(const ee of G._order){const ie=G._layers[ee];if(ie.type==="slot"){const pe=o.da(ee);if(g[pe])continue;g[pe]=[]}ie.slot&&g[ie.slot]?g[ie.slot].push(ie):S.push(ie)}}),this._mergedOrder=[];let z=-1;const H=(G=[])=>{for(const ee of G)if(ee.type==="slot"){const ie=o.da(ee.id);g[ie]&&H(g[ie]),this._mergedSlots.push(ie)}else{const ie=o.F(ee.id,ee.scope);this._mergedOrder.push(ie),P[ie]=ee,ee.is3D(!!this.terrain)&&(this._has3DLayers=!0,z=this._mergedOrder.length-1),ee.type==="circle"&&(this._hasCircleLayers=!0),ee.type==="symbol"&&(this._hasSymbolLayers=!0),ee.type==="clip"&&(this._clipLayerPresent=!0)}};if(H(S),this._has3DLayers){const G={};for(let ee=0;eeG[ee]-G[ie])}this._mergedLayers=P,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(S,P,z){const H=Object.assign({},P);for(const ee of Object.keys(Rg))H[ee]===void 0&&(H[ee]=Rg[ee].default);const G=new o.aa(zl,S,new Map(z));return G.setTransitionOrValue(H,z),G.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 S=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((P,z)=>{const H="data:image/png;base64,";if(!g||g.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void P();let G=g;G.startsWith(H)||(G=H+G);const ee=o.I.from("mapbox-reserved-lut"),ie=new Image;ie.src=G,ie.onerror=()=>{this._styleColorTheme.lutLoading=!1,z(new Error("Failed to load image data"))},ie.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==S)return void P();this._styleColorTheme.lutLoading=!1;const{width:pe,height:ye,data:De}=o.o.getImageData(ie);if(ye>32)return void z(new Error("The height of the image must be less than or equal to 32 pixels."));if(pe!==ye*ye)return void z(new Error("The width of the image must be equal to the height squared."));this.getImage(ee)&&this.removeImage(ee),this.addImage(ee,{data:new o.q({width:pe,height:ye},De),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Ae=this.imageManager.getImage(ee,this.scope);Ae?(this._styleColorTheme.lut={image:Ae.data,data:g},P()):z(new Error("Missing LUT image."))}})}getLut(g){const S=this._styleColorThemeForScope[g];return S?S.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(S,P,z){let H,G,ee;const ie=o.o.devicePixelRatio>1?"@2x":"";let pe=o.m(P.transformRequest(P.normalizeSpriteURL(S,ie,".json"),o.R.SpriteJSON),(Ae,Be)=>{pe=null,ee||(ee=Ae,H=Be,De())}),ye=o.n(P.transformRequest(P.normalizeSpriteURL(S,ie,".png"),o.R.SpriteImage),(Ae,Be)=>{ye=null,ee||(ee=Ae,G=Be,De())});function De(){if(ee)z(ee);else if(H&&G){const Ae=o.o.getImageData(G),Be={};for(const tt in H){const{width:Ye,height:ut,x:dt,y:jt,sdf:Tt,pixelRatio:ft,stretchX:Kt,stretchY:Rt,content:Wt}=H[tt],Et=new o.q({width:Ye,height:ut});o.q.copy(Ae,Et,{x:dt,y:jt},{x:0,y:0},{width:Ye,height:ut},null),Be[tt]={data:Et,pixelRatio:ft!==void 0?ft:1,sdf:Tt!==void 0&&Tt,stretchX:Kt,stretchY:Rt,content:Wt,usvg:!1,version:0}}z(null,Be)}}return{cancel(){pe&&(pe.cancel(),pe=null),ye&&(ye.cancel(),ye=null)}}}(g,this.map._requestManager,(S,P)=>{if(this._spriteRequest=null,S)this.fire(new o.B(S));else if(P){const z=new Map;for(const H in P)z.set(o.I.from(H),P[H]);this.addImages(z)}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,S){if(S.type==="sprite")return void this._loadSprite(S.url);const P=this.getOwnSourceCache(S.source);if(!P)return void this.fire(new o.B(new Error(`Source "${S.source}" as specified by iconset "${g}" does not exist and cannot be used as an iconset source`)));const z=P.getSource();if(z.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${S.source}" as specified by iconset "${g}" is not a "raster-array" source and cannot be used as an iconset source`)));z.partial=!1;const H=new nb(g,this.scope,P);this.imageManager.addImageProvider(H,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 S=this.map._spriteFormat==="auto";var P,z;this._spriteRequest=(z=(H,G)=>{if(this._spriteRequest=null,H)S?this._loadSprite(g):this.fire(new o.B(H));else if(G){const ee=new Map;for(const ie in G)ee.set(o.I.from(ie),G[ie]);this.addImages(ee)}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((P=this.map._requestManager).transformRequest(P.normalizeIconsetURL(g),o.R.Iconset),(H,G)=>{if(H)return void z(H);const ee={},ie=o.c$(new o.a$(G));for(const pe of ie.icons){const ye={version:1,pixelRatio:o.o.devicePixelRatio,content:Ad(pe),stretchX:pe.metadata?Kc(pe.metadata.stretch_x_areas):void 0,stretchY:pe.metadata?Kc(pe.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:pe};ee[pe.name]=ye}z(null,ee)}))}_validateLayer(g){const S=this.getOwnSource(g.source);if(!S)return;const P=g.sourceLayer;P&&(S.type==="geojson"||S.vectorLayerIds&&S.vectorLayerIds.indexOf(P)===-1)&&this.fire(new o.B(new Error(`Source layer "${P}" does not exist on source "${S.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,S)=>{const P=this.fragments[S];return P&&P.style&&(g.data=P.style.serialize()),g})}_serializeSources(){const g={};for(const S in this._sourceCaches){const P=this._sourceCaches[S].getSource();g[P.id]||(g[P.id]=P.serialize())}return g}_serializeLayers(g){const S=[];for(const P of g){const z=this._layers[P];z&&z.type!=="custom"&&S.push(z.serialize())}return S}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 S=this._mergedLayers[g];if(S._transitionablePaint&&S._transitionablePaint._values){const P=S._transitionablePaint._values["line-emissive-strength"];if(P&&P.value&&P.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 S=this.getOwnLayer(g);if(S)return S;this.fire(new o.B(new Error(`The layer '${g}' does not exist in the map's style.`)))}_checkSource(g){const S=this.getOwnSource(g);if(S)return S;this.fire(new o.B(new Error(`The source '${g}' does not exist in the map's style.`)))}precompilePrograms(g,S){const P=this.map.painter;if(P)for(let z=g.minzoom||0;z<(g.maxzoom||25.5);z++){const H=g.getProgramIds();if(H)for(const G of H){const ee=g.getDefaultProgramParams(G,S.zoom,this._styleColorTheme.lut);ee&&(P.style=this,this.fog&&(P._fogVisible=!0,ee.overrideFog=!0,P.getOrCreateProgram(G,ee)),P._fogVisible=!1,ee.overrideFog=!1,P.getOrCreateProgram(G,ee),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(ee.overrideRtt=!0,P.getOrCreateProgram(G,ee)))}}}update(g){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(g),this.directionalLight&&this.directionalLight.recalculate(g);const S=this.calculateLightsBrightness();g.brightness=S||0,S!==this._brightness&&(this._brightness=S,this.dispatcher.broadcast("setBrightness",S)),g.worldview!==this._worldview&&(this._worldview=g.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const P=this._changes.isDirty();let z=!1;if(this._changes.isDirty()){const ie=this._changes.getLayerUpdatesByScope();for(const pe in ie){const{updatedIds:ye,removedIds:De}=ie[pe];(ye||De)&&(this._updateWorkerLayers(pe,ye,De),z=!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 H={};for(const ie in this._mergedSourceCaches){const pe=this._mergedSourceCaches[ie];H[ie]=pe.used,pe.used=!1,pe.tileCoverLift=0}const G={};for(const ie of this._mergedOrder){const pe=this._mergedLayers[ie];if((pe.visibility!=="none"||pe.hasTransition())&&pe.recalculate(g,this._availableImages),!pe.isHidden(g.zoom)){const ye=this.getLayerSourceCache(pe);ye&&(ye.used=!0,ye.tileCoverLift=Math.max(ye.tileCoverLift,pe.tileCoverLift()))}if(pe.type==="fill-extrusion"){const ye=o.F(pe.source,pe.scope);if(ye in this._mergedFillExtrusionSourceCaches){const De=pe.layout&&pe.layout.get("source-max-zoom");if(De!=null){const Ae=G[ye];G[ye]=Ae==null?De:Math.min(Ae,De)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(pe,g)}):this.precompilePrograms(pe,g))}this._shouldPrecompile&&(this._precompileDone=!0);for(const ie in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[ie].setMaxzoomOverride(G[ie]!=null?G[ie]:null);this.terrain&&z&&this.mergeLayers();const ee=this.imageManager.getPendingImageProviders();for(const ie of ee)ie.sourceCache.used=!0;for(const ie in H){const pe=this._mergedSourceCaches[ie];H[ie]!==pe.used&&pe.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:pe.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),P&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const g=this.imageManager.getPendingImageProviders();for(const S of g){const P=S.resolvePendingRequests(),z=this.getFragmentStyle(S.scope);z&&z.addImages(P)}}_updateTilesForChangedImages(){const g={};for(const S in this._mergedSourceCaches){const P=this._mergedSourceCaches[S].getSource().scope;g[P]=g[P]||this._changes.getUpdatedImages(P),g[P].length!==0&&this._mergedSourceCaches[S].reloadTilesForDependencies(["icons","patterns"],g[P])}for(const S in g)this._changes.resetUpdatedImages(S)}_updateWorkerLayers(g,S,P){const z=this.getFragmentStyle(g);z&&this.dispatcher.broadcast("updateLayers",{layers:S?z._serializeLayers(S):[],scope:g,removedIds:P||[],options:z.options})}setState(g,S){if(this._checkLoaded(),wv(this,Qr(g)))return!1;(g=o.d9(g)).layers=np(g.layers);const P=function(G,ee){if(!G)return[{command:qa.setStyle,args:[ee]}];let ie=[];try{if(!o.b6(G.version,ee.version))return[{command:qa.setStyle,args:[ee]}];if(o.b6(G.center,ee.center)||ie.push({command:qa.setCenter,args:[ee.center]}),o.b6(G.zoom,ee.zoom)||ie.push({command:qa.setZoom,args:[ee.zoom]}),o.b6(G.bearing,ee.bearing)||ie.push({command:qa.setBearing,args:[ee.bearing]}),o.b6(G.pitch,ee.pitch)||ie.push({command:qa.setPitch,args:[ee.pitch]}),o.b6(G.sprite,ee.sprite)||ie.push({command:qa.setSprite,args:[ee.sprite]}),o.b6(G.glyphs,ee.glyphs)||ie.push({command:qa.setGlyphs,args:[ee.glyphs]}),o.b6(G.imports,ee.imports)||function(Be=[],tt=[],Ye){tt=tt||[];const ut=(Be=Be||[]).map(Up),dt=tt.map(Up),jt=Be.reduce(Rx,{}),Tt=tt.reduce(Rx,{}),ft=ut.slice();let Kt,Rt,Wt,Et;for(Kt=0,Rt=0;Kt{Be.source&&pe[Be.source]?ie.push({command:qa.removeLayer,args:[Be.id]}):De.push(Be)});let Ae=G.terrain;Ae&&pe[Ae.source]&&(ie.push({command:qa.setTerrain,args:[void 0]}),Ae=void 0),ie=ie.concat(ye),o.b6(Ae,ee.terrain)||ie.push({command:qa.setTerrain,args:[ee.terrain]}),function(Be,tt,Ye){tt=tt||[];const ut=(Be=Be||[]).map(Up),dt=tt.map(Up),jt=Be.reduce(Rx,{}),Tt=tt.reduce(Rx,{}),ft=ut.slice(),Kt=Object.create(null);let Rt,Wt,Et,Lt,Vt,ds,Zt;for(Rt=0,Wt=0;Rt!(G.command in W2));if(P.length===0)return!1;const z=P.filter(G=>!(G.command in _h));if(z.length>0)throw new Error(`Unimplemented: ${z.map(G=>G.command).join(", ")}.`);const H=[];return P.forEach(G=>{H.push(this[G.command](...G.args))}),S&&Promise.all(H).then(S).catch(S),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[S,P]of g.entries()){if(this.getImage(S))return this.fire(new o.B(new Error(`An image with the name "${S.name}" already exists.`)));this.imageManager.addImage(S,this.scope,P),this._changes.updateImage(S,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(g,S){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,S),this._changes.updateImage(g,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(g,S,P=!1){this.imageManager.updateImage(g,this.scope,S),P&&(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,S,P={}){return this._checkLoaded(),this._validate(Bs,`models.${g}`,S,null,P)||(this.modelManager.addModel(g,S,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,S,P={}){if(this._checkLoaded(),this.getOwnSource(g)!==void 0)throw new Error(`There is already a source with ID "${g}".`);if(!S.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(S).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(S.type)>=0&&this._validate(Tn,`sources.${g}`,S,null,P))return;this.map&&this.map._collectResourceTiming&&(S.collectResourceTiming=!0);const z=Y0(g,S,this.dispatcher,this);z.scope=this.scope,z.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(z.id),source:z.serialize(),sourceId:z.id}));const H=G=>{const ee=(G===o.b4.Symbol?"symbol:":G===o.b4.FillExtrusion?"fill-extrusion:":"other:")+z.id,ie=o.F(ee,this.scope),pe=this._sourceCaches[ee]=new Xo(ie,z,G);G===o.b4.Symbol?this._symbolSourceCaches[z.id]=pe:G===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[z.id]=pe:this._otherSourceCaches[z.id]=pe,pe.onAdd(this.map)};H(o.b4.Other),S.type!=="vector"&&S.type!=="geojson"||(H(o.b4.Symbol),S.type==="vector"&&H(o.b4.FillExtrusion)),z.onAdd&&z.onAdd(this.map),P.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(g){this._checkLoaded();const S=this.getOwnSource(g);if(!S)throw new Error("There is no source with this ID");for(const z in this._layers)if(this._layers[z].source===g)return this.fire(new o.B(new Error(`Source "${g}" cannot be removed while layer "${z}" 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 z=Object.entries(this.stylesheet.iconsets).find(([H,G])=>G.type==="source"&&G.source===g);if(z)return this.fire(new o.B(new Error(`Source "${g}" cannot be removed while iconset "${z[0]}" is using it.`)))}const P=this.getOwnSourceCaches(g);for(const z of P){const H=o.da(z.id);delete this._sourceCaches[H],this._changes.discardSourceCacheUpdate(z.id),z.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:z.getSource().id})),z.setEventedParent(null),z.clearTiles()}return delete this._otherSourceCaches[g],delete this._symbolSourceCaches[g],delete this._fillExtrusionSourceCaches[g],this.mergeSources(),S.setEventedParent(null),S.onRemove&&S.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(g,S){this._checkLoaded(),this.getOwnSource(g).setData(S),this._changes.setDirty()}getOwnSource(g){const S=this.getOwnSourceCache(g);return S&&S.getSource()}getOwnSources(){const g=[];for(const S in this._otherSourceCaches){const P=this.getOwnSourceCache(S);P&&g.push(P.getSource())}return g}areTilesLoaded(){const g=this._mergedSourceCaches;for(const S in g){const P=g[S]._tiles;for(const z in P){const H=P[z];if(H.state!=="loaded"&&H.state!=="errored")return!1}}return!0}setLights(g){if(this._checkLoaded(),!g)return delete this.ambientLight,void delete this.directionalLight;const S=this._getTransitionParameters();for(const H of g){if(this._validate(Re,"lights",H))return;switch(H.type){case"ambient":if(this.ambientLight){const G=this.ambientLight;G.set(H),G.updateTransitions(S)}else this.ambientLight=new vr(H,Ca(),this.scope,this.options);break;case"directional":if(this.directionalLight){const G=this.directionalLight;G.set(H),G.updateTransitions(S)}else this.directionalLight=new vr(H,Zo(),this.scope,this.options)}}const P=Object.assign(S,{worldview:this.map.getWorldview()}),z=new o.ae(this.z||0,P);this.ambientLight&&this.ambientLight.recalculate(z),this.directionalLight&&this.directionalLight.recalculate(z),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const g=this.directionalLight,S=this.ambientLight;if(!g||!S)return;const P=Ae=>.2126*(Ae[0]<=.03928?Ae[0]/12.92:Math.pow((Ae[0]+.055)/1.055,2.4))+.7152*(Ae[1]<=.03928?Ae[1]/12.92:Math.pow((Ae[1]+.055)/1.055,2.4))+.0722*(Ae[2]<=.03928?Ae[2]/12.92:Math.pow((Ae[2]+.055)/1.055,2.4)),z=g.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),H=g.properties.get("intensity"),G=g.properties.get("direction"),ee=1-o.cP(G.x,G.y,G.z)[2]/90,ie=P(z)*H*ee,pe=S.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),ye=S.properties.get("intensity"),De=P(pe)*ye;return Number(((ie+De)/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 S=o.dc(g),P=this.fragments.find(({id:H})=>H===S);if(!P)return;const z=o.da(g);return P.style.getFragmentStyle(z)}{const S=this.fragments.find(({id:P})=>P===g);return S?S.style:void 0}}setFeaturesetSelectors(g){if(!g)return;const S=(P,z="")=>`${P}::${z}`;this._featuresetSelectors={};for(const P in g){const z={},H=this._featuresetSelectors[P]=[];for(const G of g[P].selectors){if(G.featureNamespace){const ie=this.getOwnLayer(G.layer);if(!ie){o.w(`Layer is undefined for selector: ${G.layer}`);continue}const pe=S(ie.source,ie.sourceLayer);if(pe in z&&z[pe]!==G.featureNamespace){o.w(`"featureNamespace ${G.featureNamespace} of featureset ${P}'s selector is not associated to the same source, skip this selector`);continue}z[pe]=G.featureNamespace}let ee;if(G.properties)for(const ie in G.properties){const pe=o.X(G.properties[ie]);pe.result==="success"&&(ee=ee||{},ee[ie]=pe.value)}H.push({layerId:G.layer,namespace:G.featureNamespace,properties:ee,uniqueFeatureID:G._uniqueFeatureID})}}}getFeaturesetDescriptors(g){const S=this.getFragmentStyle(g);if(!S||!S.stylesheet.featuresets)return[];const P=[];for(const z in S.stylesheet.featuresets)P.push({featuresetId:z,importId:S.scope?S.scope:void 0});return P}getFeaturesetLayers(g,S){const P=this.getFragmentStyle(S),z=P.stylesheet.featuresets;if(!z||!z[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 H=[];for(const G of z[g].selectors){const ee=P.getOwnLayer(G.layer);ee&&H.push(ee)}return H}getConfigProperty(g,S){const P=this.getFragmentStyle(g);if(!P)return null;const z=o.F(S,P.scope),H=P.options.get(z),G=H?H.value||H.default:null;return G?G.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(g,S){const P=o.F(g,S);return this._mergedIndoor[P]}setIndoorData(g,S){this.indoorManager.setIndoorData(S)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(g,S,P){const z=this.getFragmentStyle(g);if(!z)return;const H=z.stylesheet.schema;if(!H||!H[S])return;const G=o.X(P);if(G.result!=="success")return void wv(this,G.value);const ee=G.value.expression,ie=o.F(S,z.scope),pe=z.options.get(ie);if(!pe)return;let ye;const{minValue:De,maxValue:Ae,stepValue:Be,type:tt,values:Ye}=H[S],ut=o.X(H[S].default);ut.result==="success"&&(ye=ut.value.expression),ye?(this.options.set(ie,Object.assign({},pe,{value:ee,default:ye,minValue:De,maxValue:Ae,stepValue:Be,type:tt,values:Ye})),this.updateConfigDependencies(S)):this.fire(new o.B(new Error(`No schema defined for the config option "${S}" in the "${g}" fragment.`)))}getConfig(g){const S=this.getFragmentStyle(g);if(!S)return null;const P=S.stylesheet.schema;if(!P)return null;const z={};for(const H in P){const G=o.F(H,S.scope),ee=S.options.get(G),ie=ee?ee.value||ee.default:null;z[H]=ie?ie.serialize():null}return z}setConfig(g,S){const P=this.getFragmentStyle(g);P&&(P.updateConfig(S,P.stylesheet.schema),this.updateConfigDependencies())}getSchema(g){const S=this.getFragmentStyle(g);return S?S.stylesheet.schema:null}setSchema(g,S){const P=this.getFragmentStyle(g);P&&(P.stylesheet.schema=S,P.updateConfig(P._config,S),this.updateConfigDependencies())}updateConfig(g,S){if(this._config=g,g||S)if(S)for(const P in S){let z,H;const G=o.X(S[P].default);if(G.result==="success"&&(z=G.value.expression),g&&g[P]!==void 0){const Ae=o.X(g[P]);Ae.result==="success"&&(H=Ae.value.expression)}const{minValue:ee,maxValue:ie,stepValue:pe,type:ye,values:De}=S[P];if(z){const Ae=o.F(P,this.scope);this.options.set(Ae,{default:z,value:H,minValue:ee,maxValue:ie,stepValue:pe,type:ye,values:De})}else this.fire(new o.B(new Error(`No schema defined for config option "${P}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(g,S=()=>!0){for(const P of g){const z=this.getLayer(P);z&&S(z)&&(z.possiblyEvaluateVisibility(),this._updateLayer(z),this._changes.setDirty())}}updateConfigDependencies(g){this._updateLayers(this._configDependentLayers,S=>!g||S.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(S=>{const P=S._styleColorTheme.colorThemeOverride?S._styleColorTheme.colorThemeOverride:S._styleColorTheme.colorTheme;if(P){const z=S._evaluateColorThemeData(P);(!S._styleColorTheme.lut&&z!==""||S._styleColorTheme.lut&&z!==S._styleColorTheme.lut.data)&&S.setColorTheme(P)}}),this._changes.setDirty()}addLayer(g,S,P={}){this._checkLoaded();const z=g.id;if(this._layers[z])return void this.fire(new o.B(new Error(`Layer with id "${z}" already exists on this map`)));let H;if(g.type==="custom"){if(wv(this,o.dd(g)))return;H=o.de(g,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof g.source=="object"&&(this.addSource(z,g.source),g=o.d9(g),g=Object.assign(g,{source:z})),this._validate(qt,`layers.${z}`,g,{arrayIndex:-1},P))return;H=o.de(g,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(H),H.setEventedParent(this,{layer:{id:z}})}const G=o.F(H.source,H.scope);H.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(G),H.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(G);let ee=this._order.length;if(S){const De=this._order.indexOf(S);if(De===-1)return void this.fire(new o.B(new Error(`Layer with id "${S}" does not exist on this map.`)));H.slot&&H.slot!==this._layers[S].slot?o.w(`Layer with id "${S}" has a different slot. Layers can only be rearranged within the same slot.`):ee=De}this._order.splice(ee,0,z),this._handleLayerOrderChange(),this._layers[z]=H;const ie=this.getOwnLayerSourceCache(H),pe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();ie&&H.canCastShadows()&&pe&&(ie.castsShadows=!0);const ye=this._changes.getRemovedLayer(H);if(ye&&H.source&&ie&&H.type!=="custom"){this._changes.discardLayerRemoval(H);const De=o.F(H.source,H.scope);ye.type!==H.type?this._changes.updateSourceCache(De,"clear"):(this._changes.updateSourceCache(De,"reload"),ie.pause())}this._updateLayer(H),H.onAdd&&H.onAdd(this.map),H.scope=this.scope,this.mergeLayers()}moveLayer(g,S){this._checkLoaded();const P=this._checkLayer(g);if(!P||g===S)return;const z=this._order.indexOf(g);this._order.splice(z,1);let H=this._order.length;if(S){const G=this._order.indexOf(S);if(G===-1)return void this.fire(new o.B(new Error(`Layer with id "${S}" does not exist on this map.`)));P.slot&&P.slot!==this._layers[S].slot?o.w(`Layer with id "${S}" has a different slot. Layers can only be rearranged within the same slot.`):H=G}this._order.splice(H,0,g),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(g){this._checkLoaded();const S=this._checkLayer(g);if(!S)return;S.setEventedParent(null);const P=this._order.indexOf(g);this._order.splice(P,1),delete this._layers[g],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(S.fqid),this._indoorDependentLayers.delete(S.fqid),this._changes.removeLayer(S);const z=this.getOwnLayerSourceCache(S);if(z&&z.castsShadows){let H=!1;for(const G in this._layers)if(this._layers[G].source===S.source&&this._layers[G].canCastShadows()){H=!0;break}z.castsShadows=H}S.onRemove&&S.onRemove(this.map),this.mergeLayers()}getOwnLayer(g){return this._layers[g]}hasLayer(g){return g in this._mergedLayers}hasLayerType(g){for(const S in this._layers)if(this._layers[S].type===g)return!0;return!1}setLayerZoomRange(g,S,P){this._checkLoaded();const z=this._checkLayer(g);z&&(z.minzoom===S&&z.maxzoom===P||(S!=null&&(z.minzoom=S),P!=null&&(z.maxzoom=P),this._updateLayer(z)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(g,S){this._checkLoaded();const P=this._checkLayer(g);P&&P.slot!==S&&(P.slot=S,this._updateLayer(P))}setFilter(g,S,P={}){this._checkLoaded();const z=this._checkLayer(g);if(z&&!o.b6(z.filter,S))return S==null?(z.filter=void 0,void this._updateLayer(z)):void(this._validate(cs,`layers.${z.id}.filter`,S,{layerType:z.type},P)||(z.filter=o.d9(S),this._updateLayer(z)))}getFilter(g){const S=this._checkLayer(g);if(S)return o.d9(S.filter)}setLayoutProperty(g,S,P,z={}){this._checkLoaded();const H=this._checkLayer(g);if(H&&!o.b6(H.getLayoutProperty(S),P)){if(P!=null&&(!z||z.validate!==!1)&&wv(H,Xt.call(Qr,{key:`layers.${g}.layout.${S}`,layerType:H.type,objectKey:S,value:P,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;H.setLayoutProperty(S,P),H.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(H.fqid),H.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(H.fqid),this._updateLayer(H)}}setLayerProperty(g,S,P,z={}){this._checkLoaded();const H=this._checkLayer(g);H&&(S==="appearances"?(H.setAppearances(P),this._updateLayer(H)):H.isPaintProperty(S)?this.setPaintProperty(g,S,P,z):this.setLayoutProperty(g,S,P,z))}getLayoutProperty(g,S){const P=this._checkLayer(g);if(P)return P.getLayoutProperty(S)}setPaintProperty(g,S,P,z={}){this._checkLoaded();const H=this._checkLayer(g);if(!H||o.b6(H.getPaintProperty(S),P)||P!=null&&(!z||z.validate!==!1)&&wv(H,it.call(Qr,{key:`layers.${g}.paint.${S}`,layerType:H.type,objectKey:S,value:P,styleSpec:o.a8})))return;const G=H.setPaintProperty(S,P);H.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(H.fqid),H.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(H.fqid),G&&this._updateLayer(H),this._changes.updatePaintProperties(H)}getPaintProperty(g,S){const P=this._checkLayer(g);if(P)return P.getPaintProperty(S)}setFeatureState(g,S){if(this._checkLoaded(),"target"in g){if("featuresetId"in g.target){const{featuresetId:ie,importId:pe}=g.target,ye=this.getFragmentStyle(pe),De=ye.getFeaturesetLayers(ie);for(const{source:Ae,sourceLayer:Be}of De)ye.setFeatureState({id:g.id,source:Ae,sourceLayer:Be},S)}else if("layerId"in g.target){const{layerId:ie}=g.target,pe=this.getLayer(ie);this.setFeatureState({id:g.id,source:pe.source,sourceLayer:pe.sourceLayer},S)}return}const P=g.source,z=g.sourceLayer,H=this._checkSource(P);if(!H)return;const G=H.type;if(G==="geojson"&&z)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(G==="vector"&&!z)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 ee=this.getOwnSourceCaches(P);for(const ie of ee)ie.setFeatureState(z,g.id,S)}removeFeatureState(g,S){if(this._checkLoaded(),"target"in g){if("featuresetId"in g.target){const{featuresetId:ie,importId:pe}=g.target,ye=this.getFragmentStyle(pe),De=ye.getFeaturesetLayers(ie);for(const{source:Ae,sourceLayer:Be}of De)ye.removeFeatureState({id:g.id,source:Ae,sourceLayer:Be},S)}else if("layerId"in g.target){const{layerId:ie}=g.target,pe=this.getLayer(ie);this.removeFeatureState({id:g.id,source:pe.source,sourceLayer:pe.sourceLayer},S)}return}const P=g.source,z=this._checkSource(P);if(!z)return;const H=z.type,G=H==="vector"?g.sourceLayer:void 0;if(H==="vector"&&!G)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(S&&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 ee=this.getOwnSourceCaches(P);for(const ie of ee)ie.removeFeatureState(G,g.id,S)}getFeatureState(g){if(this._checkLoaded(),"target"in g){let H;if("featuresetId"in g.target){const{featuresetId:G,importId:ee}=g.target,ie=this.getFragmentStyle(ee),pe=ie.getFeaturesetLayers(G);for(const{source:ye,sourceLayer:De}of pe){const Ae=ie.getFeatureState({id:g.id,source:ye,sourceLayer:De});if(Ae&&!H)H=Ae;else if(!o.b6(H,Ae))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:G}=g.target,ee=this.getLayer(G);H=this.getFeatureState({id:g.id,source:ee.source,sourceLayer:ee.sourceLayer})}return H}const S=g.source,P=g.sourceLayer,z=this._checkSource(S);if(z){if(z.type!=="vector"||P)return g.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(S)[0].getFeatureState(P,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(),S=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:S,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)},P=>P!==void 0)}_updateFilteredLayers(g){for(const S of Object.values(this._mergedLayers))g(S)&&this._updateLayer(S)}_updateLayer(g){this._changes.updateLayer(g);const S=this.getLayerSourceCache(g),P=o.F(g.source,g.scope),z=this._changes.getUpdatedSourceCaches();g.source&&!z[P]&&S&&S.getSource().type!=="raster"&&(this._changes.updateSourceCache(P,"reload"),S.pause()),g.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(g){const S=ee=>this._mergedLayers[ee].is3D(!!this.terrain),P=this.order,z={},H=[];for(let ee=P.length-1;ee>=0;ee--){const ie=P[ee];if(S(ie)){z[ie]=ee;for(const pe of g){const ye=pe[ie];if(ye)for(const De of ye)H.push(De)}}}H.sort((ee,ie)=>ie.intersectionZ-ee.intersectionZ);const G=[];for(let ee=P.length-1;ee>=0;ee--){const ie=P[ee];if(S(ie))for(let pe=H.length-1;pe>=0;pe--){const ye=H[pe].feature;if(ye.layer&&z[ye.layer.id]{if(jw.has(ye.type))return;const De=this.getOwnLayerSourceCache(ye),Ae=H[De.id]=H[De.id]||{sourceCache:De,layers:{},has3DLayers:!1};ye.is3D(!!this.terrain)&&(Ae.has3DLayers=!0),Ae.layers[ye.fqid]=Ae.layers[ye.fqid]||{styleLayer:ye,targets:[]},Ae.layers[ye.fqid].targets.push({filter:z})};if(S&&S.layers){if(!Array.isArray(S.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const ye of S.layers){const De=this._layers[ye];if(!De)return this.fire(new o.B(new Error(`The layer '${ye}' does not exist in the map's style and cannot be queried for features.`))),[];G(De)}}else for(const ye in this._layers)G(this._layers[ye]);const ee=this._queryRenderedFeatures(g,H,P),ie=this._flattenAndSortRenderedFeatures(ee),pe=[];for(const ye of ie)o.dh(ye.layer.id)===this.scope&&pe.push(ye);return pe}queryRenderedFeatureset(g,S,P){let z;S&&!Array.isArray(S)&&S.filter&&(this._validate(cs,"queryRenderedFeatures.filter",S.filter,null,S),z=o.dg(S.filter));const H="mock",G=[];if(S&&S.target)G.push(Object.assign({},S,{targetId:H,filter:z}));else{const ye=this.getFeaturesetDescriptors();for(const De of ye)G.push({targetId:H,filter:z,target:De});for(const{style:De}of this.fragments){const Ae=De.getFeaturesetDescriptors();for(const Be of Ae)G.push({targetId:H,filter:z,target:Be})}}const ee=this.queryRenderedTargets(g,G,P),ie=[],pe=new Set;for(const ye of ee)for(const De of ye.variants[H])Xu(De,ye,pe)||ie.push(new o.di(ye,De));return ie}queryRenderedTargets(g,S,P){const z={},H=(ee,ie,pe,ye)=>{const De=z[ie.id]=z[ie.id]||{sourceCache:ie,layers:{},has3DLayers:!1};if(De.layers[ee.fqid]=De.layers[ee.fqid]||{styleLayer:ee,targets:[]},ee.is3D(!!this.terrain)&&(De.has3DLayers=!0),!ye)return pe.uniqueFeatureID=!1,void De.layers[ee.fqid].targets.push(pe);De.layers[ee.fqid].targets.push(Object.assign({},pe,{namespace:ye.namespace,properties:ye.properties,uniqueFeatureID:ye.uniqueFeatureID}))};for(const ee of S)if("featuresetId"in ee.target){const{featuresetId:ie,importId:pe}=ee.target,ye=this.getFragmentStyle(pe);if(!ye||!ye._featuresetSelectors)continue;const De=ye._featuresetSelectors[ie];if(!De){this.fire(new o.B(new Error(`The featureset '${ie}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Ae of De){const Be=ye.getOwnLayer(Ae.layerId);Be&&!jw.has(Be.type)&&H(Be,ye.getOwnLayerSourceCache(Be),ee,Ae)}}else if("layerId"in ee.target){const{layerId:ie}=ee.target,pe=this.getLayer(ie);if(!pe||jw.has(pe.type))continue;H(pe,this.getLayerSourceCache(pe),ee)}const G=this._queryRenderedFeatures(g,z,P);return this._flattenAndSortRenderedFeatures(G)}_queryRenderedFeatures(g,S,P){const z=[],H=!!this.map._showQueryGeometry,G=vl.createFromScreenPoints(g,P);for(const ee in S){const ie=Bp(G,S[ee],this._availableImages,P,H,this.getActualScope());Object.keys(ie).length&&z.push(ie)}if(this.placement)for(const ee in S){if(S[ee].sourceCache._renderSourceType!==o.b4.Symbol)continue;const ie=co(G.screenGeometry,S[ee],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(ie).length&&z.push(ie)}return z}querySourceFeatures(g,S){const P=S&&S.filter;P&&this._validate(cs,"querySourceFeatures.filter",P,null,S);let z=[];const H=this.getOwnSourceCaches(g);for(const G of H)z=z.concat(X1(G,S));return z}addSourceType(g,S,P){return Ic.getSourceType(g)?P(new Error(`A source type called "${g}" already exists.`)):(Ic.setSourceType(g,S),S.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:g,url:S.workerSourceURL},P):P(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(g,S,P={}){this._checkLoaded();const z=this.light.getLight();let H=!1;for(const ee in g)if(!o.b6(g[ee],z[ee])){H=!0;break}if(!H)return;const G=this._getTransitionParameters();this.light.setLight(g,S,P),this.light.updateTransitions(G)}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,S=1){if(this._checkLoaded(),!g)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),S===0&&delete this.terrain,g===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let P=g;const z=!("source"in g)||g.source==null;if(S===1){if(this.disableElevatedTerrain)return;if("source"in P&&typeof P.source=="object"){const ee="terrain-dem-src";this.addSource(ee,P.source),P=o.d9(P),P=Object.assign(P,{source:ee})}const H=Object.assign({},P),G={};if(this.terrain&&z){H.source=this.terrain.get().source;const ee=this.terrain?this.getFragmentStyle(this.terrain.scope):null;ee&&(G.style=ee.serialize())}if(this._validate(Ke,"terrain",H,G))return}if(!this.terrain||this.terrain.scope!==this.scope&&!z||this.terrain&&S!==this.terrain.drapeRenderMode){if(!P)return;this._createTerrain(P,S),this.fire(new o.C("data",{dataType:"style"}))}else{const H=this.terrain,G=H.get();for(const ee of Object.keys(o.a8.terrain))!P.hasOwnProperty(ee)&&o.a8.terrain[ee].default&&(P[ee]=o.a8.terrain[ee].default);for(const ee in g)if(!o.b6(g[ee],G[ee])){H.set(g,this.options),this.stylesheet.terrain=g;const ie=this._getTransitionParameters({duration:0});H.updateTransitions(ie),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(g){const S=this.fog=new Fi(g,this.map.transform,this.scope,this.options);this.stylesheet.fog=S.get();const P=this._getTransitionParameters({duration:0});S.updateTransitions(P)}_createSnow(g){const S=this.snow=new Gi(g,this.map.transform,this.scope,this.options);this.stylesheet.snow=S.get();const P=this._getTransitionParameters({duration:0});S.updateTransitions(P)}_createRain(g){const S=this.rain=new Qn(g,this.map.transform,this.scope,this.options);this.stylesheet.rain=S.get();const P=this._getTransitionParameters({duration:0});S.updateTransitions(P)}_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 S=this.fog;if(!o.b6(S.get(),g)){S.set(g,this.options),this.stylesheet.fog=S.get();const P=this._getTransitionParameters({duration:0});S.updateTransitions(P)}}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 S=this.snow;if(!o.b6(S.get(),g)){S.set(g,this.options),this.stylesheet.snow=S.get();const P=this._getTransitionParameters({duration:0});S.updateTransitions(P)}}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 S=this.rain;if(!o.b6(S.get(),g)){S.set(g,this.options),this.stylesheet.rain=S.get();const P=this._getTransitionParameters({duration:0});S.updateTransitions(P)}}else this._createRain(g);this._markersNeedUpdate=!0}_reloadColorTheme(){const g=()=>{for(const z in this._layers)this._layers[z].lut=this._styleColorTheme.lut;for(const z in this._sourceCaches)this._sourceCaches[z].clearTiles()},S=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!S)return this._styleColorTheme.lut=null,void g();const P=this._evaluateColorThemeData(S);this._loadColorTheme(P).then(()=>{this.fire(new o.C("colorthemeset")),g()}).catch(z=>{o.w(`Couldn't set color theme: ${z}`)})}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,S){const P=this.getFragmentStyle(g);P&&(P._styleColorTheme.colorThemeOverride=S,P._reloadColorTheme())}_getTransitionParameters(g){return{now:o.o.now(),transition:Object.assign(this.transition,g)}}updateDrapeFirstLayers(){if(!this.terrain)return;const g=[],S=[];for(const P of this._mergedOrder)this.isLayerDraped(this._mergedLayers[P])?g.push(P):S.push(P);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...g),this._drapedFirstOrder.push(...S)}_createTerrain(g,S){const P=this.terrain=new pn(g,S,this.scope,this.options,this.map.getWorldview());S===1&&(this.stylesheet.terrain=g),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const z=this._getTransitionParameters({duration:0});P.updateTransitions(z)}_force3DLayerUpdate(){for(const g in this._layers){const S=this._layers[g];S.type==="fill-extrusion"&&this._updateLayer(S)}}_forceSymbolLayerUpdate(){for(const g in this._layers){const S=this._layers[g];S.type==="symbol"&&this._updateLayer(S)}}_validate(g,S,P,z,H={}){if(H&&H.validate===!1)return!1;const G=Object.assign({},this.serialize());return wv(this,g.call(Qr,Object.assign({key:S,style:G,value:P,styleSpec:o.a8},z)))}_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 S=this.getSourceCaches(g);for(const P of S)P.clearTiles()}clearSources(){for(const g in this._mergedSourceCaches)this._mergedSourceCaches[g].clearTiles()}clearLayers(){for(const g in this._mergedLayers){const S=this._mergedLayers[g];S._clear&&S._clear()}}reloadSource(g){const S=this.getSourceCaches(g);for(const P of S)P.resume(),P.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 S;this.directionalLight&&(S=G2(this.directionalLight));const P=new Set,z=new Set,H=new Set;for(const G in this._mergedLayers){const ee=this._mergedLayers[G];ee.type==="building"?P.add(ee.source):ee.type==="raster"&&ee.paint&&ee.paint.get("raster-elevation-reference")==="ground"&&H.add(ee.source),ee.hasElevation()&&!z.has(ee.source)&&z.add(ee.source)}for(const G in this._mergedSourceCaches){const ee=this._mergedSourceCaches[G],ie=z.has(ee._source.id);ee._isRasterElevatedOverTerrain=H.has(ee._source.id),P.has(ee._source.id)&&(ee._source.reparseOverscaled=!1),ee.update(g,void 0,void 0,S,ie)}}_generateCollisionBoxes(){for(const g in this._sourceCaches){const S=this._sourceCaches[g];S.resume(),S.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new sb),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(g,S,P,z,H){this.pauseablePlacement||(this.pauseablePlacement=new sb);let G=!1,ee=!1;const ie={},pe={};for(const Ye of this._mergedOrder){const ut=this._mergedLayers[Ye];if(ut.type!=="symbol")continue;const dt=o.F(ut.source,ut.scope);let jt=ie[dt];if(!jt){const ft=this.getLayerSourceCache(ut);if(!ft)continue;const Kt=ft.getRenderableIds(!0).map(Rt=>ft.getTileByID(Rt));pe[dt]=Kt.slice(),jt=ie[dt]=Kt.sort((Rt,Wt)=>Wt.tileID.overscaledZ-Rt.tileID.overscaledZ||(Rt.tileID.isLessThan(Wt.tileID)?-1:1))}const Tt=this.crossTileSymbolIndex.addLayer(ut,jt,g.center.lng,g.projection);G=G||Tt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const ye=!!(this.placement&&!g.equals(this.placement.transform)),De=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!H||this.placement.lastReplacementSourceUpdateTime!==H.updateTime)),Ae=ye||De||G,Be=(Ae||this.pauseablePlacement.isStale())&&P===0,tt=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),g.zoom)&&P!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Be||tt)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(g,this._mergedOrder,S,P,z,this.placement,this.fog&&g.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Ye=this.map.painter.maxFrontCutoffRawStart;if(Ye>0){const ut=180*g.pitch/Math.PI;if(ut>=15){const dt=Math.min(1,Math.max(0,(ut-15)/5)),jt=dt*dt*(3-2*dt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-jt)+Ye*jt}}}if(this.pauseablePlacement.isDone()?Ae&&P!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,ie,pe,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),ee=!0),G&&this.pauseablePlacement.setStale()),ee||G){this._buildingIndex.onNewFrame(g.zoom);for(let Ye=0;YeH===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(!S)return P.push(g),this._loadImports([g],!0);const z=P.findIndex(({id:H})=>H===S);return z===-1&&this.fire(new o.B(new Error(`Import with id "${S}" does not exist on this map.`))),this.stylesheet.imports=P.slice(0,z).concat(g).concat(P.slice(z)),this._loadImports([g],!0,S)}updateImport(g,S){this._checkLoaded();const P=this.stylesheet.imports||[],z=this.getImportIndex(g);return z===-1?this:typeof S=="string"?(this.setImportUrl(g,S),this):(S.url&&S.url!==P[z].url&&this.setImportUrl(g,S.url),o.b6(S.config,P[z].config)||this.setImportConfig(g,S.config,S.data.schema),o.b6(S.data,P[z].data)||this.setImportData(g,S.data),this)}moveImport(g,S){this._checkLoaded();let P=this.stylesheet.imports||[];const z=this.getImportIndex(g);if(z===-1)return this;const H=this.getImportIndex(S);if(H===-1)return this;const G=P[z],ee=this.fragments[z];return P=P.filter(({id:ie})=>ie!==g),this.fragments=this.fragments.filter(({id:ie})=>ie!==g),this.stylesheet.imports=P.slice(0,H).concat(G).concat(P.slice(H)),this.fragments=this.fragments.slice(0,H).concat(ee).concat(this.fragments.slice(H)),this.mergeLayers(),this}setImportUrl(g,S){this._checkLoaded();const P=this.stylesheet.imports||[],z=this.getImportIndex(g);if(z===-1)return this;P[z].url=S;const H=this.fragments[z];return H.style=this._createFragmentStyle(P[z]),H.style.on("style.import.load",()=>this.mergeAll()),H.style.loadURL(S),this}setImportData(g,S){this._checkLoaded();const P=this.getImportIndex(g),z=this.stylesheet.imports||[];return P===-1?this:S?(this.fragments[P].style.setState(S),this._reloadImports(),this):(delete z[P].data,this.setImportUrl(g,z[P].url))}setImportConfig(g,S,P){this._checkLoaded();const z=this.getImportIndex(g),H=this.stylesheet.imports||[];if(z===-1)return this;S?H[z].config=S:delete H[z].config;const G=this.fragments[z];P&&G.style.stylesheet&&(G.style.stylesheet.schema=P);const ee=G.style.stylesheet&&G.style.stylesheet.schema;return G.config=S,G.style.updateConfig(S,ee),this.updateConfigDependencies(),this}removeImport(g){this._checkLoaded();const S=this.stylesheet.imports||[],P=this.getImportIndex(g);P!==-1&&(S.splice(P,1),this.fragments[P].style._remove(),this.fragments.splice(P,1),this._reloadImports())}getImportIndex(g){const S=(this.stylesheet.imports||[]).findIndex(P=>P.id===g);return S===-1&&this.fire(new o.B(new Error(`Import '${g}' does not exist in the map's style and cannot be updated.`))),S}getLayer(g){return this._mergedLayers[g]}getSources(){const g=[];for(const S in this._mergedOtherSourceCaches){const P=this._mergedOtherSourceCaches[S];P&&g.push(P.getSource())}return g}getSource(g,S){const P=this.getSourceCache(g,S);return P&&P.getSource()}getLayerSource(g){const S=this.getLayerSourceCache(g);return S&&S.getSource()}getSourceCache(g,S){const P=o.F(g,S);return this._mergedOtherSourceCaches[P]}getLayerSourceCache(g){const S=o.F(g.source,g.scope);return g.type==="symbol"?this._mergedSymbolSourceCaches[S]:g.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[S]||this._mergedOtherSourceCaches[S]}getSourceCaches(g){if(g==null)return Object.values(this._mergedSourceCaches);const S=[];return this._mergedOtherSourceCaches[g]&&S.push(this._mergedOtherSourceCaches[g]),this._mergedSymbolSourceCaches[g]&&S.push(this._mergedSymbolSourceCaches[g]),this._mergedFillExtrusionSourceCaches[g]&&S.push(this._mergedFillExtrusionSourceCaches[g]),S}updateSourceCaches(){const g=this._changes.getUpdatedSourceCaches();for(const S in g){const P=g[S];P==="reload"?this.reloadSource(S):P==="clear"&&this.clearSource(S)}}updateLayers(g){const S=this._changes.getUpdatedPaintProperties();for(const P of S){const z=this.getLayer(P);z&&z.updateTransitions(g)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(g){this.stylesheet.glyphs=g,this.glyphManager.setURL(g)}getImages(g,S,P){this.imageManager.getImages(S.images,S.scope,P),this._updateTilesForChangedImages();const z=G=>{if(G){const ee=S.images.map(ie=>o.I.toString(ie));G.setDependencies(S.tileID.key,S.type,ee)}},H=o.F(S.source,S.scope);z(this._mergedOtherSourceCaches[H]),z(this._mergedSymbolSourceCaches[H]),S.images.some(G=>G.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(g,S,P){this.imageManager.rasterizeImages(S,P)}checkAtlasCache(g,S,P){const z=this.imageManager.imageAtlasCache.findCachedAtlas(S.descriptor);P(null,z&&z.contentDescriptor?{iconPositions:z.iconPositions,patternPositions:z.patternPositions,sourceHash:z.contentDescriptor.hash}:null)}getGlyphs(g,S,P){this.glyphManager.getGlyphs(S.stacks,P)}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 S=[];return this._otherSourceCaches[g]&&S.push(this._otherSourceCaches[g]),this._symbolSourceCaches[g]&&S.push(this._symbolSourceCaches[g]),this._fillExtrusionSourceCaches[g]&&S.push(this._fillExtrusionSourceCaches[g]),S}_isSourceCacheLoaded(g){const S=this.getOwnSourceCaches(g);return S.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${g}'`))),!1):S.every(P=>P.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(g,S){if(!this._clipLayerPresent&&g.type!=="fill-extrusion"&&g.type!=="building")return!1;const P=g.type==="fill-extrusion"&&(g.sourceLayer==="building"||g.sourceLayer==="procedural_buildings"),z=g.type==="building";if(g.is3D(!!this.terrain)){if(P||z||S&&S.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)}}Ic.getSourceType=function(M){return K0[M]},Ic.setSourceType=function(M,g){K0[M]=g},Ic.registerForPluginStateChange=o.dk;var jv=` #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`,Nw=` #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;}`,Fx=` #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`,ib="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;}",K2=` #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`,Y2=`#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`,Nv=`#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`,kv=`#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`,Z2=`#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;}`,kw=`#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`,zm=`#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 Og=/#include\s+"([^"]+)"/g,Lr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,Sw=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,Cw=new Set(["ifdef","ifndef","elif","if","defined"]),ry=new Set;zx(jv,ry),zx(Fx,ry),zx(Nw,ry);const bf={"_prelude_fog.vertex.glsl":Y2,"_prelude_terrain.vertex.glsl":K2,"_prelude_shadow.vertex.glsl":kw,"_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":Nv,"_prelude_shadow.fragment.glsl":zm,"_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":kv,"_prelude_raster_particle.glsl":Z2},Sv={};hi("",K2),hi(Nv,Y2),hi(zm,kw),hi(kv,""),hi(Z2,"");const Fg=hi(Nw,Fx),ob=jv,Cv=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",ob,Fg.fragmentSource].join(` `),b4=["precision highp float;",ob,Fg.vertexSource].join(` `);var _4={background:hi(`#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:hi(`#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:hi(`#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:hi(`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:hi("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:hi(`#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:hi("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:hi(`#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:hi(`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:hi("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:hi("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:hi("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:hi("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:hi(`#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:hi(`#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:hi(`#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:hi(`#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:hi(`#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:hi(`#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:hi(`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:hi(`#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:hi("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:hi(`#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:hi(`#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:hi(`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:hi(`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:hi(`#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:hi(`#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:hi(`#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:hi(`#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:hi(`#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:hi("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:hi("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:hi(`#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:hi(`#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:hi(`#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:hi("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:hi(`#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 }`,ib),skyboxGradient:hi(`#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 }`,ib),skyboxCapture:hi(` 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:hi(`#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:hi(`#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:hi(`#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:hi("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:hi(`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:hi("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:hi("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:hi("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:hi("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 zx(M,g){const S=M.split(` `);for(let P of S){if(P=P.trimStart(),P[0]!=="#"||!P.includes("if")||P.startsWith("#endif"))continue;const z=P.match(Sw);if(z)for(const H of z)Cw.has(H)||g.add(H)}}function w4(M){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(M)}function hi(M,g){const S=new Set,P=[],z=[];M=M.replace(Og,(G,ee)=>(z.push(ee),"")),g=g.replace(Og,(G,ee)=>(P.push(ee),""));let H=new Set(ry);zx(M,H),zx(g,H);for(const G of[...P,...z])Sv[G]||(Sv[G]=new Set,zx(bf[G],Sv[G])),H=new Set([...H,...Sv[G]]);return{fragmentSource:M=M.replace(Lr,(G,ee,ie,pe,ye)=>(S.add(ye),ee==="define"?` #ifndef HAS_UNIFORM_u_${ye} ${w4(pe)?"flat ":""}in ${ie} ${pe} ${ye}; #else uniform ${ie} ${pe} u_${ye}; #endif `:ee==="initialize"?` #ifdef HAS_UNIFORM_u_${ye} ${ie} ${pe} ${ye} = u_${ye}; #endif `:ee==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ye} in ${ie} ${pe} ${ye}; #endif `:ee==="initialize-attribute"?"":void 0)),vertexSource:g=g.replace(Lr,(G,ee,ie,pe,ye)=>{const De=`MATERIAL_ATTRIBUTE_OFFSET_${ye}`,Ae=pe==="float"?"vec2":pe,Be=`GET_ATTRIBUTE_${Ae}(a_${ye}, materialInfo, ${De})`,tt=ye.match(/color/)?"color":Ae;return ee==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${ye} in ${ie} ${pe} a_${ye}; #endif `:S.has(ye)?ee==="define"?` #ifndef HAS_UNIFORM_u_${ye} uniform lowp float u_${ye}_t; #if !defined(${De}) in ${ie} ${Ae} a_${ye}; #endif ${w4(pe)?"flat ":""}out ${ie} ${pe} ${ye}; #else uniform ${ie} ${pe} u_${ye}; #endif `:ee==="initialize"?tt==="vec4"||tt==="uvec4"?` #ifndef HAS_UNIFORM_u_${ye} ${ye} = a_${ye}; #else ${ie} ${pe} ${ye} = u_${ye}; #endif `:` #if !defined(HAS_UNIFORM_u_${ye}) #ifdef ${De} ${ye} = unpack_mix_${tt}(${Be}, u_${ye}_t); #else ${ye} = unpack_mix_${tt}(a_${ye}, u_${ye}_t); #endif #else ${ie} ${pe} ${ye} = u_${ye}; #endif `:ee==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ye} in ${ie} ${pe} a_${ye}; out ${ie} ${pe} ${ye}; #endif `:ee==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ye} ${ye} = a_${ye}; #endif `:void 0:ee==="define"?` #ifndef HAS_UNIFORM_u_${ye} uniform lowp float u_${ye}_t; #if !defined(${De}) in ${ie} ${Ae} a_${ye}; #endif #else uniform ${ie} ${pe} u_${ye}; #endif `:ee==="define-instanced"?tt==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${ye}0; in vec4 a_${ye}1; in vec4 a_${ye}2; in vec4 a_${ye}3; #else uniform ${ie} ${pe} u_${ye}; #endif `:` #ifdef INSTANCED_ARRAYS in ${ie} ${Ae} a_${ye}; #else uniform ${ie} ${pe} u_${ye}; #endif `:ee==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${ye} ${ie} ${pe} ${ye} = a_${ye}; #endif `:tt==="vec4"||tt==="uvec4"?` #ifndef HAS_UNIFORM_u_${ye} #ifdef ${De} ${ie} ${pe} ${ye} = ${Be}; #else ${ie} ${pe} ${ye} = a_${ye}; #endif #else ${ie} ${pe} ${ye} = u_${ye}; #endif `:` #ifndef HAS_UNIFORM_u_${ye} #ifdef ${De} ${ie} ${pe} ${ye} = unpack_mix_${tt}(${Be}, u_${ye}_t); #else ${ie} ${pe} ${ye} = unpack_mix_${tt}(a_${ye}, u_${ye}_t); #endif #else ${ie} ${pe} ${ye} = u_${ye}; #endif `}),usedDefines:H,vertexIncludes:P,fragmentIncludes:z}}class j4{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(g,S,P,z,H,G,ee,ie){this.context=g;let pe=this.boundPaintVertexBuffers.length!==z.length;for(let De=0;!pe&&De{const Kt=Tt.paint.get("hillshade-shadow-color"),Rt=Tt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Wt=Tt.paint.get("hillshade-highlight-color"),Et=Tt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Lt=Tt.paint.get("hillshade-accent-color"),Vt=Tt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",ds=Tt.paint.get("hillshade-emissive-strength");let Zt=o.ap(Tt.paint.get("hillshade-illumination-direction"));if(Tt.paint.get("hillshade-illumination-anchor")==="viewport")Zt-=dt.transform.angle;else if(dt.style&&dt.style.enable3dLights()&&dt.style.directionalLight){const Ns=dt.style.directionalLight.properties.get("direction"),er=o.cP(Ns.x,Ns.y,Ns.z);Zt=o.ap(er[1])}const Is=!dt.options.moving;return{u_matrix:ft||dt.transform.calculateProjMatrix(jt.tileID.toUnwrapped(),Is),u_image:0,u_latrange:N4(0,jt.tileID),u_light:[Tt.paint.get("hillshade-exaggeration"),Zt],u_shadow:Kt.toPremultipliedRenderColor(Rt?null:Tt.lut),u_highlight:Wt.toPremultipliedRenderColor(Et?null:Tt.lut),u_emissive_strength:ds,u_accent:Lt.toPremultipliedRenderColor(Vt?null:Tt.lut)}})(M,S,P,M.terrain?g.projMatrix:null);M.uploadCommonUniforms(ee,Ae,g.toUnwrapped());const{tileBoundsBuffer:tt,tileBoundsIndexBuffer:Ye,tileBoundsSegments:ut}=M.getTileBoundsBuffers(S);Ae.draw(M,ie.TRIANGLES,z,H,G,Cn.disabled,Be,P.id,tt,Ye,ut)}function k4(M,g,S){if(!g.needsDEMTextureUpload)return;const P=M.context,z=P.gl;P.pixelStoreUnpackPremultiplyAlpha.set(!1),g.demTexture=g.demTexture||M.getTileTexture(S.stride);const H=S.getPixels();g.demTexture?g.demTexture.update(H,{premultiply:!1}):g.demTexture=new o.T(P,H,z.R32F,{premultiply:!1}),g.needsDEMTextureUpload=!1}function gM(M,g,S){const P=M.context,z=P.gl;if(!g.dem)return;const H=g.dem;if(P.activeTexture.set(z.TEXTURE1),k4(M,g,H),!g.demTexture)return;g.demTexture.bind(z.NEAREST,z.CLAMP_TO_EDGE);const G=H.dim;P.activeTexture.set(z.TEXTURE0);let ee=g.hillshadeFBO;if(!ee){const Ae=new o.T(P,{width:G,height:G,data:null},z.RGBA8);Ae.bind(z.LINEAR,z.CLAMP_TO_EDGE),ee=g.hillshadeFBO=P.createFramebuffer(G,G,1,"renderbuffer"),ee.colorAttachment0.set(Ae.texture)}P.bindFramebuffer.set(ee.framebuffer),P.viewport.set([0,0,G,G]);const{tileBoundsBuffer:ie,tileBoundsIndexBuffer:pe,tileBoundsSegments:ye}=M.getMercatorTileBoundsBuffers(),De=[];M.linearFloatFilteringSupported()&&De.push("TERRAIN_DEM_FLOAT_FORMAT"),M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback"&&De.push("USE_MRT1"),M.getOrCreateProgram("hillshadePrepare",{defines:De}).draw(M,z.TRIANGLES,Jr.disabled,Xn.disabled,Hn.unblended,Cn.disabled,((Ae,Be)=>{const tt=Be.stride,Ye=o.bb();return o.bT(Ye,0,o.an,-o.an,0,0,1),o.bx(Ye,Ye,[0,-o.an,0]),{u_matrix:Ye,u_image:1,u_dimension:[tt,tt],u_zoom:Ae.overscaledZ}})(g.tileID,H),S.id,ie,pe,ye),g.needsHillshadePrepare=!1}class nl{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 Tw extends nl{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(g){const S=this.current;(g.r!==S.r||g.g!==S.g||g.b!==S.b||g.a!==S.a||this.dirty)&&(this.gl.clearColor(g.r,g.g,g.b,g.a),this.current=g,this.dirty=!1)}}class vD extends nl{getDefault(){return 1}set(g){(g!==this.current||this.dirty)&&(this.gl.clearDepth(g),this.current=g,this.dirty=!1)}}class X2 extends nl{getDefault(){return 0}set(g){(g!==this.current||this.dirty)&&(this.gl.clearStencil(g),this.current=g,this.dirty=!1)}}class bD extends nl{getDefault(){return[!0,!0,!0,!0]}set(g){const S=this.current;(g[0]!==S[0]||g[1]!==S[1]||g[2]!==S[2]||g[3]!==S[3]||this.dirty)&&(this.gl.colorMask(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class hp extends nl{getDefault(){return!0}set(g){(g!==this.current||this.dirty)&&(this.gl.depthMask(g),this.current=g,this.dirty=!1)}}class Ew extends nl{getDefault(){return 255}set(g){(g!==this.current||this.dirty)&&(this.gl.stencilMask(g),this.current=g,this.dirty=!1)}}class Tv extends nl{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(g){const S=this.current;(g.func!==S.func||g.ref!==S.ref||g.mask!==S.mask||this.dirty)&&(this.gl.stencilFunc(g.func,g.ref,g.mask),this.current=g,this.dirty=!1)}}class Q2 extends nl{getDefault(){const g=this.gl;return[g.KEEP,g.KEEP,g.KEEP]}set(g){const S=this.current;(g[0]!==S[0]||g[1]!==S[1]||g[2]!==S[2]||this.dirty)&&(this.gl.stencilOp(g[0],g[1],g[2]),this.current=g,this.dirty=!1)}}class ny extends nl{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;g?S.enable(S.STENCIL_TEST):S.disable(S.STENCIL_TEST),this.current=g,this.dirty=!1}}class ay extends nl{getDefault(){return[0,1]}set(g){const S=this.current;(g[0]!==S[0]||g[1]!==S[1]||this.dirty)&&(this.gl.depthRange(g[0],g[1]),this.current=g,this.dirty=!1)}}class iy extends nl{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;g?S.enable(S.DEPTH_TEST):S.disable(S.DEPTH_TEST),this.current=g,this.dirty=!1}}class Yh extends nl{getDefault(){return this.gl.LESS}set(g){(g!==this.current||this.dirty)&&(this.gl.depthFunc(g),this.current=g,this.dirty=!1)}}class J2 extends nl{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;g?S.enable(S.BLEND):S.disable(S.BLEND),this.current=g,this.dirty=!1}}class Aw extends nl{getDefault(){const g=this.gl;return[g.ONE,g.ZERO,g.ONE,g.ZERO]}set(g){const S=this.current;(g[0]!==S[0]||g[1]!==S[1]||g[2]!==S[2]||g[3]!==S[3]||this.dirty)&&(this.gl.blendFuncSeparate(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class yM extends nl{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(g){const S=this.current;(g.r!==S.r||g.g!==S.g||g.b!==S.b||g.a!==S.a||this.dirty)&&(this.gl.blendColor(g.r,g.g,g.b,g.a),this.current=g,this.dirty=!1)}}class Ev extends nl{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 Mw extends nl{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;g?S.enable(S.CULL_FACE):S.disable(S.CULL_FACE),this.current=g,this.dirty=!1}}class Iw extends nl{getDefault(){return this.gl.BACK}set(g){(g!==this.current||this.dirty)&&(this.gl.cullFace(g),this.current=g,this.dirty=!1)}}class eN extends nl{getDefault(){return this.gl.CCW}set(g){(g!==this.current||this.dirty)&&(this.gl.frontFace(g),this.current=g,this.dirty=!1)}}let Pw=class extends nl{getDefault(){return null}set(M){(M!==this.current||this.dirty)&&(this.gl.useProgram(M),this.current=M,this.dirty=!1)}};class Lw extends nl{getDefault(){return this.gl.TEXTURE0}set(g){(g!==this.current||this.dirty)&&(this.gl.activeTexture(g),this.current=g,this.dirty=!1)}}class Zh extends nl{getDefault(){const g=this.gl;return[0,0,g.drawingBufferWidth,g.drawingBufferHeight]}set(g){const S=this.current;(g[0]!==S[0]||g[1]!==S[1]||g[2]!==S[2]||g[3]!==S[3]||this.dirty)&&(this.gl.viewport(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class wh extends nl{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;S.bindFramebuffer(S.FRAMEBUFFER,g),this.current=g,this.dirty=!1}}class S4 extends nl{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;S.bindRenderbuffer(S.RENDERBUFFER,g),this.current=g,this.dirty=!1}}class Av extends nl{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;S.bindTexture(S.TEXTURE_2D,g),this.current=g,this.dirty=!1}}class C4 extends nl{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;S.bindBuffer(S.ARRAY_BUFFER,g),this.current=g,this.dirty=!1}}class vM extends nl{getDefault(){return null}set(g){const S=this.gl;S.bindBuffer(S.ELEMENT_ARRAY_BUFFER,g),this.current=g,this.dirty=!1}}class bM extends nl{getDefault(){return null}set(g){this.gl&&(g!==this.current||this.dirty)&&(this.gl.bindVertexArray(g),this.current=g,this.dirty=!1)}}class T4 extends nl{getDefault(){return 4}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;S.pixelStorei(S.UNPACK_ALIGNMENT,g),this.current=g,this.dirty=!1}}class tN extends nl{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;S.pixelStorei(S.UNPACK_PREMULTIPLY_ALPHA_WEBGL,g),this.current=g,this.dirty=!1}}class Dw extends nl{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const S=this.gl;S.pixelStorei(S.UNPACK_FLIP_Y_WEBGL,g),this.current=g,this.dirty=!1}}class lb extends nl{constructor(g,S){super(g),this.context=g,this.parent=S}getDefault(){return null}}class Mv extends lb{constructor(g,S,P=0){super(g,S),this.attachmentPoint=g.gl.COLOR_ATTACHMENT0+P}setDirty(){this.dirty=!0}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const S=this.gl;S.framebufferTexture2D(S.FRAMEBUFFER,this.attachmentPoint,S.TEXTURE_2D,g,0),this.current=g,this.dirty=!1}}class Rw extends lb{attachment(){return this.gl.DEPTH_ATTACHMENT}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const S=this.gl;S.framebufferRenderbuffer(S.FRAMEBUFFER,this.attachment(),S.RENDERBUFFER,g),this.current=g,this.dirty=!1}}class sN extends lb{attachment(){return this.gl.DEPTH_ATTACHMENT}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const S=this.gl;S.framebufferTexture2D(S.FRAMEBUFFER,this.attachment(),S.TEXTURE_2D,g,0),this.current=g,this.dirty=!1}}class _M extends Rw{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const Iv=(M,g,S,P)=>({u_matrix:M,u_image0:0,u_image1:1,u_skirt_height:g,u_ground_shadow_factor:S,u_emissive_texture_available:P}),zg=(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut)=>({u_proj_matrix:Float32Array.from(M),u_globe_matrix:g,u_normalize_matrix:Float32Array.from(P),u_merc_matrix:S,u_zoom_transition:z,u_merc_center:H,u_image0:0,u_image1:1,u_frustum_tl:G,u_frustum_tr:ee,u_frustum_br:ie,u_frustum_bl:pe,u_globe_pos:ye,u_globe_radius:De,u_viewport:Ae,u_grid_matrix:ut?Float32Array.from(ut):new Float32Array(9),u_skirt_height:Be,u_far_z_cutoff:tt,u_emissive_texture_available:Ye});function E4(M,g){return M!=null&&g!=null&&!(!M.hasData()||!g.hasData())&&M.demTexture!=null&&g.demTexture!=null&&M.tileID.key!==g.tileID.key}const Qd=new class{constructor(){this.operations={}}newMorphing(M,g,S,P,z){if(M in this.operations){const H=this.operations[M];H.to.tileID.key!==S.tileID.key&&(H.queued=S)}else this.operations[M]={startTime:P,phase:0,duration:z,from:g,to:S,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 S=this.operations[g];for(S.phase=(M-S.startTime)/S.duration;S.phase>=1||!this._validOp(S);)if(!this._nextOp(S,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()}},cb={0:null,1:"TERRAIN_VERTEX_MORPHING"};function db(M,g,S){if(g===0)return 0;const P=g<1&&S===514?.25/g:1;return 6*Math.pow(1.5,22-M)*Math.max(g,1)*P}function Pv(M,g){const S=1<({u_matrix:M});function Bm(M,g,S,P,z){if(z>0){const H=o.o.now(),G=(H-M.timeAdded)/z,ee=g?(H-g.timeAdded)/z:-1,ie=S.getSource(),pe=P.coveringZoomLevel({tileSize:ie.tileSize,roundZoom:ie.roundZoom}),ye=!g||Math.abs(g.tileID.overscaledZ-pe)>Math.abs(M.tileID.overscaledZ-pe),De=ye&&M.refreshedUponExpiration?1:o.aC(ye?G:1-ee,0,1);return g?{opacity:1,mix:1-De,isFading:G<1}:{opacity:De,mix:0,isFading:G<1}}return{opacity:1,mix:0,isFading:!1}}class Fw extends Xo{constructor(g){const S={type:"raster-dem",maxzoom:Math.ceil(g.transform.maxZoom)},P=Y0("mock-dem",S,g.style.dispatcher,g.style);super("mock-dem",P,null),P.setEventedParent(this),this._sourceLoaded=!0}_loadTile(g,S){g.state="loaded",S(null)}}class Lv extends Xo{constructor(g){const S=Y0("proxy",{type:"geojson",maxzoom:Math.ceil(g.transform.maxZoom)},g.style.dispatcher,g.style);super("proxy",S,null),S.setEventedParent(this),this.map=this.getSource().map=g,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(g,S,P){if(g.freezeTileCoverage)return;this.transform=g;const z=g.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((H,G)=>{if(H[G.key]="",!this._tiles[G.key]){const ee=new o.b0(G,this._source.tileSize*G.overscaleFactor(),g.tileZoom,void 0,void 0,this._source.worldview);ee.state="loaded",this._tiles[G.key]=ee}return H},{});for(const H in this._tiles)H in z||(this.freeFBO(H),this._tiles[H].unloadVectorData(),delete this._tiles[H])}freeFBO(g){const S=this.proxyCachedFBO[g];if(S!==void 0){const P=Object.values(S);this.renderCachePool.push(...P),delete this.proxyCachedFBO[g]}}deallocRenderCache(){this.renderCache.forEach(g=>g.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class oy extends o.aR{constructor(g,S,P){super(g.overscaledZ,g.wrap,g.canonical.z,g.canonical.x,g.canonical.y),this.proxyTileKey=S,this.projMatrix=P}}class ly extends o.bu{constructor(g,S){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=g,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[P,z,H]=function(){const ie=new o.dB,pe=new o.dC,ye=131;ie.reserve(17161),pe.reserve(33800);const De=o.an/128,Ae=o.an+De/2,Be=Ae+De;for(let Ye=-De;YeAe||Ye<0||Ye>Ae?24575:0,jt=o.aC(Math.round(ut),0,o.an),Tt=o.aC(Math.round(Ye),0,o.an);ie.emplaceBack(jt+dt,Tt)}const tt=(Ye,ut)=>{const dt=ut*ye+Ye;pe.emplaceBack(dt+1,dt,dt+ye),pe.emplaceBack(dt+ye,dt+ye+1,dt+1)};for(let Ye=1;Ye<129;Ye++)for(let ut=1;ut<129;ut++)tt(ut,Ye);return[0,129].forEach(Ye=>{for(let ut=0;ut<130;ut++)tt(ut,Ye),tt(Ye,ut)}),[ie,pe,32768]}(),G=g.context;this.gridBuffer=G.createVertexBuffer(P,o.dx.members),this.gridIndexBuffer=G.createIndexBuffer(z),this.gridSegments=o.dy.simpleSegment(0,0,P.length,z.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,P.length,H),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new Lv(S.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 ee=G.gl;this._overlapStencilMode=new Xn({func:ee.GEQUAL,mask:255},0,255,ee.KEEP,ee.KEEP,ee.REPLACE),this._previousZoom=g.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=S,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Fw(S.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,S,P){if(g&&g.terrain){this._style!==g&&(this.style=g,this._evaluationZoom=void 0);const z=g.terrain.properties,H=g.terrain.drapeRenderMode===0,G=g.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const ee=g.terrain&&g.terrain.scope,ie=z.get("source"),pe=H?this._mockSourceCache:g.getSourceCache(ie,ee);if(!pe)return void o.w(`Couldn't find terrain source "${ie}".`);if(this.sourceCache=pe,this._attenuationRange=g.terrain.getAttenuationRange(),this._exaggeration=G?this.calculateExaggeration(S):z.get("exaggeration"),!S.projection.requiresDraping&&G&&this._exaggeration===0)return void this._disable();this.enabled=!0;const ye=()=>{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 De=this.getScaledDemTileSize();this.sourceCache.update(S,De,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,ye(),this._initializing=!0),ye(),S.updateElevation(!0,P),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(S),this._emptyDEMTextureDirty=!0,this._previousZoom=S.zoom}else this._disable()}calculateExaggeration(g){if(this._attenuationRange&&g.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(g.zoom);const S=this._previousCameraAltitude,P=g.getFreeCameraOptions().position.z/g.pixelsPerMeter*g.worldSize;this._previousCameraAltitude=P;const z=S!=null?P-S:Number.MAX_VALUE;if(Math.abs(z)<2)return this._exaggeration;const H=g.zoom,G=this._style.terrain;if(!this._previousUpdateTimestamp)return G.getExaggeration(H);let ee=H-this._previousZoom;const ie=this._previousUpdateTimestamp;let pe=H;this._evaluationZoom!=null&&(pe=this._evaluationZoom,Math.abs(H-pe)>.5&&(ee=.5*(H-pe+ee)),ee*z<0&&(pe+=ee)),this._evaluationZoom=pe;const ye=G.getExaggeration(pe),De=ye===G.getExaggeration(Math.max(0,pe-.1));if(De&&Math.abs(ye-this._exaggeration)<.01)return ye;let Ae=Math.min(.1,.00375*(this._updateTimestamp-ie));return(De||ye<.1||Math.abs(ee)<1e-4)&&(Ae=Math.min(.2,4*Ae)),o.am(this._exaggeration,ye,Ae)}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 S=this.proxySourceCache,P=this.painter.transform;this._initializing&&(this._initializing=P._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(P.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const z=this.proxyCoords=S.getIds().map(ie=>{const pe=S.getTileByID(ie).tileID;return pe.projMatrix=P.calculateProjMatrix(pe.toUnwrapped()),pe});(function(ie,pe){const ye=pe.transform.pointCoordinate(pe.transform.getCameraPoint()),De=new o.P(ye.x,ye.y);ie.sort((Ae,Be)=>{if(Be.overscaledZ-Ae.overscaledZ)return Be.overscaledZ-Ae.overscaledZ;const tt=new o.P(Ae.canonical.x+(1<{this.proxyToSource[ie.key]={}}),this.terrainTileForTile={};const G=this._style._mergedSourceCaches;for(const ie in G){const pe=G[ie];if(!pe.used||(pe!==this.sourceCache&&this.resetTileLookupCache(pe.id),this._setupProxiedCoordsForOrtho(pe,g[ie],H),pe.usedForTerrain))continue;const ye=g[ie];(pe.getSource().reparseOverscaled||pe._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(ye)}this.proxiedCoords[S.id]=z.map(ie=>new oy(ie,ie.key,this.orthoMatrix)),this._assignTerrainTiles(z),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(H),this.renderingToTexture=!1;const ee={};this._visibleDemTiles=[];for(const ie of this.proxyCoords){const pe=this.terrainTileForTile[ie.key];if(!pe)continue;const ye=pe.tileID.key;ye in ee||(this._visibleDemTiles.push(pe),ee[ye]=ye)}}_assignTerrainTiles(g){this._initializing||g.forEach(S=>{if(this.terrainTileForTile[S.key])return;const P=this._findTileCoveringTileID(S,this.sourceCache);P&&(this.terrainTileForTile[S.key]=P)})}_prepareDEMTextures(){const g=this.painter.context,S=g.gl;for(const P in this.terrainTileForTile){const z=this.terrainTileForTile[P],H=z.dem;!H||z.demTexture&&!z.needsDEMTextureUpload||(g.activeTexture.set(S.TEXTURE1),k4(this.painter,z,H))}}_prepareDemTileUniforms(g,S,P,z){if(!S||S.demTexture==null)return!1;const H=g.tileID.canonical,G=Math.pow(2,S.tileID.canonical.z-H.z),ee=z||"";return P[`u_dem_tl${ee}`]=[H.x*G%1,H.y*G%1],P[`u_dem_scale${ee}`]=G,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let g=0;const S=this._visibleDemTiles.reduce((P,z)=>{if(!z.dem)return P;const H=z.dem.tree.minimums[0];return H>0&&g++,P+H},0);return g?S/g:0}_updateEmptyDEMTexture(){const g=this.painter.context,S=g.gl;g.activeTexture.set(S.TEXTURE2);const P=this._getLoadedAreaMinimum(),z=new o.dz({width:1,height:1},new Float32Array([P]));this._emptyDEMTextureDirty=!1;let H=this._emptyDEMTexture;return H?H.update(z,{premultiply:!1}):H=this._emptyDEMTexture=new o.T(g,z,S.R32F,{premultiply:!1}),H}setupElevationDraw(g,S,P){const z=this.painter.context,H=z.gl,G={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};G.u_exaggeration=this.exaggeration();let ee=null,ie=null,pe=1;if(P&&P.morphing&&this._useVertexMorphing){const Be=P.morphing.srcDemTile,tt=P.morphing.dstDemTile;pe=P.morphing.phase,Be&&tt&&(this._prepareDemTileUniforms(g,Be,G,"_prev")&&(ie=Be),this._prepareDemTileUniforms(g,tt,G)&&(ee=tt))}const ye=Be=>Be&&Be.demTexture&&this.painter.linearFloatFilteringSupported()?H.LINEAR:H.NEAREST;let De=null;var Ae;if(this.enabled?ie&&ee?(De=ee.demTexture,z.activeTexture.set(H.TEXTURE4),ie.demTexture.bind(ye(ie),H.CLAMP_TO_EDGE),G.u_dem_lerp=pe):(ee=this.terrainTileForTile[g.tileID.key],De=this._prepareDemTileUniforms(g,ee,G)?ee.demTexture:this.emptyDEMTexture):De=this.emptyDEMTexture,z.activeTexture.set(H.TEXTURE2),De&&(G.u_dem_size=(Ae=De).size[0]===1?1:Ae.size[0]-2,De.bind(ye(ee),H.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(P&&P.useDepthForOcclusion,S,G),P&&P.useMeterToDem&&ee){const Be=(1<{if(dt===Ns)return;const er=[cb[Ns],"PROJECTION_GLOBE_VIEW"];Tt&&er.push("CUSTOM_ANTIALIASING");const lr=pe.isTileAffectedByFog(Is);ut=pe.getOrCreateProgram("globeRaster",{defines:er,overrideFog:lr}),dt=Ns},Kt=pe.colorModeForRenderPass(),Rt=new Jr(Ye.LEQUAL,Jr.ReadWrite,pe.depthRangeFor3D);Qd.update(Be);const Wt=o.dq(jt),Et=[o.aH(jt.center.lng),o.aL(jt.center.lat)],Lt=pe.globeSharedBuffers,Vt=[jt.width*o.o.devicePixelRatio,jt.height*o.o.devicePixelRatio],ds=Float32Array.from(jt.globeMatrix),Zt={useDenormalizedUpVectorScale:!0};{const Is=pe.transform,Ns=db(Is.zoom,ye.exaggeration(),ye.sourceCache._source.tileSize);dt=-1;const er=Ye.TRIANGLES;for(const lr of Ae){const hs=De.getTile(lr),ss=Xn.disabled,Ts=ye.prevTerrainTileForTile[lr.key],Rs=ye.terrainTileForTile[lr.key];E4(Ts,Rs)&&Qd.newMorphing(lr.key,Ts,Rs,Be,250),_f(pe,hs.emissiveTexture),tt.activeTexture.set(Ye.TEXTURE0),hs.texture&&hs.texture.bind(Ye.LINEAR,Ye.CLAMP_TO_EDGE);const qs=Qd.getMorphValuesForProxy(lr.key),Cr=qs?1:0;qs&&Object.assign(Zt,{morphing:{srcDemTile:qs.from,dstDemTile:qs.to,phase:o.dn(qs.phase)}});const br=o.dr(lr.canonical),_r=o.ds(br.getCenter().lat),nr=o.dt(lr.canonical,br,_r,Is.worldSize/Is._pixelsPerMercatorPixel),on=o.du(o.dv(lr.canonical)),gn=pe.emissiveMode==="mrt-fallback"?1:0,en=zg(Is.expandedFarZProjMatrix,ds,Wt,on,o.al(Is.zoom),Et,Is.frustumCorners.TL,Is.frustumCorners.TR,Is.frustumCorners.BR,Is.frustumCorners.BL,Is.globeCenterInViewSpace,Is.globeRadius,Vt,Ns,Is._farZ,gn,nr);if(ft(lr,Cr),ut&&(ye.setupElevationDraw(hs,ut,Zt),pe.uploadCommonUniforms(tt,ut,lr.toUnwrapped()),Lt)){const[nn,Gn,ma]=Lt.getGridBuffers(_r,Ns!==0);ut.draw(pe,er,Rt,ss,Kt,Cn.backCCW,en,"globe_raster",nn,Gn,ma)}}}if(Lt&&(pe.renderDefaultNorthPole||pe.renderDefaultSouthPole)){const Is=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Tt&&Is.push("CUSTOM_ANTIALIASING"),ut=pe.getOrCreateProgram("globeRaster",{defines:Is});for(const Ns of Ae){const{x:er,y:lr,z:hs}=Ns.canonical,ss=lr===0,Ts=lr===(1<nn.draw(pe,Ye.TRIANGLES,Rt,Xn.disabled,Kt,Cn.disabled,zg(jt.expandedFarZProjMatrix,nr,nr,on,0,Et,jt.frustumCorners.TL,jt.frustumCorners.TR,jt.frustumCorners.BR,jt.frustumCorners.BL,jt.globeCenterInViewSpace,jt.globeRadius,Vt,0,jt._farZ,gn),"globe_pole_raster",Gn,Cr,br);ye.setupElevationDraw(_r,ut,Zt),pe.uploadCommonUniforms(tt,ut,Ns.toUnwrapped()),ss&&pe.renderDefaultNorthPole&&en(ut,Rs),Ts&&pe.renderDefaultSouthPole&&(nr=o.cC(o.bb(),nr,[1,-1,1]),en(ut,qs))}}}})(z,H,G,ee,ie);else{const pe=z.context,ye=pe.gl;let De,Ae;const Be=z.shadowRenderer,tt=wc(z,z.longestCutoffRange),Ye=Kt=>{if(Ae===Kt)return;const Rt=[];Rt.push(cb[Kt]),tt.shouldRenderCutoff&&Rt.push("RENDER_CUTOFF"),Be&&(Rt.push("RENDER_SHADOWS"),Be.useNormalOffset&&Rt.push("NORMAL_OFFSET")),De=z.getOrCreateProgram("terrainRaster",{defines:Rt}),Ae=Kt},ut=z.colorModeForRenderPass(),dt=new Jr(ye.LEQUAL,Jr.ReadWrite,z.depthRangeFor3D);Qd.update(ie);const jt=z.transform,Tt=db(jt.zoom,H.exaggeration(),H.sourceCache._source.tileSize);let ft=[0,0,0];if(Be){const Kt=z.style.directionalLight,Rt=z.style.ambientLight;Kt&&Rt&&(ft=vf(z.style,Kt,Rt))}{Ae=-1;const Kt=ye.TRIANGLES,[Rt,Wt]=[H.gridIndexBuffer,H.gridSegments];for(const Et of ee){const Lt=G.getTile(Et),Vt=Xn.disabled,ds=H.prevTerrainTileForTile[Et.key],Zt=H.terrainTileForTile[Et.key];E4(ds,Zt)&&Qd.newMorphing(Et.key,ds,Zt,ie,250),_f(z,Lt.emissiveTexture),pe.activeTexture.set(ye.TEXTURE0),Lt.texture&&Lt.texture.bind(ye.LINEAR,ye.CLAMP_TO_EDGE);const Is=Qd.getMorphValuesForProxy(Et.key),Ns=Is?1:0;let er;Is&&(er={morphing:{srcDemTile:Is.from,dstDemTile:Is.to,phase:o.dn(Is.phase)}});const lr=z.emissiveMode==="mrt-fallback"?1:0,hs=Iv(Et.projMatrix,Pv(Et.canonical,jt.renderWorldCopies)?Tt/10:Tt,ft,lr);if(Ye(Ns),!De)continue;H.setupElevationDraw(Lt,De,er);const ss=Et.toUnwrapped();Be&&Be.setupShadows(ss,De),z.uploadCommonUniforms(pe,De,ss,null,tt),De.draw(z,Kt,dt,Vt,ut,Cn.backCCW,hs,"terrain_raster",H.gridBuffer,Rt,Wt)}}}}(S,this,this.proxySourceCache,g,this._updateTimestamp),this.renderingToTexture=!0,S.gpuTimingDeferredRenderEnd(),g.splice(0,g.length))}renderBatch(g){if(this._drapedRenderBatches.length===0)return g+1;this.renderingToTexture=!0;const S=this.painter,P=this.painter.context,z=this.proxySourceCache,H=this.proxiedCoords[z.id],G=this._drapedRenderBatches.shift(),ee=S.style.order,ie=[];this._updateFBOs(S.emissiveMode==="mrt-fallback");let pe=0;for(const ye of H){const De=z.getTileByID(ye.proxyTileKey),Ae=z.proxyCachedFBO[ye.key]?z.proxyCachedFBO[ye.key][g]:void 0,Be=Ae!==void 0?z.renderCache[Ae]:this.pool[pe++],tt=Ae!==void 0;if(De.texture=Be.tex,De.emissiveTexture=Be.emissiveTex,tt&&!Be.dirty){ie.push(De.tileID);continue}P.bindFramebuffer.set(Be.fb.framebuffer);const Ye=P.gl;let ut;Ye.drawBuffers(S.emissiveMode==="mrt-fallback"?[Ye.COLOR_ATTACHMENT0,Ye.COLOR_ATTACHMENT1]:[Ye.COLOR_ATTACHMENT0]),this.renderedToTile=!1,Be.dirty&&(P.clear({color:o.aq.transparent,stencil:0}),Be.dirty=!1);for(let dt=G.start;dt<=G.end;++dt){const jt=S.style._mergedLayers[ee[dt]];if(jt.isHidden(S.transform.zoom))continue;const Tt=S.style.getLayerSourceCache(jt),ft=Tt?this.proxyToSource[ye.key][Tt.id]:[ye];if(!ft)continue;const Kt=ft;P.viewport.set([0,0,Be.fb.width,Be.fb.height]),ut!==(Tt?Tt.id:null)&&(this._setupStencil(Be,ft,jt,Tt),ut=Tt?Tt.id:null),S.renderLayer(S,Tt,jt,Kt)}if(Ye.drawBuffers([Ye.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const dt of this._pendingGroundEffectLayers){const jt=S.style._mergedLayers[ee[dt]];if(jt.isHidden(S.transform.zoom))continue;const Tt=S.style.getLayerSourceCache(jt),ft=Tt?this.proxyToSource[ye.key][Tt.id]:[ye];if(!ft)continue;const Kt=ft;P.viewport.set([0,0,Be.fb.width,Be.fb.height]),ut!==(Tt?Tt.id:null)&&(this._setupStencil(Be,ft,jt,Tt),ut=Tt?Tt.id:null),S.renderLayer(S,Tt,jt,Kt)}this.renderedToTile?(Be.dirty=!0,ie.push(De.tileID)):tt||--pe,pe===5&&(pe=0,this.renderToBackBuffer(ie))}return this.renderToBackBuffer(ie),this.renderingToTexture=!1,P.bindFramebuffer.set(null),P.viewport.set([0,0,S.width,S.height]),G.end+1}postRender(){}isLayerOrderingCorrect(g){const S=g.order.length;let P=-1,z=S;for(let H=0;HP}getMinElevationBelowMSL(){let g=0;return this._visibleDemTiles.filter(S=>S.dem).forEach(S=>{g=Math.min(g,S.dem.tree.minimums[0])}),g===0?g:(g-30)*this._exaggeration}raycast(g,S,P){if(!this._visibleDemTiles)return null;const z=this._visibleDemTiles.filter(H=>H.dem).map(H=>{const G=H.tileID,ee=1<(H.t!==null?H.t:Number.MAX_VALUE)-(G.t!==null?G.t:Number.MAX_VALUE));for(const H of z){if(H.t==null)return null;const G=H.tile.dem.tree.raycast(H.minx,H.miny,H.maxx,H.maxy,g,S,P);if(G!=null)return G}return null}_createFBO(){const g=this.painter.context,S=g.gl,P=this.drapeBufferSize;g.activeTexture.set(S.TEXTURE0);const z=new o.T(g,{width:P[0],height:P[1],data:null},S.RGBA8);z.bind(S.LINEAR,S.CLAMP_TO_EDGE);const H=g.createFramebuffer(P[0],P[1],1,null);let G;return H.colorAttachment0.set(z.texture),this._emissiveTexture&&(G=new o.T(g,{width:P[0],height:P[1],data:null},S.R8),G.bind(S.LINEAR,S.CLAMP_TO_EDGE),H.createColorAttachment(g,1),H.colorAttachment1.set(G.texture)),H.depthAttachment=new _M(g,H.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=g.createRenderbuffer(g.gl.DEPTH_STENCIL,P[0],P[1]),this._stencilRef=0,H.depthAttachment.set(this._sharedDepthStencil),g.clear({stencil:0})):H.depthAttachment.set(this._sharedDepthStencil),g.extTextureFilterAnisotropic&&S.texParameterf(S.TEXTURE_2D,g.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,g.extTextureFilterAnisotropicMax),{fb:H,tex:z,emissiveTex:G,dirty:!1}}_updateFBOs(g){if(this._emissiveTexture!==g){for(const S of this.pool)this._updateFBO(S,g);for(const S of this.proxySourceCache.renderCache)this._updateFBO(S,g);this._emissiveTexture=g}}_updateFBO(g,S){const P=g.fb,z=this.painter.context,H=z.gl,G=this.drapeBufferSize;if(S){const ee=new o.T(z,{width:G[0],height:G[1],data:null},H.R8);ee.bind(H.LINEAR,H.CLAMP_TO_EDGE),g.emissiveTex=ee,P.createColorAttachment(z,1),P.colorAttachment1.set(ee.texture)}else g.emissiveTex=void 0,P.removeColorAttachment(z,1);g.dirty=!0}_initFBOPool(){for(;this.pool.length{const S=this._style._mergedLayers[g],P=S.isHidden(this.painter.transform.zoom);return S.type==="hillshade"||S.type==="custom"?!P&&S.shouldRedrape():!P&&S.hasTransition()})}_clearLineLayersFromRenderCache(){let g=!1;for(const P of this._style.getSources())if(P instanceof Cd){g=!0;break}if(!g)return;const S={};for(let P=0;Pie>ee.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=P}_setupRenderCache(g){const S=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,S.renderCache.length>S.renderCachePool.length){const G=Object.values(S.proxyCachedFBO);S.proxyCachedFBO={};for(let ee=0;ee=0;G--){const ee=P[G];if(S.getTileByID(ee.key),S.proxyCachedFBO[ee.key]!==void 0){const ie=g[ee.key],pe=this.proxyToSource[ee.key];let ye=0;for(const De in pe){const Ae=pe[De],Be=ie[De];if(!Be||Be.length!==Ae.length||Ae.some((tt,Ye)=>tt!==Be[Ye]||z[De]&&z[De].hasOwnProperty(tt.key))){ye=-1;break}++ye}for(const De in S.proxyCachedFBO[ee.key])S.renderCache[S.proxyCachedFBO[ee.key][De]].dirty=ye<0||ye!==Object.values(ie).length}}const H=[...this._drapedRenderBatches];H.sort((G,ee)=>ee.end-ee.start-(G.end-G.start));for(const G of H)for(const ee of P){if(S.proxyCachedFBO[ee.key])continue;let ie=S.renderCachePool.pop();ie===void 0&&S.renderCache.length<50&&(ie=S.renderCache.length,S.renderCache.push(this._createFBO())),ie!==void 0&&(S.proxyCachedFBO[ee.key]={},S.proxyCachedFBO[ee.key][G.start]=ie,S.renderCache[ie].dirty=!0)}this._tilesDirty={}}_setupStencil(g,S,P,z){if(!z||!this._sourceTilesOverlap[z.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const H=this.painter.context,G=H.gl;if(S.length<=1)return void(this._overlapStencilType=!1);let ee;if(P.isTileClipped())ee=S.length,this._overlapStencilMode.test={func:G.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(S[0].overscaledZ>S[S.length-1].overscaledZ))return void(this._overlapStencilType=!1);ee=1,this._overlapStencilMode.test={func:G.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+ee>255&&(H.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=ee,this._overlapStencilMode.ref=this._stencilRef,P.isTileClipped()&&this._renderTileClippingMasks(S,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):Xn.disabled}_renderTileClippingMasks(g,S){const P=this.painter,z=this.painter.context,H=z.gl;P._tileClippingMaskIDs={},z.setColorMode(Hn.disabled),z.setDepthMode(Jr.disabled);const G=P.getOrCreateProgram("clippingMask");for(const ee of g){const ie=P._tileClippingMaskIDs[ee.key]=--S;G.draw(P,H.TRIANGLES,Jr.disabled,new Xn({func:H.ALWAYS,mask:0},ie,255,H.KEEP,H.KEEP,H.REPLACE),Hn.disabled,Cn.disabled,Ow(ee.projMatrix),"$clipping",P.tileExtentBuffer,P.quadTriangleIndexBuffer,P.tileExtentSegments)}}pointCoordinate(g){const S=this.painter.transform;if(g.x<0||g.x>S.width||g.y<0||g.y>S.height)return null;const P=[g.x,g.y,1,1];o.aE(P,P,S.pixelMatrixInverse),o.cu(P,P,1/P[3]),P[0]/=S.worldSize,P[1]/=S.worldSize;const z=S._camera.position,H=o.bU(1,S.center.lat),G=[z[0],z[1],z[2]/H,0],ee=o.cV([],P.slice(0,3),G);o.ay(ee,ee);const ie=this.raycast(G,ee,this._exaggeration);return ie!==null&&ie?(o.bg(G,G,ee,ie),G[3]=G[2],G[2]*=H,G):null}_setupProxiedCoordsForOrtho(g,S,P){if(g.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(g,S,P);this._findCoveringTileCache[g.id]=this._findCoveringTileCache[g.id]||{};const z=this.proxiedCoords[g.id]=[],H=this.proxyCoords;for(let ie=0;ieye.overscaledZ-pe.overscaledZ)}_setupProxiedCoordsForImageSource(g,S,P){if(!g.getSource().loaded())return;const z=this.proxiedCoords[g.id]=[],H=this.proxyCoords,G=g.getSource(),ee=G.tileID;if(!ee)return;const ie=new o.P(ee.x,ee.y)._div(1<(De.min.x=Math.min(De.min.x,Ae.x-ie.x),De.min.y=Math.min(De.min.y,Ae.y-ie.y),De.max.x=Math.max(De.max.x,Ae.x-ie.x),De.max.y=Math.max(De.max.y,Ae.y-ie.y),De),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),ye=(De,Ae)=>{const Be=De.wrap+De.canonical.x/(1<ut+pe.max.x||tt+Yedt+pe.max.y};for(let De=0;DeG.key===S.tileID.key);if(H)return H}if(S.tileID.key!==g.key){const H=g.canonical.z-S.tileID.canonical.z;let G,ee,ie;z=o.bb();const pe=S.tileID.wrap-g.wrap<0?(G=o.an>>H,ee=G*((S.tileID.canonical.x<=De){const Ae=g.canonical.z-De;S.getSource().reparseOverscaled?(ee=Math.max(g.canonical.z+2,S.transform.tileZoom),G=new o.aR(ee,g.wrap,De,g.canonical.x>>Ae,g.canonical.y>>Ae)):Ae!==0&&(ee=De,G=new o.aR(ee,g.wrap,De,g.canonical.x>>Ae,g.canonical.y>>Ae))}G.key!==g.key&&(pe.push(G.key),P=S.getTile(G))}const ye=De=>{pe.forEach(Ae=>{z[Ae]=De}),pe.length=0};for(ee-=1;ee>=ie&&(!P||!P.hasData());ee--){P&&ye(P.tileID.key);const De=G.calculateScaledKey(ee);if(P=S.getTileByID(De),P&&P.hasData())break;const Ae=z[De];if(Ae===null)break;Ae===void 0?pe.push(De):P=S.getTileByID(Ae)}return ye(P?P.tileID.key:null),P&&P.hasData()?P:null}findDEMTileFor(g){return this.enabled?this._findTileCoveringTileID(g,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(g,S){let P=this._tilesDirty[g];P||(P=this._tilesDirty[g]={}),P[S.key]=!0}}function ub(M,g,S){const P=function(ee,ie,pe){const ye=o.bi(ie,ee),De=o.bi(pe,[.2126,.7152,.0722]),Ae=(tt,Ye,ut)=>(1-ut)*tt+ut*Ye,Be=Ae(1-.3*Math.min(De,1),1,Math.min(ye+1,1));return Ae(.92,1,Math.asin(o.aC(ie[2],-1,1))/Math.PI+.5)*Be}(M,[0,0,1],g),z=[0,0,0];o.bJ(z,S.slice(0,3),P);const H=[0,0,0];o.bJ(H,g.slice(0,3),M[2]);const G=[0,0,0];return o.cT(G,z,H),o.cW(G)}const A4=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],hb=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Yc{static cacheKey(g,S,P,z){const H=[S];z&&H.push(z.cacheKey);for(const G of P)(typeof G=="string"&&G.includes(" ")||g.usedDefines.has(G))&&H.push(G);return H.join("/")}constructor(g,S,P,z,H,G){const ee=g.gl;this.program=ee.createProgram(),this.configuration=z,this.name=S,this.fixedDefines=[...G];const ie=`#version 300 es ${(z?z.defines():[]).concat(G.map(Ye=>`#define ${Ye}`)).join(` `)}`,pe=[ie,Cv];for(const Ye of P.fragmentIncludes)pe.push(bf[Ye]);pe.push(P.fragmentSource);const ye=pe.join(` `),De=[ie,b4];for(const Ye of P.vertexIncludes)De.push(bf[Ye]);this.forceManualRenderingForInstanceIDShaders=g.forceManualRenderingForInstanceIDShaders&&P.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&De.push("uniform int u_instanceID;"),De.push(P.vertexSource);let Ae=De.join(` `);this.forceManualRenderingForInstanceIDShaders&&(Ae=Ae.replaceAll("gl_InstanceID","u_instanceID"));const Be=ee.createShader(ee.FRAGMENT_SHADER);if(ee.isContextLost())return void(this.failedToCreate=!0);ee.shaderSource(Be,ye),ee.compileShader(Be),ee.attachShader(this.program,Be);const tt=ee.createShader(ee.VERTEX_SHADER);ee.isContextLost()?this.failedToCreate=!0:(ee.shaderSource(tt,Ae),ee.compileShader(tt),ee.attachShader(this.program,tt),this.attributes={},ee.linkProgram(this.program),ee.deleteShader(tt),ee.deleteShader(Be),this.fixedUniforms=H(g),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=z?z.getUniforms(g):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(Ye=>({u_instanceID:new o.bX(Ye)}))(g)),(G.includes("TERRAIN")||G.includes("ELEVATED")||S.includes("symbol")||S.includes("circle"))&&(this.terrainUniforms=(Ye=>({u_dem:new o.bX(Ye),u_dem_prev:new o.bX(Ye),u_dem_tl:new o.b_(Ye),u_dem_scale:new o.bZ(Ye),u_dem_tl_prev:new o.b_(Ye),u_dem_scale_prev:new o.bZ(Ye),u_dem_size:new o.bZ(Ye),u_dem_lerp:new o.bZ(Ye),u_exaggeration:new o.bZ(Ye),u_depth:new o.bX(Ye),u_depth_size_inv:new o.b_(Ye),u_depth_range_unpack:new o.b_(Ye),u_occluder_half_size:new o.bZ(Ye),u_occlusion_depth_offset:new o.bZ(Ye),u_meter_to_dem:new o.bZ(Ye),u_label_plane_matrix_inv:new o.b$(Ye)}))(g)),G.includes("GLOBE")&&(this.globeUniforms=(Ye=>({u_tile_tl_up:new o.bY(Ye),u_tile_tr_up:new o.bY(Ye),u_tile_br_up:new o.bY(Ye),u_tile_bl_up:new o.bY(Ye),u_tile_up_scale:new o.bZ(Ye)}))(g)),G.includes("FOG")&&(this.fogUniforms=(Ye=>({u_fog_matrix:new o.b$(Ye),u_fog_range:new o.b_(Ye),u_fog_color:new o.cO(Ye),u_fog_horizon_blend:new o.bZ(Ye),u_fog_vertical_limit:new o.b_(Ye),u_fog_temporal_offset:new o.bZ(Ye),u_frustum_tl:new o.bY(Ye),u_frustum_tr:new o.bY(Ye),u_frustum_br:new o.bY(Ye),u_frustum_bl:new o.bY(Ye),u_globe_pos:new o.bY(Ye),u_globe_radius:new o.bZ(Ye),u_globe_transition:new o.bZ(Ye),u_is_globe:new o.bX(Ye),u_viewport:new o.b_(Ye)}))(g)),G.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(Ye=>({u_cutoff_params:new o.cO(Ye)}))(g)),G.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(Ye=>({u_lighting_ambient_color:new o.bY(Ye),u_lighting_directional_dir:new o.bY(Ye),u_lighting_directional_color:new o.bY(Ye),u_ground_radiance:new o.bY(Ye)}))(g)),G.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(Ye=>({u_light_matrix_0:new o.b$(Ye),u_light_matrix_1:new o.b$(Ye),u_fade_range:new o.b_(Ye),u_shadow_normal_offset:new o.bY(Ye),u_shadow_intensity:new o.bZ(Ye),u_shadow_texel_size:new o.bZ(Ye),u_shadow_map_resolution:new o.bZ(Ye),u_shadow_direction:new o.bY(Ye),u_shadow_bias:new o.bY(Ye),u_shadowmap_0:new o.bX(Ye),u_shadowmap_1:new o.bX(Ye)}))(g)))}getAttributeLocation(g,S){let P=this.attributes[S];return P===void 0&&(P=this.attributes[S]=g.getAttribLocation(this.program,S)),P}setTerrainUniformValues(g,S){if(!this.terrainUniforms)return;const P=this.terrainUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const z in S)P[z]&&P[z].set(this.program,z,S[z])}}setGlobeUniformValues(g,S){if(!this.globeUniforms)return;const P=this.globeUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const z in S)P[z]&&P[z].set(this.program,z,S[z])}}setFogUniformValues(g,S){if(!this.fogUniforms)return;const P=this.fogUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const z in S)P[z].set(this.program,z,S[z])}}setCutoffUniformValues(g,S){if(!this.cutoffUniforms)return;const P=this.cutoffUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const z in S)P[z].set(this.program,z,S[z])}}setLightsUniformValues(g,S){if(!this.lightsUniforms)return;const P=this.lightsUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const z in S)P[z].set(this.program,z,S[z])}}setShadowUniformValues(g,S){if(this.failedToCreate||!this.shadowUniforms)return;const P=this.shadowUniforms;g.program.set(this.program);for(const z in S)P[z].set(this.program,z,S[z])}_drawDebugWireframe(g,S,P,z,H,G,ee,ie,pe,ye){const De=g.options.wireframe;if(De.terrain===!1&&De.layers2D===!1&&De.layers3D===!1)return;const Ae=g.context;if(!(!(!De.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!De.layers2D||g._terrain&&g._terrain.renderingToTexture||!A4.includes(this.name))||!(!De.layers3D||!hb.includes(this.name))))return;const Be=Ae.gl,tt=g.wireframeDebugCache.getLinesFromTrianglesBuffer(g.frameCounter,H,Ae);if(!tt)return;const Ye=[...this.fixedDefines,"DEBUG_WIREFRAME"],ut=g.getOrCreateProgram(this.name,{config:this.configuration,defines:Ye});Ae.program.set(ut.program);const dt=(ft,Kt,Rt)=>{if(Kt[ft]&&Rt[ft])for(const Wt in Kt[ft])Rt[ft][Wt]&&Rt[ft][Wt].set(Rt.program,Wt,Kt[ft][Wt].current)};pe&&pe.setUniforms(ut.program,Ae,ut.binderUniforms,ee,{zoom:ie}),dt("fixedUniforms",this,ut),dt("terrainUniforms",this,ut),dt("globeUniforms",this,ut),dt("fogUniforms",this,ut),dt("lightsUniforms",this,ut),dt("shadowUniforms",this,ut),tt.bind(),Ae.setColorMode(new Hn([Be.ONE,Be.ONE_MINUS_SRC_ALPHA,Be.ZERO,Be.ONE],o.aq.transparent,[!0,!0,!0,!1])),Ae.setDepthMode(new Jr(S.func===Be.LESS?Be.LEQUAL:S.func,Jr.ReadOnly,S.range)),Ae.setStencilMode(Xn.disabled);const jt=3*G.primitiveLength*2,Tt=3*G.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const ft=ye||1;for(let Kt=0;Kt1?Be.drawElementsInstanced(Be.LINES,jt,Be.UNSIGNED_SHORT,Tt,ye):Be.drawElements(Be.LINES,jt,Be.UNSIGNED_SHORT,Tt);H.bind(),Ae.program.set(this.program),Ae.setDepthMode(S),Ae.setStencilMode(P),Ae.setColorMode(z)}checkUniforms(g,S,P){if(this.fixedDefines.includes(S)){for(const z of Object.keys(P))if(!P[z].initialized)throw new Error(`Program '${this.name}', from draw '${g}': uniform ${z} not set but required by ${S} being defined`)}}draw(g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut){const dt=g.context,jt=dt.gl;if(this.failedToCreate)return;dt.program.set(this.program),dt.setDepthMode(P),dt.setStencilMode(z),dt.setColorMode(H),dt.setCullFace(G);for(const[Et,Lt]of this.fixedUniformsEntries)Lt.set(this.program,Et,ee[Et]);tt&&tt.setUniforms(this.program,dt,this.binderUniforms,Ae,{zoom:Be});const Tt={[jt.POINTS]:1,[jt.LINES]:2,[jt.TRIANGLES]:3,[jt.LINE_STRIP]:1}[S];this.checkUniforms(ie,"RENDER_SHADOWS",this.shadowUniforms);const ft=Ye||[],Kt=tt?tt.getPaintVertexBuffers():[],Rt=S===jt.TRIANGLES&&ye,Wt=ut&&ut>0?1:void 0;for(const Et of De.get()){const Lt=Et.vaos||(Et.vaos={});if((Lt[ie]||(Lt[ie]=new j4)).bind(dt,this,pe,Kt,ye,Et.vertexOffset,ft,Wt),this.forceManualRenderingForInstanceIDShaders){const Vt=ut||1;for(let ds=0;ds1?jt.drawElementsInstanced(S,Et.primitiveLength*Tt,jt.UNSIGNED_SHORT,Et.primitiveOffset*Tt*2,ut):ye?jt.drawElements(S,Et.primitiveLength*Tt,jt.UNSIGNED_SHORT,Et.primitiveOffset*Tt*2):jt.drawArrays(S,Et.vertexOffset,Et.vertexLength);Rt&&this._drawDebugWireframe(g,P,z,H,ye,Et,Ae,Be,tt,ut)}}}function wM(M,g,S=0){const P=Math.pow(2,g.tileID.overscaledZ),z=g.tileSize*Math.pow(2,M.transform.tileZoom)/P,H=z*(g.tileID.canonical.x+g.tileID.wrap*P),G=z*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:[H>>16,G>>16],u_pixel_coord_lower:[65535&H,65535&G],u_pattern_transition:S}}const rN={terrain:0,flat:1},nN=o.bb(),Qu=(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut,dt,jt=[0,0,1])=>{const Tt=g.style.light,ft=Tt.properties.get("position"),Kt=[ft.x,ft.y,ft.z],Rt=o.dE();Tt.properties.get("anchor")==="viewport"&&(o.dF(Rt,-g.transform.angle),o.dG(Kt,Kt,Rt));const Wt=Tt.properties.get("color").toPremultipliedRenderColor(null),Et=g.transform,Lt={u_matrix:M,u_lightpos:Kt,u_lightintensity:Tt.properties.get("intensity"),u_lightcolor:[Wt.r,Wt.g,Wt.b],u_vertical_gradient:+S,u_opacity:P,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:nN,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:rN[pe],u_base_type:rN[ye],u_ao:z,u_edge_radius:H,u_width_scale:G,u_flood_light_color:tt,u_vertical_scale:Ye,u_flood_light_intensity:ut,u_ground_shadow_factor:dt,u_front_cutoff_params:jt};return Et.projection.name==="globe"&&(Lt.u_tile_id=[ee.canonical.x,ee.canonical.y,1<({u_matrix:M,u_edge_radius:g,u_width_scale:S,u_vertical_scale:P,u_height_type:rN[z],u_base_type:rN[H]}),Pa=(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut,dt)=>{const jt=Qu(M,g,S,P,z,H,G,ee,pe,ye,De,Ae,Be,tt,Ye,ut,1,[0,0,0]),Tt={u_height_factor:-Math.pow(2,ee.overscaledZ)/ie.tileSize/8};return Object.assign(jt,wM(g,ie,dt),Tt)},Bg=(M,g,S)=>({u_matrix:M,u_emissive_strength:g,u_ground_shadow_factor:S}),mb=(M,g,S,P,z,H=0)=>Object.assign(Bg(M,g,z),wM(S,P,H)),M4=(M,g,S,P)=>({u_matrix:M,u_world:S,u_emissive_strength:g,u_ground_shadow_factor:P}),fb=(M,g,S,P,z,H,G=0)=>Object.assign(mb(M,g,S,P,H,G),{u_world:z}),pb=(M,g)=>({u_matrix:M,u_depth_bias:g}),zw=(M,g)=>({u_matrix:M,u_ground_shadow_factor:g}),Dv=(M,g,S,P,z)=>({u_matrix:M,u_camera_pos:[g[0],g[1],g[2]],u_depth_bias:S,u_height_scale:P,u_reset_depth:z}),Bw=(M,g,S)=>({u_image:M,u_opacity:g,u_blend_mode:S}),$g=(M,g,S,P,z,H,G,ee,ie,pe=[0,0,1])=>({u_matrix:M,u_normal_matrix:g,u_opacity:S,u_faux_facade_ao_intensity:P,u_camera_pos:z,u_tile_to_meter:H,u_facade_emissive_chance:G,u_flood_light_color:ee,u_flood_light_intensity:ie,u_front_cutoff_params:pe}),$w=M=>({u_matrix:M}),xb=M=>({u_matrix:M}),aN=(M,g,S,P,z,H,G,ee)=>{const ie=o.an/H.tileSize;return{u_matrix:M,u_inv_rot_matrix:g,u_camera_to_center_distance:S.getCameraToCenterDistance(ee),u_extrude_scale:[S.pixelsToGLUnits[0]/ie,S.pixelsToGLUnits[1]/ie],u_zoom_transition:P,u_tile_id:G,u_merc_center:z}},jc=(M,g,S,P)=>({u_matrix:M,u_inv_matrix:g,u_camera_to_center_distance:S.getCameraToCenterDistance(P),u_viewport_size:[S.width,S.height]}),Xh=(M,g,S=1)=>({u_matrix:M,u_color:g,u_overlay:0,u_overlay_scale:S}),wf=o.bb(),iN=(M,g,S,P,z,H,G)=>{const ee=M.transform,ie=ee.projection.name==="globe",pe=ie?o.dH(ee.zoom,g.canonical)*ee._pixelsPerMercatorPixel:o.aA(S,1,H),ye={u_matrix:g.projMatrix,u_extrude_scale:pe,u_intensity:G,u_inv_rot_matrix:wf,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(ie){ye.u_inv_rot_matrix=P,ye.u_merc_center=z,ye.u_tile_id=[g.canonical.x,g.canonical.y,1<({u_matrix:g,u_normalize_matrix:S,u_globe_matrix:P,u_merc_matrix:z,u_grid_matrix:H,u_tl_parent:G,u_scale_parent:ye,u_fade_t:De.mix,u_opacity:De.opacity*Ae.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Ae.paint.get("raster-brightness-min"),u_brightness_high:Ae.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(Ae.paint.get("raster-saturation")),u_contrast_factor:o.dI(Ae.paint.get("raster-contrast")),u_spin_weights:jM(Ae.paint.get("raster-hue-rotate")),u_perspective_transform:Be,u_raster_elevation:tt,u_zoom_transition:ee,u_merc_center:ie,u_cutoff_params:pe,u_colorization_mix:oN(o.dK,ut,jt),u_colorization_offset:$m(o.dK,dt,jt),u_color_ramp:Ye,u_texture_offset:[ft/(Tt+2*ft),Tt/(Tt+2*ft)],u_texture_res:[Tt+2*ft,Tt+2*ft],u_emissive_strength:Kt,u_zbias_factor:lN(M)});function jM(M){M*=Math.PI/180;const g=Math.sin(M),S=Math.cos(M);return[(2*S+1)/3,(-Math.sqrt(3)*g-S+1)/3,(Math.sqrt(3)*g-S+1)/3]}const Kp=.05,NM=(M,g,S,P,z,H,G,ee,ie,pe,ye,De)=>({u_matrix:M,u_normalize_matrix:g,u_globe_matrix:S,u_merc_matrix:P,u_grid_matrix:z,u_tl_parent:H,u_scale_parent:pe,u_fade_t:ye.mix,u_opacity:ye.opacity,u_image0:0,u_image1:1,u_raster_elevation:De,u_zoom_transition:G,u_merc_center:ee,u_cutoff_params:ie}),kM=(M,g,S,P,z,H,G,ee,ie,pe)=>({u_particle_texture:M,u_particle_texture_side_len:g,u_tile_offset:S,u_velocity:P,u_color_ramp:H,u_velocity_res:z,u_max_speed:G,u_uv_offset:ee,u_data_scale:[255*ie[0],255*ie[1]],u_data_offset:pe,u_particle_pos_scale:1.1,u_particle_pos_offset:[Kp,Kp]}),I4=(M,g,S,P,z,H,G,ee,ie,pe)=>({u_particle_texture:M,u_particle_texture_side_len:g,u_velocity:S,u_velocity_res:P,u_max_speed:z,u_speed_factor:H,u_reset_rate:G,u_rand_seed:Math.random(),u_uv_offset:ee,u_data_scale:[255*ie[0],255*ie[1]],u_data_offset:pe,u_particle_pos_scale:1.1,u_particle_pos_offset:[Kp,Kp]}),Uw=o.bb(),Rv=(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut,dt,jt,Tt,ft,Kt,Rt,Wt)=>{const Et=z.transform,Lt={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:Et.getCameraToCenterDistance(jt),u_rotate_symbol:+S,u_aspect_ratio:Et.width/Et.height,u_fade_change:z.options.fadeDuration?z.symbolFadeChange:1,u_matrix:H,u_label_plane_matrix:G,u_coord_matrix:ee,u_is_text:+pe,u_elevation_from_sea:ie?1:0,u_pitch_with_map:+P,u_texsize:ye,u_texsize_icon:De,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Uw,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Uw,u_up_vector:[0,-1,0],u_color_adj_mat:Kt,u_icon_transition:Rt||0,u_gamma_scale:P?z.transform.getCameraToCenterDistance(jt)*Math.cos(z.terrain?0:z.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Wt||1,u_ground_shadow_factor:Tt,u_inv_matrix:o.b7(o.bb(),G),u_normal_scale:ft,u_lutTexture:10,u_zoom:Et.zoom-Math.floor(Et.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 jt.name==="globe"&&(Lt.u_tile_id=[Be.canonical.x,Be.canonical.y,1<({u_matrix:M,u_emissive_strength:g,u_opacity:S,u_color:P}),Yp=(M,g,S,P,z,H,G,ee,ie)=>Object.assign(function(pe,ye,De,Ae,Be,tt){const{width:Ye,height:ut}=Ae.imageManager.getPixelSize(ye),dt=Math.pow(2,tt.tileID.overscaledZ),jt=tt.tileSize*Math.pow(2,Ae.transform.tileZoom)/dt,Tt=jt*(tt.tileID.canonical.x+tt.tileID.wrap*dt),ft=jt*tt.tileID.canonical.y;return{u_image:0,u_pattern_tl:De.tl,u_pattern_br:De.br,u_texsize:[Ye,ut],u_pattern_size:De.displaySize,u_pattern_units_to_pixels:Be?[Ae.transform.width,-1*Ae.transform.height]:[1/o.aA(tt,1,Ae.transform.tileZoom),1/o.aA(tt,1,Ae.transform.tileZoom)],u_pixel_coord_upper:[Tt>>16,ft>>16],u_pixel_coord_lower:[65535&Tt,65535&ft]}}(0,H,G,P,ee,ie),{u_matrix:M,u_emissive_strength:g,u_opacity:S}),Ug=new Float32Array(o.b9([])),Zp=(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be=[0,0,0],tt,Ye,ut)=>{const dt=z.style.light,jt=dt.properties.get("position"),Tt=[-jt.x,-jt.y,jt.z],ft=o.dE();dt.properties.get("anchor")==="viewport"&&(o.dF(ft,-z.transform.angle),o.dG(Tt,Tt,ft));const Kt=ye.alphaMode==="MASK",Rt=dt.properties.get("color").toNonPremultipliedRenderColor(null),Wt=Ae.paint.get("model-ambient-occlusion-intensity"),Et=Ae.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return Et.a=Ae.paint.get("model-color-mix-intensity").constantOr(0),ut&&(Et.r=ut[0],Et.g=ut[1],Et.b=ut[2],Et.a=ut[3]),Ye&&(Et.r=Ye.color.r,Et.g=Ye.color.g,Et.b=Ye.color.b,Et.a=Ye.colorMix,De=Ye.emissionStrength,H*=Ye.opacity),{u_matrix:M,u_lighting_matrix:g,u_normal_matrix:S,u_node_matrix:P||Ug,u_lightpos:Tt,u_lightintensity:dt.properties.get("intensity"),u_lightcolor:[Rt.r,Rt.g,Rt.b],u_camera_pos:Be,u_opacity:H,u_baseTextureIsAlpha:0,u_alphaMask:+Kt,u_alphaCutoff:ye.alphaCutoff,u_baseColorFactor:G.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:ee.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:ie,u_roughnessFactor:pe,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:Et.toArray01(),u_aoIntensity:Wt,u_emissive_strength:De,u_occlusionTextureTransform:tt||[0,0,0,0]}},qw=(M,g=Ug,S=Ug)=>({u_matrix:M,u_instance:g,u_node_matrix:S}),gb={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 jf{constructor(g,S,P,z){this.id=jf.uniqueIdxCounter,jf.uniqueIdxCounter++,this.context=g;const H=g.gl;this.buffer=H.createBuffer(),this.dynamicDraw=!!P,this.context.unbindVAO(),g.bindElementBuffer.set(this.buffer),H.bufferData(H.ELEMENT_ARRAY_BUFFER,S.arrayBuffer,this.dynamicDraw?H.DYNAMIC_DRAW:H.STATIC_DRAW),this.dynamicDraw||z||S.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(g){this.id=jf.uniqueIdxCounter,jf.uniqueIdxCounter++;const S=this.context.gl;this.context.unbindVAO(),this.bind(),S.bufferSubData(S.ELEMENT_ARRAY_BUFFER,0,g.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}jf.uniqueIdxCounter=0;const cN={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class dN{constructor(g,S,P,z,H,G){this.length=S.length,this.attributes=P,this.itemSize=S.bytesPerElement,this.dynamicDraw=z,this.instanceCount=G,this.context=g;const ee=g.gl;this.buffer=ee.createBuffer(),g.bindVertexBuffer.set(this.buffer),ee.bufferData(ee.ARRAY_BUFFER,S.arrayBuffer,this.dynamicDraw?ee.DYNAMIC_DRAW:ee.STATIC_DRAW),this.dynamicDraw||H||S.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(g){const S=this.context.gl;this.bind(),S.bufferSubData(S.ARRAY_BUFFER,0,g.arrayBuffer)}enableAttributes(g,S){for(const P of this.attributes){const z=S.getAttributeLocation(g,P.name);z!==-1&&g.enableVertexAttribArray(z)}}setVertexAttribPointers(g,S,P){for(const z of this.attributes){const H=S.getAttributeLocation(g,z.name);if(H!==-1){const G=z.offset+this.itemSize*(P||0);z.type==="Float32"?g.vertexAttribPointer(H,z.components,g.FLOAT,!1,this.itemSize,G):g.vertexAttribIPointer(H,z.components,g[cN[z.type]],this.itemSize,G)}}}setVertexAttribDivisor(g,S,P){for(let z=0;z0&&g.vertexAttribDivisor(H,P)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Vw{constructor(g,S,P,z,H){this.context=g,this.width=S,this.height=P;const G=this.framebuffer=g.gl.createFramebuffer();z>0&&(this.colorAttachment0=new Mv(g,G,0)),z>1&&(this.colorAttachment1=new Mv(g,G,1)),H&&(this.depthAttachmentType=H,this.depthAttachment=H==="renderbuffer"?new Rw(g,G):new sN(g,G))}static createWithTexture(g,S,P,z,H){const G=g.gl;if(g.activeTexture.set(G.TEXTURE1),g.viewport.set([0,0,P,z]),S&&S.width===P&&S.height===z)return G.bindTexture(G.TEXTURE_2D,S.colorAttachment0.get()),g.bindFramebuffer.set(S.framebuffer),S;S&&S.destroy();const ee=new o.T(g,{width:P,height:z,data:null},g.extRenderToTextureHalfFloat?g.gl.RGBA16F:g.gl.RGBA8);ee.bind(G.LINEAR,G.CLAMP_TO_EDGE);const ie=g.createFramebuffer(P,z,1,null);if(ie.colorAttachment0.set(ee.texture),H){const pe=g.createRenderbuffer(G.DEPTH24_STENCIL8,P,z);g.bindFramebuffer.set(ie.framebuffer),G.framebufferRenderbuffer(G.FRAMEBUFFER,G.DEPTH_STENCIL_ATTACHMENT,G.RENDERBUFFER,pe),ie._stencilRbo=pe}return ie}createColorAttachment(g,S){S===0?this.colorAttachment0=new Mv(g,this.framebuffer,0):S===1&&(this.colorAttachment1=new Mv(g,this.framebuffer,1))}removeColorAttachment(g,S){const P=this.context.gl;let z;S===0?(z=this.colorAttachment0.get(),this.colorAttachment0=void 0):S===1&&(z=this.colorAttachment1.get(),this.colorAttachment1=void 0),z&&P.deleteTexture(z)}destroy(){const g=this.context.gl;if(this.colorAttachment0){const S=this.colorAttachment0.get();S&&g.deleteTexture(S)}if(this.colorAttachment1){const S=this.colorAttachment1.get();S&&g.deleteTexture(S)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const S=this.depthAttachment.get();S&&g.deleteRenderbuffer(S)}else{const S=this.depthAttachment.get();S&&g.deleteTexture(S)}this._stencilRbo&&(g.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),g.deleteFramebuffer(this.framebuffer)}}class qg{constructor(g,S){this.gl=g,this.clearColor=new Tw(this),this.clearDepth=new vD(this),this.clearStencil=new X2(this),this.colorMask=new bD(this),this.depthMask=new hp(this),this.stencilMask=new Ew(this),this.stencilFunc=new Tv(this),this.stencilOp=new Q2(this),this.stencilTest=new ny(this),this.depthRange=new ay(this),this.depthTest=new iy(this),this.depthFunc=new Yh(this),this.blend=new J2(this),this.blendFunc=new Aw(this),this.blendColor=new yM(this),this.blendEquation=new Ev(this),this.cullFace=new Mw(this),this.cullFaceSide=new Iw(this),this.frontFace=new eN(this),this.program=new Pw(this),this.activeTexture=new Lw(this),this.viewport=new Zh(this),this.bindFramebuffer=new wh(this),this.bindRenderbuffer=new S4(this),this.bindTexture=new Av(this),this.bindVertexBuffer=new C4(this),this.bindElementBuffer=new vM(this),this.bindVertexArrayOES=new bM(this),this.pixelStoreUnpack=new T4(this),this.pixelStoreUnpackPremultiplyAlpha=new tN(this),this.pixelStoreUnpackFlipY=new Dw(this),this.options=S?Object.assign({},S):{},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=S&&!!S.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=S&&!!S.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,S,P){return new jf(this,g,S,P)}createVertexBuffer(g,S,P,z,H){return new dN(this,g,S,P,z,H)}createRenderbuffer(g,S,P){const z=this.gl,H=z.createRenderbuffer();return this.bindRenderbuffer.set(H),z.renderbufferStorage(z.RENDERBUFFER,g,S,P),this.bindRenderbuffer.set(null),H}createFramebuffer(g,S,P,z){return new Vw(this,g,S,P,z)}clear({color:g,depth:S,stencil:P,colorMask:z}){const H=this.gl;let G=0;g&&(G|=H.COLOR_BUFFER_BIT,this.clearColor.set(g.toNonPremultipliedRenderColor(null)),this.colorMask.set(z||[!0,!0,!0,!0])),S!==void 0&&(G|=H.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(S),this.depthMask.set(!0)),P!==void 0&&(G|=H.STENCIL_BUFFER_BIT,this.clearStencil.set(P),this.stencilMask.set(255)),H.clear(G)}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,Hn.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 Vg;function Wr(M,g,S,P,z,H,G){const ee=M.context,ie=ee.gl,pe=M.transform,ye=[o.aH(pe.center.lng),o.aL(pe.center.lat)],De=S.layout.get("symbol-placement"),Ae=S.layout.get("text-variable-anchor"),Be=S.layout.get("icon-rotation-alignment")==="map",tt=S.layout.get("text-rotation-alignment")==="map",Ye=De!=="point",ut=[];let dt=0,jt=0;for(let Et=0;Et0){const gn=o.bb(),en=br;o.cz(gn,ds.placementInvProjMatrix,pe.glCoordMatrix),o.cz(gn,gn,ds.placementViewportMatrix),ut.push({circleArray:nr,circleOffset:jt,transform:en,invTransform:gn,projection:ds.getProjection()}),dt+=nr.length/4,jt=dt}if(!_r)continue;M.terrain&&M.terrain.setupElevationDraw(Vt,Cr);const on=Rs?[Lt.canonical.x,Lt.canonical.y,1<=0&&(Be[Tt.associatedIconIndex]={x:Zt,y:Is,z:Ns,angle:Ts})}else ri(Rt,De)}if(pe){Ae.clear();const jt=M.icon.placedSymbolArray;for(let Tt=0;Tt{let ya=[0,0,0];if(Pi){const al=M.style.directionalLight,fo=M.style.ambientLight;al&&fo&&(ya=vf(M.style,al,fo))}return ya},Fa=Pi=>{if(M.context.disableSymbolUBO)return;Pi.push("USE_PAINT_PROPERTIES_UBO");const ya=Math.floor(M.context.maxUniformBlockSize/4),al=Math.floor(ya/4);Pi.push(`MAX_UBO_SIZE_VEC4 ${al}u`)},ia=Pi=>{Lt.depthOcclusionForSymbolsAndCircles&&(S.hasOcclusionOpacityProperties||M.terrain)&&(Pi.push("DEPTH_D24"),Pi.push("DEPTH_OCCLUSION"))},ji=Pi=>{S.lut&&!Rt&&(S.lut.texture||(S.lut.texture=new o.dR(M.context,S.lut.image,[S.lut.image.height,S.lut.image.height,S.lut.image.height],Wt.gl.RGBA8)),Wt.activeTexture.set(Wt.gl.TEXTURE0+10),S.lut.texture&&S.lut.texture.bind(Wt.gl.LINEAR,Wt.gl.CLAMP_TO_EDGE),Pi.push("APPLY_LUT_ON_GPU"))},mo=()=>{const Pi=Vt&&S.layout.get("symbol-placement")!=="point",ya=[];ia(ya),ji(ya);const al=Pi||ma,fo=nr.elevationType==="road",lc=M.shadowRenderer,ni=fo&&Zt&&!!lc&&lc.enabled,bo=zn(ni),Pc=fo&&Zt&&!M.terrain?hs:lr,th=S.paint.get("icon-image-cross-fade");M.terrainRenderModeElevated()&&Zt&&ya.push("PITCH_WITH_MAP_TERRAIN"),on&&(ya.push("PROJECTION_GLOBE_VIEW"),al&&ya.push("PROJECTED_POS_ON_VIEWPORT")),th>0&&nr.hasAnySecondaryIcon&&ya.push("ICON_TRANSITION"),!nr.icon.zOffsetVertexBuffer||fo&&M.terrain||ya.push("Z_OFFSET"),dt===0&&jt===0&&Tt===0&&ft===1||ya.push("COLOR_ADJUSTMENT"),nr.sdfIcons&&ya.push("RENDER_SDF"),ni&&ya.push("RENDER_SHADOWS","NORMAL_OFFSET"),fo&&Zt&&!M.terrain&&nr.icon.orientationVertexBuffer&&ya.push("ELEVATED_ROADS"),Fa(ya);const Qc=Wt.disableSymbolUBO?nr.icon.programConfigurations.get(S.id):null,Jd=M.getOrCreateProgram("symbol",{config:Qc,defines:ya}),pp=_r.imageAtlasTexture?_r.imageAtlasTexture.size:[0,0],Xi=nr.iconSizeData,ex=o.bj(Xi,Lt.zoom),tx=Zt||!Lt.isOrthographic,To=md(en,_r.tileID.canonical,Zt,Vt,Lt,nr.getProjection(),nn),Po=Lm(en,_r.tileID.canonical,Zt,Vt,Lt,nr.getProjection(),nn),ao=nr.icon.uboBinder&&nr.icon.uboBinder.cachedHeader&&256&nr.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:ee,tc=M.translatePosMatrix(Po,_r,ao,pe,!0),Sh=M.translatePosMatrix(en,_r,ao,pe),Pl=al?uo:To,xp=Vt&&!Zt&&!Pi;let Nb=Cr;!Rs&&!Lt.mercatorFromTransition||Vt||(Nb=ec(Lt));const sj=on?Nb:Cr,rj=S.getColorAdjustmentMatrix(dt,jt,Tt,ft),bN=Rv(Xi.kind,ex,xp,Zt,M,Sh,Pl,tc,Kt,!1,pp,[0,0],0,br,gn,ss,aa,sj,nr.getProjection(),bo,Oa,rj,th,null),Uv=_r.imageAtlasTexture?_r.imageAtlasTexture:null,py=S.layout.get("icon-size").constantOr(0)!==1||nr.iconsNeedLinear,_N=nr.sdfIcons||M.options.rotating||M.options.zooming||py||tx?Et.LINEAR:Et.NEAREST,Tf=nr.sdfIcons&&S.paint.get("icon-halo-width").constantOr(1)!==0,kb=M.terrain&&Zt&&Pi?o.b7(o.bb(),To):uo;if(Pi&&nr.icon){const Sb=o.bu.getAtTileOffsetFunc(br,Lt.center.lat,Lt.worldSize,nr.getProjection()),Cb=_c(en,_r.tileID.canonical,Zt,Vt,Lt,nr.getProjection(),nn),BM=S.layout.get("icon-size-scale-range"),wN=o.aC(M.scaleFactor,BM[0],BM[1]);It(nr,en,M,!1,Cb,Po,Zt,Ye,Sb,br,wN)}return{program:Jd,buffers:nr.icon,uniformValues:bN,atlasTexture:Uv,atlasTextureIcon:null,atlasInterpolation:_N,atlasInterpolationIcon:null,isSDF:nr.sdfIcons,hasHalo:Tf,depthMode:Pc,tile:_r,renderWithShadows:ni,labelPlaneMatrixInv:kb}},ml=()=>{const Pi=ds&&S.layout.get("symbol-placement")!=="point",ya=[],al=Pi||Ts||ma,fo=nr.elevationType==="road",lc=M.shadowRenderer,ni=fo&&Is&&!!lc&&lc.enabled,bo=zn(ni),Pc=fo&&Is&&!M.terrain?hs:lr;M.terrainRenderModeElevated()&&Is&&ya.push("PITCH_WITH_MAP_TERRAIN"),on&&(ya.push("PROJECTION_GLOBE_VIEW"),al&&ya.push("PROJECTED_POS_ON_VIEWPORT")),!nr.text.zOffsetVertexBuffer||fo&&M.terrain||ya.push("Z_OFFSET"),nr.iconsInText&&ya.push("RENDER_TEXT_AND_SYMBOL"),ya.push("RENDER_SDF"),ni&&ya.push("RENDER_SHADOWS","NORMAL_OFFSET"),fo&&Is&&!M.terrain&&nr.text.orientationVertexBuffer&&ya.push("ELEVATED_ROADS"),ia(ya),Fa(ya);const th=Wt.disableSymbolUBO?nr.text.programConfigurations.get(S.id):null,Qc=M.getOrCreateProgram("symbol",{config:th,defines:ya});let Jd,pp=[0,0],Xi=null;const ex=nr.textSizeData;nr.iconsInText&&(pp=_r.imageAtlasTexture?_r.imageAtlasTexture.size:[0,0],Xi=_r.imageAtlasTexture?_r.imageAtlasTexture:null,Jd=Is||!Lt.isOrthographic||M.options.rotating||M.options.zooming||ex.kind==="composite"||ex.kind==="camera"?Et.LINEAR:Et.NEAREST);const tx=_r.glyphAtlasTexture?_r.glyphAtlasTexture.size:[0,0],To=S.layout.get("text-size-scale-range"),Po=o.aC(M.scaleFactor,To[0],To[1]),ao=o.bj(ex,Lt.zoom,Po),tc=md(en,_r.tileID.canonical,Is,ds,Lt,nr.getProjection(),nn),Sh=Lm(en,_r.tileID.canonical,Is,ds,Lt,nr.getProjection(),nn),Pl=nr.text.uboBinder&&nr.text.uboBinder.cachedHeader&&256&nr.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:ie,xp=M.translatePosMatrix(Sh,_r,Pl,ye,!0),Nb=M.translatePosMatrix(en,_r,Pl,ye),sj=al?uo:tc,rj=ds&&!Is&&!Pi;let bN=Cr;!Rs&&!Lt.mercatorFromTransition||ds||(bN=ec(Lt));const Uv=Rv(ex.kind,ao,rj,Is,M,Nb,sj,xp,Kt,!0,tx,pp,0,br,gn,ss,aa,on?bN:Cr,nr.getProjection(),bo,Oa,null,null,Po),py=_r.glyphAtlasTexture?_r.glyphAtlasTexture:null,_N=Et.LINEAR,Tf=S.paint.get("text-halo-width").constantOr(1)!==0,kb=M.terrain&&Is&&Pi?o.b7(o.bb(),tc):uo;if(Pi&&nr.text){const Sb=o.bu.getAtTileOffsetFunc(br,Lt.center.lat,Lt.worldSize,nr.getProjection()),Cb=_c(en,_r.tileID.canonical,Is,ds,Lt,nr.getProjection(),nn);It(nr,en,M,!0,Cb,Sh,Is,ut,Sb,br,Po)}return{program:Qc,buffers:nr.text,uniformValues:Uv,atlasTexture:py,atlasTextureIcon:Xi,atlasInterpolation:_N,atlasInterpolationIcon:Jd,isSDF:!0,hasHalo:Tf,depthMode:Pc,tile:_r,renderWithShadows:ni,labelPlaneMatrixInv:kb}},No=nr.icon.segments.get().length,Ii=nr.text.segments.get().length,Ta=No&&!G.onlyText?mo():null,Ea=Ii&&!G.onlyIcons?ml():null,ko=S.paint.get("icon-opacity").constantOr(1),bl=S.paint.get("text-opacity").constantOr(1);if(Ns&&nr.canOverlap){er=!0;const Pi=ko&&!G.onlyText?nr.icon.segments.get():[],ya=bl&&!G.onlyIcons?nr.text.segments.get():[];for(const al of Pi)qs.push({segments:new o.dy([al]),sortKey:al.sortKey,state:Ta});for(const al of ya)qs.push({segments:new o.dy([al]),sortKey:al.sortKey,state:Ea})}else G.onlyText||qs.push({segments:ko?nr.icon.segments:new o.dy([]),sortKey:0,state:Ta}),G.onlyIcons||qs.push({segments:bl?nr.text.segments:new o.dy([]),sortKey:0,state:Ea})}er&&qs.sort((br,_r)=>br.sortKey-_r.sortKey);for(const br of qs){const _r=br.state;if(_r)if(M.terrain?M.terrain.setupElevationDraw(_r.tile,_r.program,{useDepthForOcclusion:Lt.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:_r.labelPlaneMatrixInv}):M.setupDepthForOcclusion(Lt.depthOcclusionForSymbolsAndCircles,_r.program),Wt.activeTexture.set(Et.TEXTURE0),_r.atlasTexture&&_r.atlasTexture.bind(_r.atlasInterpolation,Et.CLAMP_TO_EDGE,!0),_r.atlasTextureIcon&&(Wt.activeTexture.set(Et.TEXTURE1),_r.atlasTextureIcon&&_r.atlasTextureIcon.bind(_r.atlasInterpolationIcon,Et.CLAMP_TO_EDGE,!0)),_r.renderWithShadows&&M.shadowRenderer.setupShadows(_r.tile.tileID.toUnwrapped(),_r.program,"vector-tile"),M.uploadCommonLightUniforms(M.context,_r.program),_r.hasHalo){const nr=_r.uniformValues;nr.u_is_halo=1,Hg(_r.buffers,br.segments,S,M,_r.program,_r.depthMode,z,H,nr,2),nr.u_is_halo=0}else{if(_r.isSDF){const nr=_r.uniformValues;_r.hasHalo&&(nr.u_is_halo=1,Hg(_r.buffers,br.segments,S,M,_r.program,_r.depthMode,z,H,nr,1)),nr.u_is_halo=0}Hg(_r.buffers,br.segments,S,M,_r.program,_r.depthMode,z,H,_r.uniformValues,1)}}}function Hg(M,g,S,P,z,H,G,ee,ie,pe){const ye=P.context,De=ye.gl,Ae=[M.dynamicLayoutVertexBuffer,M.opacityVertexBuffer,M.iconTransitioningVertexBuffer,M.globeExtVertexBuffer,M.zOffsetVertexBuffer,M.orientationVertexBuffer];M.featureIdBuffer&&Ae.push(M.featureIdBuffer);const Be=M.uboBinder?null:M.programConfigurations.get(S.id);if(M.uboBinder){M.uboBinder.layer=S;const ut=P.transform.zoom,dt=P.style.getBrightness?P.style.getBrightness():null,jt=M.uboBinder.getConstantUniformValues(ut,dt);ie.u_spp_fill_np_color=jt.fill_np_color,ie.u_spp_halo_np_color=jt.halo_np_color,ie.u_spp_opacity=jt.opacity,ie.u_spp_halo_width=jt.halo_width,ie.u_spp_halo_blur=jt.halo_blur,ie.u_spp_emissive_strength=jt.emissive_strength,ie.u_spp_occlusion_opacity=jt.occlusion_opacity,ie.u_spp_z_offset=jt.z_offset;const Tt=S.paint.get(M.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),ft=M.uboBinder.cachedHeader&&256&M.uboBinder.cachedHeader.dataDrivenMask&&Tt==="map"?P.transform.angle:0;ie.u_spp_translate_rotation=[Math.cos(ft),Math.sin(ft)]}const{batchIndices:tt,batchSegments:Ye}=M.getBatchGrouping(g);for(const ut of tt){const dt=Ye.get(ut);M.uboBinder&&M.uboBinder.bind(ye,z.program,ut),z.draw(P,De.TRIANGLES,H,G,ee,Cn.disabled,ie,S.id,M.layoutVertexBuffer,M.indexBuffer,dt,S.paint,P.transform.zoom,Be,Ae,pe)}}function Zc(M,g,S,P,z,H){const G=S.paint.get("line-width"),ee=S.paint.get("line-emissive-strength").isConstant(),ie=S.paint.get("line-emissive-strength").constantOr(0),pe=S.paint.get("line-occlusion-opacity"),ye=S.layout.get("line-elevation-reference"),De=S.layout.get("line-width-unit")==="meters",Ae=ye==="sea",Be=!(!M.terrain||!M.terrain.enabled),tt=M.context,Ye=tt.gl;if(S.hasElevatedBuckets&&M.transform.projection.name==="globe")return;const ut=S.layout.get("line-cross-slope"),dt=ut!==void 0,jt=ut<1,Tt=z||M.colorModeForDrapableLayerRenderPass(ee?ie:null),ft=M.terrain&&M.terrain.renderingToTexture||H,Kt=ft?1:o.o.devicePixelRatio,Rt=S.paint.get("line-dasharray"),Wt=Rt.constantOr(1),Et=S.layout.get("line-cap"),Lt=Rt.constantOr(null),Vt=Et.constantOr(null),ds=S.paint.get("line-pattern"),Zt=ds.constantOr(1),Is=S.paint.get("line-pattern-cross-fade"),Ns=ds.constantOr(null),er=S.paint.get("line-opacity").constantOr(1);let lr=!Zt&&er!==1||M.depthOcclusion&&pe>0&&pe<1;const hs=S.paint.get("line-gradient"),ss=Zt?"linePattern":"line",Ts=o.dU(S);let Rs;if(ft&&M.terrain&&M.terrain.clipOrMaskOverlapStencilType()&&(lr=!1),pe!==0&&M.depthOcclusion){const nr=S.paint._values["line-opacity"];nr&&nr.value&&nr.value.kind==="constant"?Rs=nr.value:o.w(`Occlusion opacity for layer ${S.id} is supported only when line-opacity isn't data-driven.`)}G.value.kind!=="constant"&&G.value.isLineProgressConstant===!1&&Ts.push("VARIABLE_LINE_WIDTH"),ft&&(M.emissiveMode!=="dual-source-blending"||ee?M.emissiveMode==="mrt-fallback"&&Ts.push("USE_MRT1"):Ts.push("DUAL_SOURCE_BLENDING"));const qs={},Cr=(nr,on,gn,en,nn,Gn)=>{for(const ma of nr){const aa=g.getTile(ma);if(Zt&&!aa.patternsLoaded())continue;const Oa=aa.getBucket(S);if(!Oa||Oa.elevationType!=="none"&&!nn||Oa.elevationType==="none"&&nn)continue;M.prepareDrawTile();const zn=[...on],Fa=M.shadowRenderer,ia=Oa.elevationType==="road"&&!!Fa&&Fa.enabled;let ji=[0,0,0];if(ia){const ni=M.style.directionalLight,bo=M.style.ambientLight;ni&&bo&&(ji=vf(M.style,ni,bo)),zn.push("RENDER_SHADOWS","NORMAL_OFFSET")}const mo=Oa.programConfigurations.get(S.id);let ml=!1;if(Ns&&aa.imageAtlas){const ni=o.dV.from(Ns),bo=ni.getPrimary().scaleSelf(Kt).toString(),Pc=aa.imageAtlas.patternPositions.get(bo),th=ni.getSecondary(),Qc=th?aa.imageAtlas.patternPositions.get(th.scaleSelf(Kt).toString()):null;ml=!!Pc&&!!Qc,Pc&&mo.setConstantPatternPositions(Pc,Qc)}Is>0&&(ml||mo.getPatternTransitionVertexBuffer("line-pattern"))&&zn.push("LINE_PATTERN_TRANSITION"),Oa.elevationGroundScaleVertexBuffer&&zn.push("ELEVATION_GROUND_SCALE");const No=M.isTileAffectedByFog(ma),Ii=M.getOrCreateProgram(ss,{config:mo,defines:zn,overrideFog:No});if(!Zt&&Lt&&Vt&&aa.lineAtlas){const ni=aa.lineAtlas.getDash(Lt,Vt);ni&&mo.setConstantPatternPositions(ni)}ia&&Fa.setupShadows(aa.tileID.toUnwrapped(),Ii,"vector-tile");let[Ta,Ea]=S.paint.get("line-trim-offset");(Vt==="round"||Vt==="square")&&Ta!==Ea&&(Ta===0&&(Ta-=1),Ea===1&&(Ea+=1));const ko=ft?ma.projMatrix:null,bl=De?1/Oa.tileToMeter/o.aA(aa,1,M.transform.zoom):1,Pi=De?1/Oa.tileToMeter/o.aA(aa,1,Math.floor(M.transform.zoom)):1,ya=Wt?S.paint._values["line-floorwidth"]:null;let al;if(ya&&ya.value.kind==="constant"){const ni=Oa.zoom;ni in qs||(qs[ni]=Math.max(.01,S.widthExpression().evaluate({zoom:ni}))),al=ya.value.value;const bo=Math.floor(M.transform.zoom);ya.value.value=qs[ni]*Math.pow(2,bo-aa.tileID.overscaledZ)}const fo=Zt?o.dW(M,aa,S,ko,Kt,bl,Pi,[Ta,Ea],ji,Is):o.dX(M,aa,S,ko,Oa.lineClipsArray.length,Kt,bl,Pi,[Ta,Ea],ji);if(hs){const ni=Oa.gradients[S.id];let bo=ni.texture;if(S.gradientVersion!==ni.version){let Pc=256;if(S.stepInterpolant){const th=g.getSource().maxzoom,Qc=ma.canonical.z===th?Math.ceil(1<{Rs!=null&&(Rs.value=er*pe),Ii.draw(M,Ye.TRIANGLES,gn,ni,Tt,Cn.disabled,fo,S.id,Oa.layoutVertexBuffer,Oa.indexBuffer,Oa.segments,S.paint,M.transform.zoom,mo,[Oa.layoutVertexBuffer2,Oa.patternVertexBuffer,Oa.zOffsetVertexBuffer,Oa.elevationGroundScaleVertexBuffer]),Rs!=null&&(Rs.value=er)};if(lr&&!nn){const ni=M.stencilModeForClipping(ma).ref;ni===0&&ft&&tt.clear({stencil:0});const bo={func:Ye.EQUAL,mask:255};fo.u_alpha_discard_threshold=.8,lc(new Xn(bo,ni,255,Ye.KEEP,Ye.KEEP,Ye.INVERT)),fo.u_alpha_discard_threshold=0,lc(new Xn(bo,ni,255,Ye.KEEP,Ye.KEEP,Ye.KEEP))}else fo.u_alpha_discard_threshold=lr&&nn&&Gn?.8:0,lc(nn?en:M.stencilModeForClipping(ma));al!==void 0&&(ya.value.value=al)}};let br=M.depthModeForSublayer(0,Jr.ReadOnly);const _r=new Jr(M.depthOcclusion?Ye.GREATER:Ye.LEQUAL,Jr.ReadOnly,M.depthRangeFor3D);if(S.hasNonElevatedBuckets){const nr=!ft&&M.terrain;pe!==0&&nr?o.w(`Occlusion opacity for layer ${S.id} is supported on terrain only if the layer has line-z-offset enabled.`):nr?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${S.id}.`):Cr(P,Ts,br,Xn.disabled,!1,!0)}if(S.hasElevatedBuckets){ye==="hd-road-markup"?Be||(br=_r,Ts.push("ELEVATED_ROADS")):(Ts.push("ELEVATED"),br=_r,dt&&Ts.push(jt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Ae&&Ts.push("ELEVATION_REFERENCE_SEA"));const nr=lr?M.stencilModeFor3D():Xn.disabled;M.forceTerrainMode=!0,Cr(P,Ts,br,nr,!0,!0),lr&&Cr(P,Ts,br,nr,!0,!1),M.forceTerrainMode=!1}lr&&(M.resetStencilClippingMasks(),ft&&tt.clear({stencil:0})),pe===0||M.depthOcclusion||ft||M.layersWithOcclusionOpacity.push(M.currentLayer)}const Nf={additive:{clearColor:new o.aq(0,0,0,0),colorMode:Hn.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:Hn.multiply,compositeUniformValue:0}};function Gg(M,g){const S=1<=cp?1:Be.pitch/cp))),2*tt}(M.transform),pe=M.transform.getFreeCameraOptions().position,ye="elevatedStructuresDepthReconstruct",De=M.getOrCreateProgram(ye,{defines:["DEPTH_RECONSTRUCTION"]}),Ae=M.getOrCreateProgram(ye);for(const Be of P){const tt=g.getTile(Be),Ye=tt.getBucket(S);if(!Ye)continue;const ut=Ye.elevatedStructures;if(!ut)continue;const dt=Ye.elevationBufferData.heightRange,jt=Gg(Be.toUnwrapped(),pe),Tt=M.translatePosMatrix(Be.projMatrix,tt,S.paint.get("fill-translate"),S.paint.get("fill-translate-anchor"));let ft,Kt,Rt,Wt;if(z==="initialize"){if(!dt||dt.min>=1||ut.depthSegments.segments[0].primitiveLength===0)continue;ft=Dv(Tt,jt,ie,1,0),Kt=G,Rt=ut.depthSegments,Wt=De}else if(z==="reset"){if(!dt||dt.min>=0||ut.maskSegments.segments[0].primitiveLength===0)continue;ft=Dv(Tt,jt,0,0,1),Kt=ee,Rt=ut.maskSegments,Wt=De}else if(z==="geometry"){if(ut.depthSegments.segments[0].primitiveLength===0)continue;ft=Dv(Tt,jt,ie,1,0),Kt=G,Rt=ut.depthSegments,Wt=Ae}Wt.draw(M,H.TRIANGLES,Kt,Xn.disabled,Hn.disabled,Cn.disabled,ft,S.id,ut.vertexBuffer,ut.indexBuffer,Rt,S.paint,M.transform.zoom)}}function Ov(M,g,S,P){const{painter:z,sourceCache:H,layer:G,coords:ee,colorMode:ie,elevationType:pe,terrainEnabled:ye,pass:De}=M,Ae=z.context.gl,Be=G.paint.get("fill-pattern"),tt=G.paint.get("fill-pattern-cross-fade"),Ye=Be.constantOr(null);let ut=pe;pe!=="road"||g&&!ye||(ut="none");const dt=ut==="road",jt=M.painter.shadowRenderer,Tt=dt&&!!jt&&jt.enabled,ft=new Jr(z.context.gl.LEQUAL,Jr.ReadOnly,z.depthRangeFor3D);let Kt=[0,0,0];if(Tt){const Lt=z.style.directionalLight,Vt=z.style.ambientLight;Lt&&Vt&&(Kt=vf(z.style,Lt,Vt))}const Rt=Be&&Be.constantOr(1),Wt=z.terrain&&z.terrain.renderingToTexture,Et=(Lt,Vt)=>{let ds,Zt,Is,Ns,er;Vt?(ds=Rt&&!G.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",Is=Ae.LINES):(ds=Rt?"fillPattern":"fill",Is=Ae.TRIANGLES);for(const lr of ee){const hs=H.getTile(lr);if(Rt&&!hs.patternsLoaded())continue;const ss=hs.getBucket(G);if(!ss)continue;const Ts=g?ss.elevationBufferData:ss.bufferData;if(Ts.isEmpty())continue;z.prepareDrawTile();const Rs=Ts.programConfigurations.get(G.id),qs=z.isTileAffectedByFog(lr),Cr=[],br=[];dt&&(Cr.push("ELEVATED_ROADS"),br.push(Ts.elevatedLayoutVertexBuffer)),Tt&&Cr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Wt&&S&&Cr.push("USE_MRT1"),Rt&&(z.context.activeTexture.set(Ae.TEXTURE0),hs.imageAtlasTexture&&hs.imageAtlasTexture.bind(Ae.LINEAR,Ae.CLAMP_TO_EDGE),Rs.updatePaintBuffers());let _r=!1;if(Ye&&hs.imageAtlas){const nn=hs.imageAtlas,Gn=o.dV.from(Ye),ma=Gn.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),aa=Gn.getSecondary(),Oa=nn.patternPositions.get(ma),zn=aa?nn.patternPositions.get(aa.scaleSelf(o.o.devicePixelRatio).toString()):null;_r=!!Oa&&!!zn,Oa&&Rs.setConstantPatternPositions(Oa,zn)}tt>0&&(_r||Rs.getPatternTransitionVertexBuffer("fill-pattern"))&&Cr.push("FILL_PATTERN_TRANSITION");const nr=z.getOrCreateProgram(ds,{config:Rs,overrideFog:qs,defines:Cr}),on=z.translatePosMatrix(lr.projMatrix,hs,G.paint.get("fill-translate"),G.paint.get("fill-translate-anchor"));Tt&&jt.setupShadows(hs.tileID.toUnwrapped(),nr,"vector-tile");const gn=G.paint.get("fill-emissive-strength");if(Vt){Ns=Ts.lineIndexBuffer,er=Ts.lineSegments;const nn=z.terrain&&z.terrain.renderingToTexture?z.terrain.drapeBufferSize:[Ae.drawingBufferWidth,Ae.drawingBufferHeight];Zt=ds==="fillOutlinePattern"&&Rt?fb(on,gn,z,hs,nn,Kt,tt):M4(on,gn,nn,Kt)}else Ns=Ts.indexBuffer,er=Ts.triangleSegments,Zt=Rt?mb(on,gn,z,hs,Kt,tt):Bg(on,gn,Kt);z.uploadCommonUniforms(z.context,nr,lr.toUnwrapped());let en=Lt;(pe==="road"&&!ye||pe==="offset")&&(en=ft),nr.draw(z,Is,en,P||z.stencilModeForClipping(lr),ie,Cn.disabled,Zt,G.id,Ts.layoutVertexBuffer,Ns,er,G.paint,z.transform.zoom,Rs,br)}};z.renderPass===De&&Et(z.depthModeForSublayer(1,z.renderPass==="opaque"?Jr.ReadWrite:Jr.ReadOnly),!1),ut==="none"&&z.renderPass==="translucent"&&G.paint.get("fill-antialias")&&Et(z.depthModeForSublayer(G.getPaintProperty("fill-outline-color")?2:0,Jr.ReadOnly),!0)}function Xp(M,g,S,P,z,H,G,ee){S.resetLayerRenderingStats(M);const ie=M.context,pe=ie.gl,ye=M.transform,De=S.paint.get("fill-extrusion-pattern"),Ae=S.paint.get("fill-extrusion-pattern-cross-fade"),Be=De.constantOr(null),tt=De.constantOr(1),Ye=S.paint.get("fill-extrusion-opacity"),ut=M.style.enable3dLights(),dt=S.paint.get(ut&&!tt?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),jt=[S.paint.get("fill-extrusion-ambient-occlusion-intensity"),dt],Tt=S.layout.get("fill-extrusion-edge-radius"),ft=Tt>0&&!S.paint.get("fill-extrusion-rounded-roof"),Kt=ft?0:Tt,Rt=ye.projection.name==="globe"?o.e1():0,Wt=ye.projection.name==="globe",Et=Wt?o.al(ye.zoom):0,Lt=[o.aH(ye.center.lng),o.aL(ye.center.lat)],Vt=S.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",ds=S.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Vt?null:S.lut).toArray01().slice(0,3),Zt=S.paint.get("fill-extrusion-flood-light-intensity"),Is=S.paint.get("fill-extrusion-vertical-scale"),Ns=S.paint.get("fill-extrusion-line-width").constantOr(1)!==0,er=S.paint.get("fill-extrusion-height-alignment"),lr=S.paint.get("fill-extrusion-base-alignment"),hs=wc(M,S.paint.get("fill-extrusion-cutoff-fade-range")),ss=S.paint.get("fill-extrusion-front-cutoff"),Ts=yb(ye.pitch,ss,!!M.terrain),Rs=Ts[2]<1;Rs&&(M.maxFrontCutoffRawStart=Math.max(M.maxFrontCutoffRawStart,ss[0]));const qs=[];let Cr;Wt&&qs.push("PROJECTION_GLOBE_VIEW"),jt[0]>0&&qs.push("FAUX_AO"),ft&&qs.push("ZERO_ROOF_RADIUS"),ee&&qs.push("HAS_CENTROID"),Zt>0&&qs.push("FLOOD_LIGHT"),hs.shouldRenderCutoff&&qs.push("RENDER_CUTOFF"),Rs&&qs.push("RENDER_FRONT_CUTOFF"),Ns&&qs.push("RENDER_WALL_MODE");const br=M.renderPass==="shadow",_r=M.shadowRenderer,nr=br&&!!_r,on=br?Cn.disabled:Cn.backCCW;M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!0);let gn=[0,0,0];if(_r){const Gn=M.style.directionalLight,ma=M.style.ambientLight;Gn&&ma&&(gn=vf(M.style,Gn,ma)),br||(qs.push("RENDER_SHADOWS"),_r.useNormalOffset&&qs.push("NORMAL_OFFSET")),Cr=qs.concat(["SHADOWS_SINGLE_CASCADE"])}const en=nr?"fillExtrusionDepth":tt?"fillExtrusionPattern":"fillExtrusion",nn=S.getLayerRenderingStats();for(const Gn of P){const ma=g.getTile(Gn),aa=ma.getBucket(S);if(!aa||aa.projection.name!==ye.projection.name)continue;let Oa=!1;_r&&(Oa=_r.getMaxCascadeForTile(Gn.toUnwrapped())===0);const zn=M.isTileAffectedByFog(Gn),Fa=aa.programConfigurations.get(S.id);let ia=!1;if(Be&&ma.imageAtlas){const Ea=ma.imageAtlas,ko=o.dV.from(Be),bl=ko.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),Pi=ko.getSecondary(),ya=Ea.patternPositions.get(bl),al=Pi?Ea.patternPositions.get(Pi.scaleSelf(o.o.devicePixelRatio).toString()):null;ia=!!ya&&!!al,ya&&Fa.setConstantPatternPositions(ya,al)}Ae>0&&(ia||Fa.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&qs.push("FILL_EXTRUSION_PATTERN_TRANSITION");const ji=M.getOrCreateProgram(en,{config:Fa,defines:Oa?Cr:qs,overrideFog:zn});if(M.terrain&&M.terrain.setupElevationDraw(ma,ji,{useMeterToDem:!0}),!aa.centroidVertexBuffer){const Ea=ji.getAttributeLocation(pe,"a_centroid_pos");Ea!==-1&&pe.vertexAttribI4ui(Ea,0,0,0,0)}!br&&_r&&_r.setupShadows(ma.tileID.toUnwrapped(),ji,"vector-tile"),tt&&(M.context.activeTexture.set(pe.TEXTURE0),ma.imageAtlasTexture&&ma.imageAtlasTexture.bind(pe.LINEAR,pe.CLAMP_TO_EDGE),Fa.updatePaintBuffers());const mo=S.paint.get("fill-extrusion-vertical-gradient"),ml=1/aa.tileToMeter;let No;if(br&&_r){if(Qp(ma.tileID,aa.maxHeight,M))continue;const Ea=_r.calculateShadowPassMatrixFromTile(ma.tileID.toUnwrapped());No=_D(Ea,Kt,ml,Is,er,lr)}else{const Ea=M.translatePosMatrix(Gn.expandedProjMatrix,ma,S.paint.get("fill-extrusion-translate"),S.paint.get("fill-extrusion-translate-anchor")),ko=ye.projection.createInversionMatrix(ye,Gn.canonical);No=tt?Pa(Ea,M,mo,Ye,jt,Kt,ml,Gn,ma,Rt,er,lr,Et,Lt,ko,ds,Is,Ae):Qu(Ea,M,mo,Ye,jt,Kt,ml,Gn,Rt,er,lr,Et,Lt,ko,ds,Is,Zt,gn,Ts)}M.uploadCommonUniforms(ie,ji,Gn.toUnwrapped(),null,hs);let Ii=aa.segments;if(ye.projection.name==="mercator"&&!br&&(Ii=aa.getVisibleSegments(ma.tileID,M.terrain,M.transform.getFrustum(0)),!Ii.get().length))continue;if(nn)if(br)for(const Ea of Ii.get())nn.numRenderedVerticesInShadowPass+=Ea.primitiveLength;else for(const Ea of Ii.get())nn.numRenderedVerticesInTransparentPass+=Ea.primitiveLength;const Ta=[];(M.terrain||ee)&&Ta.push(aa.centroidVertexBuffer),Wt&&Ta.push(aa.layoutVertexExtBuffer),Ns&&Ta.push(aa.wallVertexBuffer),ji.draw(M,ie.gl.TRIANGLES,z,H,G,on,No,S.id,aa.layoutVertexBuffer,aa.indexBuffer,Ii,S.paint,M.transform.zoom,Fa,Ta)}M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!1)}class Nh{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function yb(M,g,S){if(!(g[2]<1)||S)return[0,0,1];const P=180*M/Math.PI;if(P<15)return[-.5,g[1],g[2]];const z=Math.min(1,Math.max(0,(P-15)/5)),H=z*z*(3-2*z);return[-.5*(1-H)+g[0]*H,g[1],g[2]]}function mp(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be,tt,Ye,ut,dt,jt,Tt,ft){const Kt=g.context,Rt=Kt.gl,Wt=g.transform,Et=g.transform.zoom,Lt=[],Vt=M.translate,ds=M.translateAnchor,Zt=M.edgeRadius,Is=wc(g,M.cutoffFadeRange);ye==="clear"?(Lt.push("CLEAR_SUBPASS"),Tt&&(Lt.push("CLEAR_FROM_TEXTURE"),Kt.activeTexture.set(Rt.TEXTURE0),Tt.bind(Rt.LINEAR,Rt.CLAMP_TO_EDGE))):ye==="sdf"?Lt.push("SDF_SUBPASS"):ye==="emissive"&&(Lt.push("USE_MRT1"),Kt.activeTexture.set(Rt.TEXTURE0),Tt.bind(Rt.LINEAR,Rt.CLAMP_TO_EDGE)),dt&&Lt.push("HAS_CENTROID"),Is.shouldRenderCutoff&&Lt.push("RENDER_CUTOFF");const Ns=(er,lr,hs,ss,Ts)=>{let Rs=Lt;lr.groundRadiusBuffer!=null&&(Rs=Lt.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const qs=lr.programConfigurations.get(P.id),Cr=g.isTileAffectedByFog(er),br=g.getOrCreateProgram("fillExtrusionGroundEffect",{config:qs,defines:Rs,overrideFog:Cr}),_r=((on,gn,en,nn,Gn,ma,aa,Oa,zn,Fa,ia)=>({u_matrix:gn,u_opacity:en,u_ao_pass:nn?1:0,u_meter_to_tile:Gn,u_ao:ma,u_flood_light_intensity:aa,u_flood_light_color:Oa,u_attenuation:zn,u_edge_radius:Fa,u_fb:0,u_fb_size:ia,u_dynamic_offset:1}))(0,ss,De,pe,Ts,[Ae,Be*Ts],tt,Ye,ut,Et>=17?0:Zt*Ts,Tt?Tt.size[0]:0),nr=[];dt&&nr.push(lr.hiddenByLandmarkVertexBuffer),lr.groundRadiusBuffer!=null&&nr.push(lr.groundRadiusBuffer),g.uploadCommonUniforms(Kt,br,er.toUnwrapped(),null,Is),br.draw(g,Kt.gl.TRIANGLES,H,G,ee,ie,_r,P.id,lr.vertexBuffer,lr.indexBuffer,hs,P.paint,Et,qs,nr)};for(const er of z){const lr=S.getTile(er),hs=lr.getBucket(P);if(!hs||hs.projection.name!==Wt.projection.name||!hs.groundEffect||hs.groundEffect&&!hs.groundEffect.hasData())continue;const ss=hs.groundEffect,Ts=1/hs.tileToMeter;{const Rs=g.translatePosMatrix(er.projMatrix,lr,Vt,ds),qs=ss.getDefaultSegment();Ns(er,ss,qs,Rs,Ts)}if(jt)for(let Rs=0;Rs<4;Rs++){const qs=o.d$[Rs](er),Cr=S.getTile(qs);if(!Cr)continue;const br=Cr.getBucket(P);if(!br||br.projection.name!==Wt.projection.name||!br.groundEffect||br.groundEffect&&!br.groundEffect.hasData())continue;const _r=br.groundEffect;let nr,on;Rs===0?(nr=[-o.an,0,0],on=1):Rs===1?(nr=[o.an,0,0],on=0):Rs===2?(nr=[0,-o.an,0],on=3):(nr=[0,o.an,0],on=2);const gn=_r.regionSegments[on];if(!gn)continue;const en=new Float32Array(16);o.bx(en,er.projMatrix,nr),Ns(er,_r,gn,g.translatePosMatrix(en,lr,Vt,ds),Ts)}}}function Bx(M,g,S,P,z,H,G){P.centroidVertexArray.length===0&&P.createCentroidsBuffer();const ee=H?H.findDEMTileFor(S):null;if(!(ee&&ee.dem||G))return;H&&ee&&ee.dem&&P.selfDEMTileTimestamp!==ee.dem._timestamp&&(P.borderDoneWithNeighborZ=[-1,-1,-1,-1],P.selfDEMTileTimestamp=ee.dem._timestamp);const ie=(dt,jt)=>{(dt.flags|jt.flags)&o.e3?(dt.flags|=o.e3,jt.flags|=o.e3):(dt.flags&=~o.e3,jt.flags&=~o.e3)},pe=dt=>new o.P(Math.ceil((dt+o.e4)*o.e5),0),ye=(dt,jt,Tt)=>{const ft=Math.ceil((dt+o.e4)*o.e5),Kt=Math.floor(Math.max(0,Math.min(o.an-1,Tt))/4);return new o.P(ft,Kt<<5|(3&jt)<<3|7)},De=dt=>{const jt=g.getSource().minzoom,Tt=Kt=>{const Rt=g.getTileByID(Kt);if(Rt&&Rt.hasData())return Rt.getBucket(z)},ft=[0,-1,1];for(const Kt of ft){if(dt.overscaledZ+Kt(Ae[0]=Math.min(dt.min.y,jt.min.y),Ae[1]=Math.max(dt.max.y,jt.max.y),Ae[2]=o.an-jt.min.x>dt.max.x?jt.min.x-o.an:dt.max.x,Ae),tt=(dt,jt)=>(Ae[0]=Math.min(dt.min.x,jt.min.x),Ae[1]=Math.max(dt.max.x,jt.max.x),Ae[2]=o.an-jt.min.y>dt.max.y?jt.min.y-o.an:dt.max.y,Ae),Ye=[(dt,jt)=>Be(dt,jt),(dt,jt)=>Be(jt,dt),(dt,jt)=>tt(dt,jt),(dt,jt)=>tt(jt,dt)],ut=(dt,jt,Tt,ft,Kt,Rt,Wt)=>{if(!H)return 0;const Et=[[Rt?Tt:dt,Rt?dt:Tt,0],[Rt?Tt:jt,Rt?jt:Tt,0]],Lt=Wt<0?o.an+Wt:Wt,Vt=[Rt?Lt:(dt+jt)/2,Rt?(dt+jt)/2:Lt,0];return Tt===0&&Wt<0||Tt!==0&&Wt>0?H.getForTilePoints(Kt,[Vt],!0,ft):Et.push(Vt),H.getForTilePoints(S,Et,!0,ee),Math.max(Et[0][2],Et[1][2],Vt[2])/H.exaggeration()};for(let dt=0;dt<4;dt++){const jt=P.borderFeatureIndices[dt];if(jt.length===0)continue;const Tt=o.d$[dt](S),ft=De(Tt);if(!(ft&&ft instanceof o.e0))continue;const Kt=H?H.findDEMTileFor(Tt):null;if(!(Kt&&Kt.dem||G)||(H&&Kt&&Kt.dem&&P.borderDEMTileTimestamp[dt]!==Kt.dem._timestamp&&(P.borderDoneWithNeighborZ[dt]=-1,P.borderDEMTileTimestamp[dt]=Kt.dem._timestamp),P.borderDoneWithNeighborZ[dt]===ft.canonical.z))continue;ft.centroidVertexArray.length===0&&ft.createCentroidsBuffer();const Rt=(dt<2?1:5)-dt,Wt=ft.borderDoneWithNeighborZ[Rt]!==P.canonical.z,Et=ft.borderFeatureIndices[Rt];let Lt=0;if(P.canonical.z!==ft.canonical.z){for(const Is of jt)P.showCentroid(P.featuresOnBorder[Is]);if(Wt)for(const Is of Et)ft.showCentroid(ft.featuresOnBorder[Is]);P.borderDoneWithNeighborZ[dt]=ft.canonical.z,ft.borderDoneWithNeighborZ[Rt]=P.canonical.z;continue}const Vt=new Map,ds=new Set,Zt=new Set;for(let Is=0;Is1||hs.intersectsCount()>1;{let br=0;if(Kt&&Kt.dem&&!Cr){const _r=Ye[dt](er,ss),nr=dt%2?o.an-1:0;br=ut(_r[0],Math.min(o.an-1,_r[1]),nr,Kt,Tt,dt<2,_r[2])}er.centroidXY=ye(br,dt,qs),ss.centroidXY=ye(br,Rt,qs)}if(P.writeCentroidToBuffer(er),ft.writeCentroidToBuffer(ss),Ns.buildingId!==void 0){for(const br of P.centroidData)br.buildingId===Ns.buildingId&&br!==er&&(br.centroidXY=er.centroidXY,P.writeCentroidToBuffer(br));for(const br of ft.centroidData)br.buildingId===Ns.buildingId&&br!==ss&&(br.centroidXY=ss.centroidXY,ft.writeCentroidToBuffer(br))}}for(const Is of jt){if(ds.has(Is))continue;const Ns=P.featuresOnBorder[Is],er=P.centroidData[Ns.centroidDataIndex],lr=Ns.borders[dt];let hs;for(;Ltlr[0]+3||ss[0]>lr[0]-3)break;ft.showCentroid(hs),Lt++}if(hs&&Ltlr[1]-3||(Ts++,++Lt===Et.length))break;hs=ft.featuresOnBorder[Et[Lt]]}for(;ss=Et.length){P.showCentroid(Ns);continue}hs=ft.featuresOnBorder[Et[ss]];let Rs=!1;if(Ts>=1){const br=hs.borders[Rt];Math.abs(lr[0]-br[0])<3&&Math.abs(lr[1]-br[1])<3&&(Ts=1,Rs=!0,Lt=ss+1)}else if(Ts===0){P.showCentroid(Ns);continue}const qs=ft.centroidData[hs.centroidDataIndex];G&&Rs&&ie(er,qs);const Cr=Ns.intersectsCount()>1||hs.intersectsCount()>1;if(Ts>1)Lt=ss,er.centroidXY=qs.centroidXY=new o.P(0,0);else if(Kt&&Kt.dem&&!Cr){const br=Ye[dt](er,qs),_r=dt%2?o.an-1:0,nr=ut(br[0],Math.min(o.an-1,br[1]),_r,Kt,Tt,dt<2,br[2]);er.centroidXY=qs.centroidXY=pe(nr)}else Cr?er.centroidXY=qs.centroidXY=new o.P(0,0):(er.centroidXY=P.encodeBorderCentroid(Ns),qs.centroidXY=ft.encodeBorderCentroid(hs));P.writeCentroidToBuffer(er),ft.writeCentroidToBuffer(qs)}else P.showCentroid(Ns)}P.borderDoneWithNeighborZ[dt]=ft.canonical.z,ft.borderDoneWithNeighborZ[Rt]=P.canonical.z}(P.needsCentroidUpdate||!P.centroidVertexBuffer&&P.centroidVertexArray.length!==0)&&P.uploadCentroid(M)}const Fv=[1,0,0],Hw=[0,1,0],Gw=[0,0,1];function Qp(M,g,S){const P=S.transform,z=S.shadowRenderer;if(!z)return!0;const H=M.toUnwrapped(),G=P.tileSize*z._cascades[S.currentShadowCascade].scale;let ee=g;if(P.elevation){const tt=P.elevation.getMinMaxForTile(M);tt&&(ee+=tt.max)}const ie=P.scaleZoom(G);ee/=o.e2(P.center.lat,ie);const pe=[...z.shadowDirection];pe[2]=-pe[2];const ye=z.computeSimplifiedTileShadowVolume(H,ee,G,pe);if(!ye)return!1;const De=[Fv,Hw,Gw,pe,[pe[0],0,pe[2]],[0,pe[1],pe[2]]],Ae=o.cl.fromInvProjectionMatrix(P.invProjMatrix,P.worldSize,ie,P.projection.name!=="globe"),Be=z.getCurrentCascadeFrustum();return Ae.intersectsPrecise(ye.vertices,ye.planes,De)===0||Be.intersectsPrecise(ye.vertices,ye.planes,De)===0}function uy(M){const{painter:g,source:S,layer:P,coords:z}=M;let H=M.defines;const G=g.context,ee=g.renderPass==="shadow",ie=g.renderPass==="light-beam",pe=g.shadowRenderer,ye=o.e2(g.transform.center.lat,g.transform.zoom),De=wc(g,P.paint.get("building-cutoff-fade-range"));De.shouldRenderCutoff&&(H=H.concat("RENDER_CUTOFF"));const Ae=P.paint.get("building-front-cutoff"),Be=Ae[2]<1&&!g.terrain,tt=yb(g.transform.pitch,Ae,!!g.terrain);Be&&(H=H.concat("RENDER_FRONT_CUTOFF"),g.maxFrontCutoffRawStart=Math.max(g.maxFrontCutoffRawStart,Ae[0])),M.floodLightIntensity>0&&(H=H.concat("FLOOD_LIGHT"));for(const Ye of z){const ut=S.getTile(Ye),dt=ut.getBucket(P);if(!dt)continue;pe&&pe.getMaxCascadeForTile(Ye.toUnwrapped())===0&&(H=H.concat("SHADOWS_SINGLE_CASCADE"));const jt=dt.programConfigurations.get(P.id);let Tt,ft,Kt,Rt=g.translatePosMatrix(Ye.expandedProjMatrix,ut,[0,0],"map");if(Rt=o.cC(o.bb(),Rt,[1,1,M.verticalScale]),ee&&pe){if(Qp(ut.tileID,dt.maxHeight*ye,g))continue;let Et=pe.calculateShadowPassMatrixFromTile(ut.tileID.toUnwrapped());Et=o.cC(o.bb(),Et,[1,1,M.verticalScale]),Kt=xb(Et),Tt=ft=g.getOrCreateProgram("buildingDepth",{config:jt,defines:H,overrideFog:!1})}else if(ie)Tt=ft=g.getOrCreateProgram("buildingBloom",{config:jt,defines:H,overrideFog:!1}),Kt=$w(Rt);else{const Et=g.transform.calculatePosMatrix(Ye.toUnwrapped(),g.transform.worldSize);o.cC(Et,Et,[1,1,M.verticalScale]);const Lt=o.bb();o.cC(Lt,Et,[1,-1,1/ye]),o.b7(Lt,Lt),o.e6(Lt,Lt);const Vt=g.transform.getFreeCameraOptions().position,ds=1<{if(ie){const Vt=Et.entranceBloom;Lt.draw(g,G.gl.TRIANGLES,M.depthMode,Xn.disabled,M.blendMode,Cn.disabled,Kt,P.id,Vt.layoutVertexBuffer,Vt.indexBuffer,Vt.segmentsBucket,P.paint,g.transform.zoom,jt,[Vt.layoutAttenuationBuffer,Vt.layoutColorBuffer])}else{const Vt=Et.segmentsBucket;let ds=[Et.layoutNormalBuffer,Et.layoutCentroidBuffer,Et.layoutColorBuffer,Et.layoutFloodLightDataBuffer];Et.layoutFacadePaintBuffer&&(ds=ds.concat([Et.layoutFacadeDataBuffer,Et.layoutFacadeVerticalRangeBuffer,Et.layoutFacadePaintBuffer])),Lt.draw(g,G.gl.TRIANGLES,M.depthMode,Xn.disabled,M.blendMode,ee?Cn.disabled:Cn.backCW,Kt,P.id,Et.layoutVertexBuffer,Et.indexBuffer,Vt,P.paint,g.transform.zoom,jt,ds)}};g.uploadCommonUniforms(G,ft,Ye.toUnwrapped(),null,De),dt.buildingWithoutFacade&&Wt(dt.buildingWithoutFacade,ft),dt.buildingWithFacade&&(Tt!==ft&&g.uploadCommonUniforms(G,Tt,Ye.toUnwrapped(),null,De),Wt(dt.buildingWithFacade,Tt))}}function $x(M,g,S,P,z,H,G,ee,ie,pe,ye,De,Ae,Be){const tt=M.context.gl,Ye=M.depthModeForSublayer(1,Jr.ReadOnly,tt.LEQUAL,!0),ut=.1*(1-(dt=ye))+3*dt;var dt;const jt=M._showOverdrawInspector,Tt=De,ft=new Nh;jt||mp(ft,M,g,S,P,Ye,new Xn({func:tt.ALWAYS,mask:255},255,255,tt.KEEP,tt.KEEP,tt.REPLACE),new Hn([tt.ONE,tt.ONE,tt.ONE,tt.ONE],o.aq.transparent,[!1,!1,!1,!0],tt.MIN),Cn.disabled,z,"sdf",H,G,ee,ie,pe,ut,Tt,!1,void 0);{const Kt=jt?Xn.disabled:new Xn({func:tt.EQUAL,mask:255},255,255,tt.KEEP,tt.DECR,tt.DECR),Rt=jt?M.colorModeForRenderPass():new Hn([tt.ONE_MINUS_DST_ALPHA,tt.DST_ALPHA,tt.ONE,tt.ONE],o.aq.transparent,[!0,!0,!0,!0]);mp(ft,M,g,S,P,Ye,Kt,Rt,Cn.disabled,z,"color",H,G,ee,ie,pe,ut,Tt,!1,void 0)}}function vb(M){return[M[0]*o.e7,M[1]*o.e7,M[2]*o.e7,0]}function hy(M,g,S,P,z,H,G,ee,ie){const pe=P.getSource(),ye=S.globeSharedBuffers;if(!ye)return;let De,Ae,Be;if(g&&(De=P.getTile(g)),pe instanceof o.aV?(Ae=pe.texture,Be=o.dw(0,0,S.transform)):De&&g&&(Ae=De.texture,Be=o.dw(g.canonical.z,g.canonical.x,S.transform)),!Ae||!Be)return;M||(Be=o.cC(o.bb(),Be,[1,-1,1]));const tt=S.context,Ye=tt.gl,ut=z.paint.get("raster-resampling")==="nearest"?Ye.NEAREST:Ye.LINEAR,dt=S.colorModeForDrapableLayerRenderPass(H),jt=G.defines;jt.push("GLOBE_POLES");const Tt=new Jr(Ye.LEQUAL,Jr.ReadWrite,S.depthRangeFor3D),ft=Float32Array.from(S.transform.expandedFarZProjMatrix),Kt=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));S.terrain&&S.terrain.prepareDrawTile(),tt.activeTexture.set(Ye.TEXTURE0),Ae.bind(ut,Ye.CLAMP_TO_EDGE),tt.activeTexture.set(Ye.TEXTURE1),Ae.bind(ut,Ye.CLAMP_TO_EDGE),"useMipmap"in Ae&&tt.extTextureFilterAnisotropic&&S.transform.pitch>20&&Ye.texParameterf(Ye.TEXTURE_2D,tt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,tt.extTextureFilterAnisotropicMax);const[Rt,Wt,Et,Lt]=g?ye.getPoleBuffers(g.canonical.z,!1):ye.getPoleBuffers(0,!0),Vt=z.paint.get("raster-elevation");let ds;M?(ds=Rt,S.renderDefaultNorthPole=Vt!==0):(ds=Wt,S.renderDefaultSouthPole=Vt!==0);const Zt=vb(G.mix),Is=((er,lr,hs,ss,Ts,Rs,qs,Cr,br,_r,nr,on,gn,en)=>Wp(er,lr,hs,ss,new Float32Array(16),new Float32Array(9),[0,0],Ts,[0,0],[0,0,0,0],1,{opacity:1,mix:0},qs,[0,0],br,2,nr,on,gn,1,0,en))(S,ft,Kt,Be,o.al(S.transform.zoom),0,z,0,Vt,0,Zt,G.offset,G.range,H),Ns=S.getOrCreateProgram("raster",{defines:jt});S.uploadCommonUniforms(tt,Ns,null),Ns.draw(S,Ye.TRIANGLES,Tt,ie,dt,ee,Is,z.id,ds,Et,Lt)}function Ww(M){if(M.isOrthographic)return[0,0,0,0];const g=M._nearZ,S=M.projection.farthestPixelDistance(M),P=S-g,z=.2*M.height,H=g+z;return[g,S,(H-z-g)/P,(H-g)/P]}function Kw(M,g,S,P){if(M)return g instanceof Vh&&M instanceof vh?g.getTextureDescriptor(M,S,!0):{texture:M.texture,mix:vb(P.mix),offset:P.offset,buffer:0,tileSize:1}}var bb=o.e8([{name:"a_index",type:"Int16",components:1}]);class Ju{constructor(g,S,P,z){const H={width:P[0],height:P[1],data:null},G=g.gl;this.targetColorTexture=new o.T(g,H,G.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(g,H,G.RGBA8,{useMipmap:!1}),this.context=g,this.updateParticleTexture(S,z),this.lastInvalidatedAt=0}updateParticleTexture(g,S){if(this.particleTextureDimension===S.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const P=this.context.gl,z=S.width*S.height;this.particleTexture0=new o.T(this.context,S,P.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,S,P.RGBA8,{premultiply:!1,useMipmap:!1});const H=new o.e9;H.reserve(z);for(let G=0;G0){const Zt=o.ec(S.canonical,ie),Is=o.ed(Zt);Ae=o.aD(new Float32Array(16),ie.globeMatrix,Is),o.aD(Ae,ie.projMatrix,Ae)}const Be=o.bb();Be[12]+=2*z/(o.o.devicePixelRatio*ie.width),Be[13]+=2*H/(o.o.devicePixelRatio*ie.height),o.aD(Ae,Be,Ae);const tt=M.getOrCreateProgram("debug",{defines:De}),Ye=g.getTileByID(S.key);M.terrain&&M.terrain.setupElevationDraw(Ye,tt);const ut=Jr.disabled,dt=Xn.disabled,jt=M.colorModeForRenderPass(),Tt="$debug";ee.activeTexture.set(pe.TEXTURE0),M.emptyTexture.bind(pe.LINEAR,pe.CLAMP_TO_EDGE),ye?Ye._makeGlobeTileDebugBuffers(M.context,ie):Ye._makeDebugTileBoundsBuffers(M.context,ie.projection);const ft=Ye._tileDebugBuffer||M.debugBuffer,Kt=Ye._tileDebugIndexBuffer||M.debugIndexBuffer,Rt=Ye._tileDebugSegments||M.debugSegments;if(tt.draw(M,pe.LINE_STRIP,ut,dt,jt,Cn.disabled,Xh(Ae,P.toPremultipliedRenderColor(null)),Tt,ft,Kt,Rt,null,null,null,[Ye._globeTileDebugBorderBuffer]),G){const Zt=Ye.latestRawTileData,Is=Math.floor((Zt&&Zt.byteLength||0)/1024);let Ns=S.canonical.toString();S.overscaledZ!==S.canonical.z&&(Ns+=` => ${S.overscaledZ}`),Ns+=` ${Ye.state}`,Ns+=` ${Is}kb`,function(er,lr){er.initDebugOverlayCanvas();const hs=er.debugOverlayCanvas,ss=er.context.gl,Ts=er.debugOverlayCanvas.getContext("2d");Ts.clearRect(0,0,hs.width,hs.height),Ts.shadowColor="white",Ts.shadowBlur=2,Ts.lineWidth=1.5,Ts.strokeStyle="white",Ts.textBaseline="top",Ts.font="bold 36px Open Sans, sans-serif",Ts.fillText(lr,5,5),Ts.strokeText(lr,5,5),er.debugOverlayTexture.update(hs),er.debugOverlayTexture.bind(ss.LINEAR,ss.CLAMP_TO_EDGE)}(M,Ns)}const Wt=g.getTile(S).tileSize,Et=512/Math.min(Wt,512)*(S.overscaledZ/ie.zoom)*.5,Lt=Ye._tileDebugTextBuffer||M.debugBuffer,Vt=Ye._tileDebugTextIndexBuffer||M.quadTriangleIndexBuffer,ds=Ye._tileDebugTextSegments||M.debugSegments;tt.draw(M,pe.TRIANGLES,ut,dt,Hn.alphaBlended,Cn.disabled,Xh(Ae,o.aq.transparent.toPremultipliedRenderColor(null),Et),Tt,Lt,Vt,ds,null,null,null,[Ye._globeTileDebugTextBuffer])}function R4(M,g,S,P){qx(M,0,g+S/2,M.transform.width,S,P)}function Yw(M,g,S,P){qx(M,g-S/2,0,S,M.transform.height,P)}function qx(M,g,S,P,z,H){const G=M.context,ee=G.gl;ee.enable(ee.SCISSOR_TEST),ee.scissor(g*o.o.devicePixelRatio,S*o.o.devicePixelRatio,P*o.o.devicePixelRatio,z*o.o.devicePixelRatio),G.clear({color:H}),ee.disable(ee.SCISSOR_TEST)}const CM=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Qh}=CM;function fp(M,g,S,P){M.emplaceBack(g,S,P)}class Md{constructor(g){this.vertexArray=new o.ee,this.indices=new o.dC,fp(this.vertexArray,-1,-1,1),fp(this.vertexArray,1,-1,1),fp(this.vertexArray,-1,1,1),fp(this.vertexArray,1,1,1),fp(this.vertexArray,-1,-1,-1),fp(this.vertexArray,1,-1,-1),fp(this.vertexArray,-1,1,-1),fp(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,Qh),this.indexBuffer=g.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function kf(M,g,S,P,z,H){const G=M.context.gl,ee=g.paint.get("sky-atmosphere-color"),ie=g.paint.get("sky-atmosphere-halo-color"),pe=g.paint.get("sky-atmosphere-sun-intensity"),ye=((De,Ae,Be,tt,Ye)=>({u_matrix_3f:De,u_sun_direction:Ae,u_sun_intensity:Be,u_color_tint_r:[tt.r,tt.g,tt.b,tt.a],u_color_tint_m:[Ye.r,Ye.g,Ye.b,Ye.a],u_luminance:5e-5}))(o.eg(o.dE(),P),z,pe,ee.toPremultipliedRenderColor(null),ie.toPremultipliedRenderColor(null));G.framebufferTexture2D(G.FRAMEBUFFER,G.COLOR_ATTACHMENT0,G.TEXTURE_CUBE_MAP_POSITIVE_X+H,g.skyboxTexture,0),S.draw(M,G.TRIANGLES,Jr.disabled,Xn.disabled,Hn.unblended,Cn.frontCW,ye,"skyboxCapture",g.skyboxGeometry.vertexBuffer,g.skyboxGeometry.indexBuffer,g.skyboxGeometry.segment)}const TM=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class uN{constructor(g){const S=new o.eh;S.emplaceBack(-1,1,1,0,0),S.emplaceBack(1,1,1,1,0),S.emplaceBack(1,-1,1,1,1),S.emplaceBack(-1,-1,1,0,1);const P=new o.dC;P.emplaceBack(0,1,2),P.emplaceBack(2,3,0),this.vertexBuffer=g.createVertexBuffer(S,TM.members),this.indexBuffer=g.createIndexBuffer(P),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const hN=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 Kg{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class EM{constructor(g){this.colorModeAlphaBlendedWriteRGB=new Hn([1,kl,1,kl],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new Hn([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new Kg,this.updateNeeded=!0}update(g){const S=g.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new uN(S);const P=this.params.sizeRange,z=this.params.intensityRange,H=function(ye){const De=o.em(30),Ae=[];for(let Be=0;Be{const Et=H.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Wt&&Et.push("ALPHA_PASS");const Lt=g.getOrCreateProgram("globeAtmosphere",{defines:Et}),Vt=((Zt,Is,Ns,er,lr,hs,ss,Ts,Rs,qs,Cr,br)=>({u_frustum_tl:Zt,u_frustum_tr:Is,u_frustum_br:Ns,u_frustum_bl:er,u_horizon:lr,u_transition:hs,u_fadeout_range:ss,u_atmosphere_fog_color:Ts.toArray01(),u_high_color:Rs.toArray01(),u_space_color:qs.toArray01(),u_temporal_offset:Cr,u_horizon_angle:br}))(H.frustumCorners.TL,H.frustumCorners.TR,H.frustumCorners.BR,H.frustumCorners.BL,H.frustumCorners.horizon,ee,ut,ye,Ae,tt,jt,Kt);g.uploadCommonUniforms(P,Lt);const ds=this.atmosphereBuffer;ds&&Lt.draw(g,z.TRIANGLES,G,Xn.disabled,Wt?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,Cn.backCW,Vt,Wt?"atmosphere_glow_alpha":"atmosphere_glow",ds.vertexBuffer,ds.indexBuffer,ds.segments)};Rt(!1),Rt(!0)}drawStars(g,S){const P=o.aC(S.properties.get("star-intensity"),0,1);if(P===0)return;const z=g.context,H=z.gl,G=g.transform,ee=g.getOrCreateProgram("stars"),ie=o.bL([]);o.bN(ie,ie,-G._pitch),o.bM(ie,ie,-G.angle),o.bN(ie,ie,o.ap(G._center.lat)),o.ek(ie,ie,-o.ap(G._center.lng));const pe=o.bR(new Float32Array(16),ie),ye=o.aD([],G.starsProjMatrix,pe),De=o.eg([],pe),Ae=o.el([],De),Be=[0,1,0];o.dG(Be,Be,Ae),o.bJ(Be,Be,this.params.sizeMultiplier);const tt=[1,0,0];o.dG(tt,tt,Ae),o.bJ(tt,tt,this.params.sizeMultiplier);const Ye=(ut=Be,dt=tt,jt=P,{u_matrix:Float32Array.from(ye),u_up:ut,u_right:dt,u_intensity_multiplier:jt});var ut,dt,jt;g.uploadCommonUniforms(z,ee),this.starsVx&&this.starsIdx&&ee.draw(g,H.TRIANGLES,Jr.disabled,Xn.disabled,this.colorModeAlphaBlendedWriteRGB,Cn.disabled,Ye,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Jh{constructor(){this.visibleTiles=[]}updateBorders(g,S){const P=[],z=[],H=g._getRenderableCoordinates(!1,!0);for(const ie of H){const pe=g.getTile(ie);if(!pe.hasData())continue;const ye=pe.getBucket(S);ye&&(ye.isEmpty()||(P.push(ie.key),z.push({bucket:ye,tileID:ie.canonical})))}let G=P.length!==this.visibleTiles.length;if(!G){P.sort();for(let ie=0;ieie.tileID.z-pe.tileID.z||ie.tileID.x-pe.tileID.x||ie.tileID.y-pe.tileID.y);for(const ie of z){const pe=new Array,ye=new Array,De=ie.bucket;for(const Ae of De.featuresOnBorder)ee.has(Ae.featureId)?ye.push(Ae.footprintIndex):(ee.add(Ae.featureId),pe.push(Ae.footprintIndex));De.updateFootprintHiddenFlags(pe,o.en,!1),De.updateFootprintHiddenFlags(ye,o.en,!0)}}}function O4(M,g){const S=[...M],P=g.cameraWorldSizeForFog/g.worldSize,z=o.b9([]);return o.cC(z,z,[P,P,1]),o.aD(S,z,S),o.aD(S,g.worldToFogMatrix,S),S}function ja(M,g,S,P,z){const H=S.material,G=P.context,{baseColorTexture:ee,metallicRoughnessTexture:ie}=H.pbrMetallicRoughness,{normalTexture:pe,occlusionTexture:ye,emissionTexture:De}=H;function Ae(tt,Ye,ut){if(tt&&(M.push(Ye),G.activeTexture.set(G.gl.TEXTURE0+ut),tt.gfxTexture)){const{minFilter:dt,magFilter:jt,wrapS:Tt,wrapT:ft}=tt.sampler;tt.gfxTexture.bindExtraParam(dt,jt,Tt,ft)}}Ae(ee,"HAS_TEXTURE_u_baseColorTexture",5),Ae(ie,"HAS_TEXTURE_u_metallicRoughnessTexture",6),Ae(pe,"HAS_TEXTURE_u_normalTexture",7),Ae(ye,"HAS_TEXTURE_u_occlusionTexture",8),Ae(De,"HAS_TEXTURE_u_emissionTexture",9),z&&(z.texture||(z.texture=new o.dR(P.context,z.image,[z.image.height,z.image.height,z.image.height],G.gl.RGBA8)),G.activeTexture.set(G.gl.TEXTURE0+10),z.texture&&z.texture.bind(G.gl.LINEAR,G.gl.CLAMP_TO_EDGE),M.push("APPLY_LUT_ON_GPU")),S.texcoordBuffer&&(M.push("HAS_ATTRIBUTE_a_uv_2f"),g.push(S.texcoordBuffer)),S.colorBuffer&&(M.push(S.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),g.push(S.colorBuffer)),S.normalBuffer&&(M.push("HAS_ATTRIBUTE_a_normal_3f"),g.push(S.normalBuffer)),S.pbrBuffer&&(M.push("HAS_ATTRIBUTE_a_pbr"),M.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),g.push(S.pbrBuffer)),H.alphaMode!=="OPAQUE"&&H.alphaMode!=="MASK"||M.push("UNPREMULT_TEXTURE_IN_SHADER"),H.defined||M.push("DIFFUSE_SHADED");const Be=P.shadowRenderer;Be&&(M.push("RENDER_SHADOWS"),Be.useNormalOffset&&M.push("NORMAL_OFFSET"))}function _b(M,g,S,P,z,H){const G=M.modelOpacity,ee=g.context,ie=new Jr(g.context.gl.LEQUAL,M.isLightMesh?Jr.ReadOnly:Jr.ReadWrite,g.depthRangeFor3D),pe=g.transform,ye=M.mesh,De=ye.material,Ae=De.pbrMetallicRoughness,Be=g.style.fog;let tt;tt=g.transform.projection.zAxisUnit==="pixels"?[...M.nodeModelMatrix]:o.aD([],P.zScaleMatrix,M.nodeModelMatrix),o.aD(tt,P.negCameraPosMatrix,tt);const Ye=o.b7([],tt);o.e6(Ye,Ye);const ut=S.paint.get("model-color-use-theme").constantOr("default")==="none",dt=S.paint.get("model-emissive-strength").constantOr(0),jt=Zp(new Float32Array(M.worldViewProjection),new Float32Array(tt),new Float32Array(Ye),null,g,G,Ae.baseColorFactor,De.emissiveFactor,Ae.metallicFactor,Ae.roughnessFactor,De,dt,S,void 0,void 0,M.materialOverride,M.modelColor),Tt={defines:[]},ft=[],Kt=g.shadowRenderer;Kt&&(Kt.useNormalOffset=!1),ja(Tt.defines,ft,ye,g,ut?null:S.lut);let Rt=null;if(Be){const Lt=O4(M.nodeModelMatrix,g.transform);if(Rt=new Float32Array(Lt),pe.projection.name!=="globe"){const Vt=ye.aabb.min,ds=ye.aabb.max,[Zt,Is]=Be.getOpacityForBounds(Lt,Vt[0],Vt[1],ds[0],ds[1]);Tt.overrideFog=Zt>=wn||Is>=wn}}const Wt=wc(g,S.paint.get("model-cutoff-fade-range"));Wt.shouldRenderCutoff&&Tt.defines.push("RENDER_CUTOFF");const Et=g.getOrCreateProgram("model",Tt);g.uploadCommonUniforms(ee,Et,null,Rt,Wt),g.renderPass!=="shadow"&&Kt&&Kt.setupShadowsFromMatrix(M.nodeModelMatrix,Et),Et.draw(g,ee.gl.TRIANGLES,ie,z,H,ye.material.doubleSided?Cn.disabled:Cn.backCCW,jt,S.id,ye.vertexBuffer,ye.indexBuffer,ye.segments,S.paint,g.transform.zoom,void 0,ft)}function Zw(M,g){return M.style._importedAsBasemap?"basemap":g.scope}function mN(M,g,S,P,z,H,G,ee,ie,pe){const ye=M.transform,De=!!g.isGeometryBloom&&g.isGeometryBloom;if(De&&M.renderPass==="shadow")return;const Ae=ye.projection.name==="globe"?o.ev(S,ye):[...S];o.aD(Ae,Ae,g.globalMatrix);const Be=o.aD([],P,Ae);if(g.meshes)for(const tt of g.meshes){const Ye=ee.get(tt.material.name);if(Ye&&Ye.opacity<=0)continue;if(tt.material.alphaMode!=="BLEND"){G.push({mesh:tt,depth:0,modelIndex:z,worldViewProjection:Be,nodeModelMatrix:Ae,isLightMesh:De,materialOverride:Ye,modelOpacity:ie,modelColor:pe,node:g,modelMatrix:S});continue}const ut=o.ah([],tt.centroid,Be);!ye.isOrthographic&&ut[2]<=0||H.push({mesh:tt,depth:ut[2],modelIndex:z,worldViewProjection:Be,nodeModelMatrix:Ae,isLightMesh:De,materialOverride:Ye,modelOpacity:ie,modelColor:pe,node:g,modelMatrix:S})}if(g.children)for(const tt of g.children)mN(M,tt,S,P,z,H,G,ee,ie,pe)}function wb(M,g,S,P){const z=S.shadowRenderer;if(!z)return;const H=z.getShadowPassDepthMode(),G=z.calculateShadowPassMatrixFromMatrix(g),ee=qw(G);S.getOrCreateProgram("modelDepth").draw(S,S.context.gl.TRIANGLES,H,Xn.disabled,Hn.disabled,Cn.disabled,ee,P.id,M.vertexBuffer,M.indexBuffer,M.segments,P.paint,S.transform.zoom,void 0,void 0)}function fN(M,g,S,P){const z=function(ye,De){if(De.footprintDebugMesh)return De.footprintDebugMesh;if(!De.footprint)return null;const Ae=ye.context,Be=De.footprint.vertices,tt=De.footprint.indices,Ye=new o.dB;Ye.reserve(Be.length);for(const Vt of Be)Ye.emplaceBack(Vt.x,Vt.y);const ut=new o.dC;ut.reserve(tt.length);for(let Vt=0;Vt0){const Ae=H.terrain,Be=Ae.findDEMTileFor(ee);Be&&Be.dem?ie=o.ex.create(Ae,ee,Be):De=0}if(De===0&&(G.terrainElevationMin=0,G.terrainElevationMax=0),De===G.validForExaggeration&&(De===0||ie&&ie._demTile&&ie._demTile.tileID===G.validForDEMTile.id&&ie._dem._timestamp===G.validForDEMTile.timestamp))return!1;for(const Ae in G.instancesPerModel){const Be=G.instancesPerModel[Ae];for(let tt=0;ttpe&&(pe=Be.max)}const ye=o.aC(P.x,H,G)-P.x,De=o.aC(P.y,ee,ie)-P.y,Ae=o.bU(pe,g.center.lat)-P.z;return g._zoomFromMercatorZ(Math.sqrt(ye*ye+De*De+Ae*Ae))}function Io(M,g,S,P,z,H,G){const ee=M.context,ie=M.renderPass==="shadow",pe=M.shadowRenderer,ye=ie&&pe?pe.getShadowPassDepthMode():new Jr(ee.gl.LEQUAL,Jr.ReadWrite,M.depthRangeFor3D),De=M.isTileAffectedByFog(H),Ae=M.transform.projection.name==="globe";if(S.meshes)for(const Be of S.meshes){const tt=Ae?[]:["MODEL_POSITION_ON_GPU"],Ye=[];let ut,dt,jt;const Tt=!Ae&&P.instancedDataArray.length>20;Tt&&tt.push("INSTANCED_ARRAYS");const ft=wc(M,g.paint.get("model-cutoff-fade-range"));if(ft.shouldRenderCutoff&&tt.push("RENDER_CUTOFF"),ie&&pe)ut=M.getOrCreateProgram("modelDepth",{defines:tt}),dt=qw(G.shadowTileMatrix,G.shadowTileMatrix,Float32Array.from(S.globalMatrix)),jt=Hn.disabled;else{ja(tt,Ye,Be,M,g.paint.get("model-color-use-theme").constantOr("default")==="none"?null:g.lut),ut=M.getOrCreateProgram("model",{defines:tt,overrideFog:De});const Rt=Be.material,Wt=Rt.pbrMetallicRoughness,Et=g.paint.get("model-opacity").constantOr(1),Lt=g.paint.get("model-emissive-strength").constantOr(0);dt=Zp(H.expandedProjMatrix,Float32Array.from(S.globalMatrix),new Float32Array(16),null,M,Et,Wt.baseColorFactor,Rt.emissiveFactor,Wt.metallicFactor,Wt.roughnessFactor,Rt,Lt,g,z),pe&&(G.shadowUniformsInitialized?ut.setShadowUniformValues(ee,pe.getShadowUniformValues()):(pe.setupShadows(H.toUnwrapped(),ut,"model-tile"),G.shadowUniformsInitialized=!0)),jt=ft.shouldRenderCutoff||Et<1||Rt.alphaMode!=="OPAQUE"?Hn.alphaBlended:Hn.unblended}M.uploadCommonUniforms(ee,ut,H.toUnwrapped(),null,ft);const Kt=Be.material.doubleSided?Cn.disabled:Cn.backCCW;if(Tt)Ye.push(P.instancedDataBuffer),ut.draw(M,ee.gl.TRIANGLES,ye,Xn.disabled,jt,Kt,dt,g.id,Be.vertexBuffer,Be.indexBuffer,Be.segments,g.paint,M.transform.zoom,void 0,Ye,P.instancedDataArray.length);else{const Rt=ie?"u_instance":"u_normal_matrix";for(let Wt=0;Wtie[1]?G:ie,H[0]=S.max[0],G=o.aE(o.bE(),H,z),ee=G[1]ie[1]?G:ie,H[1]=S.min[1],G=o.aE(o.bE(),H,z),ee=G[1]ie[1]?G:ie;const pe=o.aC(P[0],0,1),ye=100*g.pixelsPerMeter*o.aC(P[1],0,1),De=o.aC(P[2],0,1),Ae=o.ey(o.bE(),ee,ie,pe),Be=Math.tan(.5*g.fovX),tt=-Ae[2]*Be;if(ye===0)return Ae[1]<-Math.abs(tt)?De:1;const Ye=(-Math.abs(tt)-Ae[1])/ye,ut=(jt,Tt,ft)=>(1-ft)*jt+ft*Tt,dt=o.aC(ut(1,De,Ye),De,1);return ut(1,dt,o.aC((g.pitch-20)/20,0,1))}class xN{}class F4{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(g,S,P){{const De=this._storage.get(S.id);if(De)return De.lastUsedFrameIdx=g,De.buf}const z=P.gl,H=z.getBufferParameter(z.ELEMENT_ARRAY_BUFFER,z.BUFFER_SIZE),G=new ArrayBuffer(H),ee=new Int16Array(G);z.getBufferSubData(z.ELEMENT_ARRAY_BUFFER,0,new Int16Array(G));const ie=new o.eA;for(let De=0;De30&&(P.buf.destroy(),this._storage.delete(S))}destroy(){for(const[g,S]of this._storage)S.buf.destroy(),this._storage.delete(g)}}class z4{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Bv=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 B4{constructor(g){this.revealStart=11,this.revealRange=2}}const gN=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class AM{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(g,S){const P=g.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const G=new o.eB,ee=new o.dC;G.emplaceBack(-1,-1),G.emplaceBack(1,-1),G.emplaceBack(1,1),G.emplaceBack(-1,1),ee.emplaceBack(0,1,2),ee.emplaceBack(0,2,3),this.vignetteVx=g.context.createVertexBuffer(G,gN.members),this.vignetteIdx=g.context.createIndexBuffer(ee)}const z=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){g.uploadCommonUniforms(g.context,P);const G={u_vignetteShape:(H={vignetteShape:[S.start,S.range,Math.pow(10,S.fadePower)],vignetteColor:[S.color.r,S.color.g,S.color.b,S.color.a*S.strength]}).vignetteShape,u_vignetteColor:H.vignetteColor};P.draw(g,g.context.gl.TRIANGLES,Jr.disabled,Xn.disabled,Hn.alphaBlended,Cn.disabled,G,"vignette",this.vignetteVx,this.vignetteIdx,z)}var H}}class yN{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(g,S){const P=g.getFreeCameraOptions().position,z=P.toAltitude(),H=P.toLngLat(),G=o.ap(H.lng),ee=o.ap(H.lat),ie=g.pixelsPerMeter/S,pe=G*o.eD,ye=o.eD*Math.log(Math.tan(Math.PI/4+ee/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 De=-this._offsetYPrev+ye,Ae=-this._elevationPrev+z;this._accumulatedOffsetX+=(-this._offsetXPrev+pe)*ie,this._accumulatedOffsetY+=De*ie,this._accumulatedElevation+=Ae*ie,this._offsetXPrev=pe,this._offsetYPrev=ye,this._elevationPrev=z}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Y(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),S=[];for(let P=0;P 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 S=g.context;if(!this.particlesVx){const P=J(this.particlesCount),z=new o.eE,H=new o.dC;let G=0;const ee=o.em(1323123451230);for(let ie=0;ieP)return;const z=be(0,1,S.revealStart,S.revealStart+S.revealRange,P);if(!this.particlesVx||!this.particlesIdx)return;const H=structuredClone(this._params);let G=[-H.direction.x,H.direction.y,-100];o.ay(G,G);const ee=structuredClone(this._vignetteParams);ee.strength*=z,H.overrideStyleParameters||(H.intensity=g.style.rain.state.density,H.timeFactor=g.style.rain.state.intensity,H.color=structuredClone(g.style.rain.state.color),G=structuredClone(g.style.rain.state.direction),H.screenThinning.intensity=g.style.rain.state.centerThinning,H.dropletSizeX=g.style.rain.state.dropletSize[0],H.dropletSizeYScale=g.style.rain.state.dropletSize[1]/g.style.rain.state.dropletSize[0],H.distortionStrength=100*g.style.rain.state.distortionStrength,ee.strength=1,ee.color=structuredClone(g.style.rain.state.vignetteColor));const ie=this.updateOnRender(g,H.timeFactor),pe=g.context,ye=pe.gl,De=g.transform;this.screenTexture&&this.screenTexture.size[0]===g.width&&this.screenTexture.size[1]===g.height||(this.screenTexture=new o.T(pe,{width:g.width,height:g.height,data:null},ye.RGBA8)),H.distortionStrength>0&&(pe.activeTexture.set(ye.TEXTURE0),this.screenTexture.bind(ye.LINEAR,ye.CLAMP_TO_EDGE),ye.copyTexSubImage2D(ye.TEXTURE_2D,0,0,0,0,0,g.width,g.height));const Ae=g.getOrCreateProgram("rainParticle");g.uploadCommonUniforms(pe,Ae),pe.activeTexture.set(ye.TEXTURE0),this.screenTexture.bind(ye.LINEAR,ye.CLAMP_TO_EDGE);const Be=[H.color.r,H.color.g,H.color.b,H.color.a],tt=(Ye,ut)=>{const dt=Y(this._movement.getPosition(),Ye),jt=H.dropletSizeX,Tt=H.dropletSizeX*H.dropletSizeYScale,ft=g.width/2,Kt=g.height/2,Rt=be(0,H.screenThinning.start,0,1,H.screenThinning.intensity),Wt=be(.001,H.screenThinning.range,0,1,H.screenThinning.intensity),Et=be(0,H.screenThinning.particleOffset,0,1,H.screenThinning.intensity),Lt=(Vt={modelview:ie.modelviewMatrix,projection:ie.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:dt,velocityConeAperture:H.velocityConeAperture,velocity:H.velocity,boxSize:Ye,rainDropletSize:[jt,Tt],distortionStrength:H.distortionStrength,rainDirection:G,color:Be,screenSize:[De.width,De.height],thinningCenterPos:[ft,Kt],thinningShape:[Rt,Wt,Math.pow(10,H.screenThinning.fadePower)],thinningAffectedRatio:H.screenThinning.affectedRatio,thinningParticleOffset:Et,shapeDirectionalPower:H.shapeDirPower,shapeNormalPower:H.shapeNormalPower,mode:ut?0:1},{u_modelview:Float32Array.from(Vt.modelview),u_projection:Float32Array.from(Vt.projection),u_time:Vt.time,u_cam_pos:Vt.camPos,u_texScreen:0,u_velocityConeAperture:Vt.velocityConeAperture,u_velocity:Vt.velocity,u_boxSize:Vt.boxSize,u_rainDropletSize:Vt.rainDropletSize,u_distortionStrength:Vt.distortionStrength,u_rainDirection:Vt.rainDirection,u_color:Vt.color,u_screenSize:Vt.screenSize,u_thinningCenterPos:Vt.thinningCenterPos,u_thinningShape:Vt.thinningShape,u_thinningAffectedRatio:Vt.thinningAffectedRatio,u_thinningParticleOffset:Vt.thinningParticleOffset,u_shapeDirectionalPower:Vt.shapeDirectionalPower,u_shapeNormalPower:Vt.shapeNormalPower,u_mode:Vt.mode});var Vt;const ds=Math.round(H.intensity*this.particlesCount),Zt=o.dy.simpleSegment(0,0,4*ds,2*ds);Ae.draw(g,ye.TRIANGLES,Jr.disabled,Xn.disabled,Hn.alphaBlended,Cn.disabled,Lt,"rain_particles",this.particlesVx,this.particlesIdx,Zt)};H.distortionStrength>0&&tt(H.boxSize,!0),tt(H.boxSize,!1),this._vignette.draw(g,ee)}}const yt=o.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_snowParticleData",components:4},{type:"Float32",name:"a_snowParticleDataHorizontalOscillation",components:2}]);class ns extends Ue{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 B4("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 S=g.context;if(!this.particlesVx){const P=J(this.particlesCount),z=new o.eF,H=new o.dC;let G=0;const ee=o.em(1323123451230);for(let ie=0;ieG)return;const ee=be(0,1,H.revealStart,H.revealStart+H.revealRange,G);z.strength*=ee,S.overrideStyleParameters||(S.intensity=g.style.snow.state.density,S.timeFactor=g.style.snow.state.intensity,S.color=structuredClone(g.style.snow.state.color),P=structuredClone(g.style.snow.state.direction),S.screenThinning.intensity=g.style.snow.state.centerThinning,S.billboardSize=2.79*g.style.snow.state.flakeSize,z.strength=1,z.color=structuredClone(g.style.snow.state.vignetteColor));const ie=this.updateOnRender(g,S.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const pe=g.context,ye=pe.gl,De=g.transform,Ae=g.getOrCreateProgram("snowParticle");g.uploadCommonUniforms(pe,Ae),((Be,tt,Ye)=>{const ut=Y(this._movement.getPosition(),Be),dt=De.width/2,jt=De.height/2,Tt=be(0,Ye.screenThinning.start,0,1,Ye.screenThinning.intensity),ft=be(.001,Ye.screenThinning.range,0,1,Ye.screenThinning.intensity),Kt=be(0,Ye.screenThinning.particleOffset,0,1,Ye.screenThinning.intensity),Rt=(Wt={modelview:ie.modelviewMatrix,projection:ie.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:ut,velocityConeAperture:Ye.velocityConeAperture,velocity:Ye.velocity,horizontalOscillationRadius:Ye.horizontalOscillationRadius,horizontalOscillationRate:Ye.horizontalOscillationRate,boxSize:Be,billboardSize:1*Ye.billboardSize,simpleShapeParameters:[Ye.shapeFadeStart,Ye.shapeFadePower],screenSize:[De.width,De.height],thinningCenterPos:[dt,jt],thinningShape:[Tt,ft,Math.pow(10,Ye.screenThinning.fadePower)],thinningAffectedRatio:Ye.screenThinning.affectedRatio,thinningParticleOffset:Kt,color:[Ye.color.r,Ye.color.g,Ye.color.b,Ye.color.a],direction:P},{u_modelview:Float32Array.from(Wt.modelview),u_projection:Float32Array.from(Wt.projection),u_time:Wt.time,u_cam_pos:Wt.camPos,u_velocityConeAperture:Wt.velocityConeAperture,u_velocity:Wt.velocity,u_horizontalOscillationRadius:Wt.horizontalOscillationRadius,u_horizontalOscillationRate:Wt.horizontalOscillationRate,u_boxSize:Wt.boxSize,u_billboardSize:Wt.billboardSize,u_simpleShapeParameters:Wt.simpleShapeParameters,u_screenSize:Wt.screenSize,u_thinningCenterPos:Wt.thinningCenterPos,u_thinningShape:Wt.thinningShape,u_thinningAffectedRatio:Wt.thinningAffectedRatio,u_thinningParticleOffset:Wt.thinningParticleOffset,u_particleColor:Wt.color,u_direction:Wt.direction});var Wt;const Et=Math.round(Ye.intensity*this.particlesCount),Lt=o.dy.simpleSegment(0,0,4*Et,2*Et);this.particlesVx&&this.particlesIdx&&Ae.draw(g,ye.TRIANGLES,Jr.disabled,Xn.disabled,Hn.alphaBlended,Cn.disabled,Rt,"snow_particles",this.particlesVx,this.particlesIdx,Lt)})(S.boxSize,0,S),this._vignette.draw(g,z)}}const ur={symbol:function(M,g,S,P,z){if(M.renderPass!=="translucent")return;const H=Xn.disabled,G=M.colorModeForRenderPass(),ee=S.layout.get("text-variable-anchor"),ie=S.layout.get("text-size-scale-range"),pe=o.aC(M.scaleFactor,ie[0],ie[1]);ee&&function(Ae,Be,tt,Ye,ut,dt,jt,Tt){const ft=Be.transform,Kt=ut==="map",Rt=dt==="map";for(const Wt of Ae){const Et=Ye.getTile(Wt),Lt=Et.getBucket(tt);if(!Lt||!Lt.text||!Lt.text.segments.get().length)continue;const Vt=o.bj(Lt.textSizeData,ft.zoom,Tt),ds=Pm(Wt,Lt.getProjection(),ft),Zt=ft.calculatePixelsToTileUnitsMatrix(Et),Is=md(ds,Et.tileID.canonical,Rt,Kt,ft,Lt.getProjection(),Zt),Ns=Lt.hasIconTextFit()&&Lt.hasIconData();Vt&&Eu(Lt,Kt,Rt,jt,ft,Is,Wt,Math.pow(2,ft.zoom-Et.tileID.overscaledZ),Vt,Ns)}}(P,M,S,g,S.layout.get("text-rotation-alignment"),S.layout.get("text-pitch-alignment"),z,pe);const ye=S.paint.get("icon-opacity").constantOr(1)!==0,De=S.paint.get("text-opacity").constantOr(1)!==0;S.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(ye||De)?jh(M,g,S,P,H,G):(ye&&jh(M,g,S,P,H,G,{onlyIcons:!0}),De&&jh(M,g,S,P,H,G,{onlyText:!0})),g.map.showCollisionBoxes&&(Wr(M,g,S,P,S.paint.get("text-translate"),S.paint.get("text-translate-anchor"),!0),Wr(M,g,S,P,S.paint.get("icon-translate"),S.paint.get("icon-translate-anchor"),!1))},circle:function(M,g,S,P){if(M.renderPass!=="translucent")return;const z=S.paint.get("circle-opacity"),H=S.paint.get("circle-stroke-width"),G=S.paint.get("circle-stroke-opacity"),ee=S.layout.get("circle-sort-key").constantOr(1)!==void 0,ie=S.paint.get("circle-emissive-strength");if(z.constantOr(1)===0&&(H.constantOr(1)===0||G.constantOr(1)===0))return;const pe=M.context,ye=pe.gl,De=M.transform,Ae=!(!M.terrain||!M.terrain.enabled),Be=S.layout.get("circle-elevation-reference"),tt=M.depthModeForSublayer(0,Jr.ReadOnly),Ye=new Jr(M.context.gl.LEQUAL,Jr.ReadOnly,M.depthRangeFor3D),ut=Be==="none"||Ae?tt:Ye,dt=Xn.disabled,jt=M.colorModeForDrapableLayerRenderPass(ie),Tt=De.projection.name==="globe",ft=[o.aH(De.center.lng),o.aL(De.center.lat)],Kt=[];for(let Wt=0;WtWt.sortKey-Et.sortKey);const Rt={useDepthForOcclusion:De.depthOcclusionForSymbolsAndCircles};for(const Wt of Kt){const{programConfiguration:Et,program:Lt,layoutVertexBuffer:Vt,dynamicBuffers:ds,indexBuffer:Zt,uniformValues:Is,tile:Ns}=Wt.state,er=Wt.segments;M.terrain&&M.terrain.setupElevationDraw(Ns,Lt,Rt),M.uploadCommonUniforms(pe,Lt,Ns.tileID.toUnwrapped()),Lt.draw(M,ye.TRIANGLES,ut,dt,jt,Cn.disabled,Is,S.id,Vt,Zt,er,S.paint,De.zoom,Et,ds)}},heatmap:function(M,g,S,P){if(S.paint.get("heatmap-opacity")!==0)if(M.renderPass==="offscreen"){const z=M.context,H=z.gl,G=Xn.disabled,ee=new Hn([H.ONE,H.ONE,H.ONE,H.ONE],o.aq.transparent,[!0,!0,!0,!0]),ie=M.transform.projection.name==="globe"?.5:.25;S.heatmapFbo=Vw.createWithTexture(z,S.heatmapFbo,M.width*ie,M.height*ie),z.clear({color:o.aq.transparent});const pe=M.transform,ye=pe.projection.name==="globe",De=ye?["PROJECTION_GLOBE_VIEW"]:[],Ae=ye?Cn.frontCCW:Cn.disabled,Be=[o.aH(pe.center.lng),o.aL(pe.center.lat)];for(let tt=0;tt({u_image:0,u_color_ramp:1,u_opacity:De.paint.get("heatmap-opacity")}))(0,H),H.id,z.viewportBuffer,z.quadTriangleIndexBuffer,z.viewportSegments,H.paint,z.transform.zoom)}(M,S))},line:function(M,g,S,P){const z=S.paint.get("line-opacity"),H=S.paint.get("line-width");if(z.constantOr(1)===0||H.constantOr(1)===0)return;const G=S.paint.get("line-blend-mode");if(G!=="default"&&M.transform.projection.name!=="globe")return M.terrain&&M.terrain.renderingToTexture?void function(ee,ie,pe,ye,De){if(ee.renderPass!=="translucent")return;const Ae=ee.context,Be=Ae.gl,tt=ee.terrain;if(!tt)return;const Ye=Ae.bindFramebuffer.current,ut=ee.emissiveMode==="mrt-fallback";pe.lineBlendDrapeFbo=Vw.createWithTexture(Ae,pe.lineBlendDrapeFbo,tt.drapeBufferSize[0],tt.drapeBufferSize[1],!0),pe.lineBlendDrapeStencil=pe.lineBlendDrapeFbo._stencilRbo,ut&&Be.drawBuffers([Be.COLOR_ATTACHMENT0]),Ae.clear({color:Nf[De].clearColor,depth:1,stencil:0});const dt=ee.currentStencilSource,jt=ee._tileClippingMaskIDs,Tt=ee.nextStencilID;ee.currentStencilSource=void 0,ee._tileClippingMaskIDs={},ee.nextStencilID=1;const ft=ee._terrain;ee._terrain=null,ee._renderTileClippingMasks(pe,ie,ye),Zc(ee,ie,pe,ye,Nf[De].colorMode,!0),ee._terrain=ft,ee.currentStencilSource=dt,ee._tileClippingMaskIDs=jt,ee.nextStencilID=Tt,Ae.bindFramebuffer.set(Ye),ut&&Be.drawBuffers([Be.COLOR_ATTACHMENT0,Be.COLOR_ATTACHMENT1]);const Kt=tt.drapeBufferSize;Ae.viewport.set([0,0,Kt[0],Kt[1]]);const Rt=pe.lineBlendDrapeFbo;if(!Rt)return;Ae.activeTexture.set(Be.TEXTURE0),Be.bindTexture(Be.TEXTURE_2D,Rt.colorAttachment0.get());const Wt=De==="additive"?1:pe.paint.get("line-opacity").constantOr(1),Et=pe.paint.get("line-emissive-strength").constantOr(0),Lt=De==="additive"?ee.colorModeForDrapableLayerRenderPass(Et):Nf[De].colorMode;ee.getOrCreateProgram("lineBlendComposite").draw(ee,Be.TRIANGLES,Jr.disabled,Xn.disabled,Lt,Cn.disabled,Bw(0,Wt,Nf[De].compositeUniformValue),pe.id,ee.viewportBuffer,ee.quadTriangleIndexBuffer,ee.viewportSegments,pe.paint,ee.transform.zoom)}(M,g,S,P,G):M.renderPass==="offscreen"?void function(ee,ie,pe,ye,De){const Ae=ee.context,Be=Math.ceil(ee.width),tt=Math.ceil(ee.height);pe.lineBlendFbo=Vw.createWithTexture(Ae,pe.lineBlendFbo,Be,tt,!0),pe.lineBlendStencil=pe.lineBlendFbo._stencilRbo,Ae.clear({color:Nf[De].clearColor,depth:1,stencil:0});const Ye=ee.currentStencilSource,ut=ee._tileClippingMaskIDs,dt=ee.nextStencilID;ee.currentStencilSource=void 0,ee._tileClippingMaskIDs={},ee.nextStencilID=1,ee._renderTileClippingMasks(pe,ie,ye);const jt=ee.renderPass;ee.renderPass="translucent",Zc(ee,ie,pe,ye,Nf[De].colorMode),ee.renderPass=jt,ee.currentStencilSource=Ye,ee._tileClippingMaskIDs=ut,ee.nextStencilID=dt,Ae.viewport.set([0,0,ee.width,ee.height])}(M,g,S,P,G):M.renderPass==="translucent"?void function(ee,ie,pe){const ye=ee.context,De=ye.gl,Ae=ie.lineBlendFbo;if(!Ae)return;ye.activeTexture.set(De.TEXTURE0),De.bindTexture(De.TEXTURE_2D,Ae.colorAttachment0.get());const Be=pe==="additive"?1:ie.paint.get("line-opacity").constantOr(1),tt=pe==="additive"?ee.colorModeForDrapableLayerRenderPass(ie.paint.get("line-emissive-strength").constantOr(0)):Nf[pe].colorMode;ee.getOrCreateProgram("lineBlendComposite").draw(ee,De.TRIANGLES,Jr.disabled,Xn.disabled,tt,Cn.disabled,Bw(0,Be,Nf[pe].compositeUniformValue),ie.id,ee.viewportBuffer,ee.quadTriangleIndexBuffer,ee.viewportSegments,ie.paint,ee.transform.zoom)}(M,S,G):void 0;M.renderPass==="translucent"&&Zc(M,g,S,P)},fill:function(M,g,S,P){const z=S.paint.get("fill-color"),H=S.paint.get("fill-opacity");if(H.constantOr(1)===0)return;const G=S.paint.get("fill-emissive-strength"),ee=M.colorModeForDrapableLayerRenderPass(G),ie=S.paint.get("fill-pattern"),pe=M.opaquePassEnabledForLayer()&&!ie.constantOr(1)&&z.constantOr(o.aq.transparent).a===1&&H.constantOr(0)===1?"opaque":"translucent";let ye="none";S.layout.get("fill-elevation-reference")!=="none"?ye="road":S.paint.get("fill-z-offset").constantOr(1)!==0&&(ye="offset");const De=!(!M.terrain||!M.terrain.enabled),Ae={painter:M,sourceCache:g,layer:S,coords:P,colorMode:ee,elevationType:ye,terrainEnabled:De,pass:pe};if(M.renderPass==="shadow")return void(M.shadowRenderer&&ye==="road"&&!De&&function(tt){const{painter:Ye,sourceCache:ut,layer:dt,coords:jt}=tt,Tt=Ye.context.gl,ft=tt.painter.shadowRenderer;for(const Kt of jt){const Rt=ut.getTile(Kt),Wt=Rt.getBucket(dt);if(!Wt)continue;const Et=Wt.elevatedStructures;if(!Et||!Et.shadowCasterSegments||Et.shadowCasterSegments.segments[0].primitiveLength===0)continue;Ye.prepareDrawTile();const Lt=Wt.bufferData.programConfigurations.get(dt.id),Vt=Ye.isTileAffectedByFog(Kt),ds=Ye.getOrCreateProgram("elevatedStructuresDepth",{config:Lt,overrideFog:Vt}),Zt=ft.calculateShadowPassMatrixFromTile(Rt.tileID.toUnwrapped());Ye.uploadCommonUniforms(Ye.context,ds,Kt.toUnwrapped());const Is=pb(Zt,0);ds.draw(Ye,Tt.TRIANGLES,ft.getShadowPassDepthMode(),Xn.disabled,Hn.disabled,Cn.disabled,Is,dt.id,Et.vertexBuffer,Et.indexBuffer,Et.shadowCasterSegments,dt.paint,Ye.transform.zoom,Lt)}}(Ae));const Be=M.emissiveMode==="mrt-fallback";if(ye!=="offset"){if(Ov(Ae,!1,Be),ye==="road"){const tt=!De&&M.renderPass==="translucent";tt&&dy(M,g,S,P,"geometry"),Ov(Ae,!0,Be,Xn.disabled),tt&&function(Ye){const{painter:ut,sourceCache:dt,layer:jt,coords:Tt,colorMode:ft}=Ye,Kt=ut.context.gl,Rt=Ye.painter.shadowRenderer,Wt=!!Rt&&Rt.enabled,Et=new Jr(ut.context.gl.LEQUAL,Jr.ReadOnly,ut.depthRangeFor3D);let Lt=[0,0,0];if(Wt){const ds=ut.style.directionalLight,Zt=ut.style.ambientLight;ds&&Zt&&(Lt=vf(ut.style,ds,Zt))}const Vt=ds=>{for(const Zt of Tt){const Is=dt.getTile(Zt),Ns=Is.getBucket(jt);if(!Ns)continue;const er=Ns.elevatedStructures;if(!er)continue;let lr,hs;if(ds?(lr=er.renderableBridgeSegments,hs=er.bridgeProgramConfigurations.get(jt.id)):(lr=er.renderableTunnelSegments,hs=er.tunnelProgramConfigurations.get(jt.id)),!lr||lr.segments[0].primitiveLength===0)continue;hs.updatePaintBuffers(),ut.prepareDrawTile();const ss=ut.isTileAffectedByFog(Zt),Ts=[];Wt&&Ts.push("RENDER_SHADOWS","NORMAL_OFFSET");const Rs=ut.getOrCreateProgram("elevatedStructures",{config:hs,overrideFog:ss,defines:Ts}),qs=ut.translatePosMatrix(Zt.projMatrix,Is,jt.paint.get("fill-translate"),jt.paint.get("fill-translate-anchor"));Wt&&Rt.setupShadows(Is.tileID.toUnwrapped(),Rs,"vector-tile");const Cr=zw(qs,Lt);ut.uploadCommonUniforms(ut.context,Rs,Zt.toUnwrapped()),Rs.draw(ut,Kt.TRIANGLES,Et,Xn.disabled,ft,Cn.backCCW,Cr,jt.id,er.vertexBuffer,er.indexBuffer,lr,jt.paint,ut.transform.zoom,hs,[er.vertexBufferNormal])}};Vt(!0),Vt(!1)}(Ae)}}else Ov(Ae,!1,Be,M.stencilModeFor3D())},"fill-extrusion":function(M,g,S,P){const z=S.paint.get("fill-extrusion-opacity"),H=M.context,G=H.gl,ee=M.terrain,ie=ee&&ee.renderingToTexture;if(z===0)return;const pe=M.emissiveMode==="mrt-fallback",ye=M.conflationActive&&M.style.isLayerClipped(S,g.getSource()),De=M.style.order.indexOf(S.fqid);if(ye&&function(Ae,Be,tt,Ye,ut){for(const dt of Ye){const jt=Be.getTile(dt).getBucket(tt);jt&&(jt.updateReplacement(dt,Ae.replacementSource,ut),jt.uploadCentroid(Ae.context))}}(M,g,S,P,De),ee||ye)for(const Ae of P){const Be=g.getTile(Ae).getBucket(S);Be&&Bx(M.context,g,Ae,Be,S,ee,ye)}if(M.renderPass==="shadow"&&M.shadowRenderer){if(ee&&z<.65&&S._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const Ae=M.shadowRenderer.getShadowPassDepthMode();Xp(M,g,S,P,Ae,Xn.disabled,Hn.disabled,ye)}else if(M.renderPass==="translucent"){const Ae=!S.paint.get("fill-extrusion-pattern").constantOr(1),Be=S.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!ie&&Be.a!==0){const tt=new Jr(M.context.gl.LEQUAL,Jr.ReadWrite,M.depthRangeFor3D);z===1&&Ae?Xp(M,g,S,P,tt,Xn.disabled,Hn.unblended,ye):(Xp(M,g,S,P,tt,Xn.disabled,Hn.disabled,ye),Xp(M,g,S,P,tt,M.stencilModeFor3D(),M.colorModeForRenderPass(),ye),M.resetStencilClippingMasks())}if(M.style.enable3dLights()&&Ae&&(!ee&&M.transform.projection.name!=="globe"||ie)){const tt=S.paint.get("fill-extrusion-opacity"),Ye=S.paint.get("fill-extrusion-ambient-occlusion-intensity"),ut=S.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),dt=S.paint.get("fill-extrusion-flood-light-intensity"),jt=S.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Tt=S.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(jt?null:S.lut).toArray01().slice(0,3),ft=Ye>0&&ut>0,Kt=dt>0,Rt=(Lt,Vt,ds)=>(1-ds)*Lt+ds*Vt,Wt=new Nh;Wt.translate=S.paint.get("fill-extrusion-translate"),Wt.translateAnchor=S.paint.get("fill-extrusion-translate-anchor"),Wt.edgeRadius=S.layout.get("fill-extrusion-edge-radius"),Wt.cutoffFadeRange=S.paint.get("fill-extrusion-cutoff-fade-range");const Et=Lt=>{const Vt=M.depthModeForSublayer(1,Jr.ReadOnly,G.LEQUAL,!0),ds=S.paint.get(Lt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Zt=Rt(.1,3,ds),Is=M._showOverdrawInspector;if(!Is){const Ns=new Xn({func:G.ALWAYS,mask:255},255,255,G.KEEP,G.KEEP,G.REPLACE),er=new Hn([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!1,!1,!1,!0],G.MIN);mp(Wt,M,g,S,P,Vt,Ns,er,Cn.disabled,Lt,"sdf",tt,Ye,ut,dt,Tt,Zt,ye,!1)}{const Ns=Is?Xn.disabled:new Xn({func:G.EQUAL,mask:255},255,255,G.KEEP,G.DECR,G.DECR),er=Is?M.colorModeForRenderPass():new Hn([G.ONE_MINUS_DST_ALPHA,G.DST_ALPHA,G.ONE,G.ONE],o.aq.transparent,[!0,!0,!0,!0]);mp(Wt,M,g,S,P,Vt,Ns,er,Cn.disabled,Lt,"color",tt,Ye,ut,dt,Tt,Zt,ye,!1)}};if(ie){const Lt=()=>{const ds=ee.drapeBufferSize[0],Zt=ee.drapeBufferSize[1];let Is=ee.framebufferCopyTexture;return Is&&(!Is||Is.size[0]===ds&&Is.size[1]===Zt)||(Is&&Is.destroy(),Is=ee.framebufferCopyTexture=new o.T(H,new o.q({width:ds,height:Zt}),G.RGBA8)),Is.bind(G.LINEAR,G.CLAMP_TO_EDGE),G.copyTexSubImage2D(G.TEXTURE_2D,0,0,0,0,0,ds,Zt),Is},Vt=(ds,Zt,Is)=>{const Ns=M.depthModeForSublayer(1,Jr.ReadOnly,G.LEQUAL,!1),er=S.paint.get(ds?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),lr=Rt(.1,3,er);{const hs=new Hn([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!1,!1,!1,!0]);mp(Wt,M,g,S,P,Ns,Xn.disabled,hs,Cn.disabled,ds,"clear",tt,Ye,ut,dt,Tt,lr,ye,Zt)}{const hs=new Xn({func:G.ALWAYS,mask:255},255,255,G.KEEP,G.KEEP,G.REPLACE),ss=new Hn([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!1,!1,!1,!0],G.MIN);mp(Wt,M,g,S,P,Ns,hs,ss,Cn.disabled,ds,"sdf",tt,Ye,ut,dt,Tt,lr,ye,Zt)}pe&&!ds&&(Is=Lt());{const hs=ds?G.ZERO:G.ONE_MINUS_DST_ALPHA,ss=new Xn({func:G.EQUAL,mask:255},255,255,G.KEEP,G.DECR,G.DECR),Ts=new Hn([hs,G.DST_ALPHA,G.ONE_MINUS_DST_ALPHA,G.ZERO],o.aq.transparent,[!0,!0,!0,!0]);mp(Wt,M,g,S,P,Ns,ss,Ts,Cn.disabled,ds,"color",tt,Ye,ut,dt,Tt,lr,ye,Zt)}if(!pe||ds){const hs=new Hn([G.ONE,G.ONE,G.ONE,ds?G.ZERO:G.ONE],o.aq.transparent,[!1,!1,!1,!0],ds?G.FUNC_ADD:G.MAX);mp(Wt,M,g,S,P,Ns,Xn.disabled,hs,Cn.disabled,ds,"clear",tt,Ye,ut,dt,Tt,lr,ye,Zt,Is)}else{G.drawBuffers([G.NONE,G.COLOR_ATTACHMENT1]);const hs=new Xn({func:G.EQUAL,mask:255},254,255,G.KEEP,G.DECR,G.DECR),ss=new Hn([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!0,!1,!1,!1],G.MAX);mp(Wt,M,g,S,P,Ns,hs,ss,Cn.disabled,ds,"emissive",tt,Ye,ut,dt,Tt,lr,ye,Zt,Is),G.drawBuffers([G.COLOR_ATTACHMENT0])}};if(ft||Kt){let ds;M.prepareDrawTile(),pe&&!ft||(ds=Lt()),ft&&Vt(!0,!1,ds),Kt&&Vt(!1,!0,ds)}}else ft&&Et(!0),Kt&&Et(!1),(ft||Kt)&&M.resetStencilClippingMasks()}}},building:function(M,g,S,P){M.currentLayer0&&H>0,pe=!0;const ye=S.paint.get("building-vertical-scale");if(ye<=0)return;M.shadowRenderer||(pe=!1);const De=M.conflationActive&&M.style.isLayerClipped(S,g.getSource()),Ae=M.style.order.indexOf(S.fqid);if(function(Be,tt,Ye,ut,dt,jt){for(const Tt of jt){const ft=tt.getTile(Tt).getBucket(Ye);ft&&(dt&&ft.updateReplacement(Tt,Be.replacementSource,ut),ft.uploadUpdatedIndexBuffer(Be.context))}}(M,g,S,Ae,De,P),function(Be,tt,Ye,ut){for(const dt of ut){const jt=tt.getTile(dt).getBucket(Ye);jt&&jt.needsEvaluation()&&jt.uploadUpdatedColorBuffer(Be.context)}}(M,g,S,P),S.resetLayerRenderingStats(M),M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!0),M.renderPass==="shadow"&&M.shadowRenderer){const Be=[],tt=M.shadowRenderer.getShadowPassDepthMode();uy({painter:M,source:g,layer:S,coords:P,defines:Be,blendMode:Hn.disabled,depthMode:tt,opacity:ee,verticalScale:ye,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(M.renderPass==="translucent"){let Be=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];pe&&(Be=Be.concat("RENDER_SHADOWS")),M.shadowRenderer&&M.shadowRenderer.useNormalOffset&&(Be=Be.concat("NORMAL_OFFSET"));const tt=S.paint.get("building-facade-emissive-chance"),Ye=S.paint.get("building-ambient-occlusion-intensity"),ut=S.paint.get("building-flood-light-intensity"),dt=S.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",jt=S.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(dt?null:S.lut).toArray01().slice(0,3),Tt=S.paint.get("building-flood-light-ground-attenuation"),ft=ut>0,Kt=new Jr(M.context.gl.LEQUAL,Jr.ReadWrite,M.depthRangeFor3D);ee<1&&uy({painter:M,source:g,layer:S,coords:P,defines:Be,blendMode:Hn.disabled,depthMode:Kt,opacity:ee,verticalScale:ye,facadeEmissiveChance:tt,facadeAOIntensity:Ye,floodLightIntensity:ut,floodLightColor:jt,depthOnly:!0});const Rt=M.colorModeForRenderPass();uy({painter:M,source:g,layer:S,coords:P,defines:Be,blendMode:Rt,depthMode:Kt,opacity:ee,verticalScale:ye,facadeEmissiveChance:tt,facadeAOIntensity:Ye,floodLightIntensity:ut,floodLightColor:jt});const Wt=S.paint.get("building-front-cutoff");yb(M.transform.pitch,Wt,!!M.terrain),ie&&$x(M,g,S,P,!0,ee,z,H,ut,jt,G,De),ft&&$x(M,g,S,P,!1,ee,z,H,ut,jt,Tt,De)}else if(M.renderPass==="light-beam"){const Be=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],tt=new Jr(M.context.gl.LEQUAL,Jr.ReadOnly,M.depthRangeFor3D);uy({painter:M,source:g,layer:S,coords:P,defines:Be,blendMode:Hn.alphaBlended,depthMode:tt,opacity:ee,verticalScale:ye,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!1),M.resetStencilClippingMasks()},hillshade:function(M,g,S,P){if(M.renderPass!=="offscreen"&&M.renderPass!=="translucent"||M.style.disableElevatedTerrain)return;const z=M.context,H=M.terrain&&M.terrain.renderingToTexture,[G,ee]=M.renderPass!=="translucent"||H?[{},P]:M.stencilConfigForOverlap(P);for(const ie of ee){const pe=g.getTile(ie);if(pe.needsHillshadePrepare&&M.renderPass==="offscreen")gM(M,pe,S);else if(M.renderPass==="translucent"){const ye=M.depthModeForSublayer(0,Jr.ReadOnly),De=S.paint.get("hillshade-emissive-strength"),Ae=M.colorModeForDrapableLayerRenderPass(De),Be=H&&M.terrain?M.terrain.stencilModeForRTTOverlap(ie):G[ie.overscaledZ];yD(M,ie,pe,S,ye,Be,Ae)}}z.viewport.set([0,0,M.width,M.height]),M.resetStencilClippingMasks()},raster:function(M,g,S,P,z,H){if(M.renderPass!=="translucent")return;const G=S.paint.get("raster-opacity");if(G===0)return;const ee=M.transform.projection.name==="globe",ie=S.paint.get("raster-elevation")!==0,pe=ie&&ee,ye=M.terrain&&M.terrain.exaggeration()>0&&ie&&S.paint.get("raster-elevation-reference")==="ground",De=!ee&&ye;if(M.renderElevatedRasterBackface&&!pe)return;const Ae=M.context,Be=Ae.gl,tt=g.getSource(),Ye=function(Lt,Vt,ds,Zt,Is){const Ns=Vt.paint.get("raster-color"),er=Lt.type==="raster-array",lr=[],hs=Vt.paint.get("raster-resampling"),ss=Vt.paint.get("raster-color-mix");let Ts=Vt.paint.get("raster-color-range");const Rs=[ss[0],ss[1],ss[2],0],qs=ss[3];let Cr=hs==="nearest"?Zt.NEAREST:Zt.LINEAR;if(er&&(lr.push("RASTER_ARRAY"),Ns||lr.push("RASTER_COLOR"),hs==="linear"&&lr.push("RASTER_ARRAY_LINEAR"),Cr=Zt.NEAREST,!Ts&&Lt.rasterLayers)){const br=Lt.rasterLayers.find(({id:_r})=>_r===Vt.sourceLayer);br&&br.fields&&br.fields.range&&(Ts=br.fields.range)}if(Ts=Ts||[0,1],Ns){lr.push("RASTER_COLOR"),ds.activeTexture.set(Zt.TEXTURE2),Vt.updateColorRamp(Ts);let br=Vt.colorRampTexture;br||(br=Vt.colorRampTexture=new o.T(ds,Vt.colorRamp,Zt.RGBA8)),br.bind(Cr,Zt.CLAMP_TO_EDGE)}return Is&&lr.push("USE_MRT1"),{mix:Rs,range:Ts,offset:qs,defines:lr,resampling:Cr}}(tt,S,Ae,Be,M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback");if(tt instanceof o.aV&&!P.length&&!ee)return;const ut=S.paint.get("raster-emissive-strength"),dt=M.colorModeForDrapableLayerRenderPass(ut),jt=M.terrain&&M.terrain.renderingToTexture,Tt=!M.options.moving,ft=S.paint.get("raster-resampling")==="nearest"?Be.NEAREST:Be.LINEAR;if(tt instanceof o.aV&&!P.length&&(tt.onNorthPole||tt.onSouthPole)){const Lt=ie?M.stencilModeFor3D():Xn.disabled;return void hy(!!tt.onNorthPole,null,M,g,S,ut,Ye,Cn.disabled,Lt)}if(!P.length)return;const[Kt,Rt]=tt instanceof o.aV||jt?[{},P]:M.stencilConfigForOverlap(P),Wt=Rt[Rt.length-1].overscaledZ;pe&&Ye.defines.push("PROJECTION_GLOBE_VIEW"),ie&&Ye.defines.push("RENDER_CUTOFF","ELEVATED"),ye&&Ye.defines.push("ELEVATION_REFERENCE_GROUND");const Et=(Lt,Vt,ds)=>{for(const Zt of Lt){const Is=Zt.toUnwrapped(),Ns=g.getTile(Zt);if(jt&&(!Ns||!Ns.hasData()))continue;Ae.activeTexture.set(Be.TEXTURE0);const er=Kw(Ns,tt,S,Ye);if(!er||!er.texture)continue;const{texture:lr,mix:hs,offset:ss,tileSize:Ts,buffer:Rs}=er;let qs,Cr;jt?(qs=Jr.disabled,Cr=Zt.projMatrix):ie?(qs=new Jr(Be.LEQUAL,Jr.ReadWrite,M.depthRangeFor3D),Cr=ee?Float32Array.from(M.transform.expandedFarZProjMatrix):M.transform.calculateProjMatrix(Is,Tt)):(qs=M.depthModeForSublayer(Zt.overscaledZ-Wt,G===1?Jr.ReadWrite:Jr.ReadOnly,Be.LESS),Cr=M.transform.calculateProjMatrix(Is,Tt));const br=M.terrain&&jt?M.terrain.stencilModeForRTTOverlap(Zt):Kt[Zt.overscaledZ],_r=H?0:S.paint.get("raster-fade-duration");Ns.registerFadeDuration(_r);const nr=g.findLoadedParent(Zt,0),on=Bm(Ns,nr,g,M.transform,_r);let gn,en;!on.isFading&&Ns.refreshedUponExpiration&&(Ns.refreshedUponExpiration=!1),M.terrain&&M.terrain.prepareDrawTile(),Ae.activeTexture.set(Be.TEXTURE0),lr.bind(ft,Be.CLAMP_TO_EDGE),Ae.activeTexture.set(Be.TEXTURE1),nr?(nr.texture&&nr.texture.bind(ft,Be.CLAMP_TO_EDGE),gn=Math.pow(2,nr.tileID.overscaledZ-Ns.tileID.overscaledZ),en=[Ns.tileID.canonical.x*gn%1,Ns.tileID.canonical.y*gn%1]):lr.bind(ft,Be.CLAMP_TO_EDGE),"useMipmap"in lr&&Ae.extTextureFilterAnisotropic&&M.transform.pitch>20&&Be.texParameterf(Be.TEXTURE_2D,Ae.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Ae.extTextureFilterAnisotropicMax);const nn=M.transform;let Gn;const ma=ie?Ww(nn):[0,0,0,0];let aa,Oa,zn,Fa,ia,ji=0;if(pe&&tt instanceof o.aV&&tt.coordinates.length>3)aa=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Oa=Float32Array.from(nn.globeMatrix),zn=Float32Array.from(o.dq(nn)),Fa=[o.aH(nn.center.lng),o.aL(nn.center.lat)],Gn=tt.elevatedGlobePerspectiveTransform,ia=tt.elevatedGlobeGridMatrix||new Float32Array(9);else if(pe){const Ii=o.dr(Zt.canonical);ji=o.ds(Ii.getCenter().lat),aa=Float32Array.from(o.du(o.dv(Zt.canonical))),Oa=Float32Array.from(nn.globeMatrix),zn=Float32Array.from(o.dq(nn)),Fa=[o.aH(nn.center.lng),o.aL(nn.center.lat)],Gn=[0,0],ia=Float32Array.from(o.dt(Zt.canonical,Ii,ji,nn.worldSize/nn._pixelsPerMercatorPixel))}else Gn=tt instanceof o.aV?tt.perspectiveTransform:[0,0],aa=new Float32Array(16),Oa=new Float32Array(9),zn=new Float32Array(16),Fa=[0,0],ia=new Float32Array(9);const mo=Wp(M,Cr,aa,Oa,zn,ia,en||[0,0],o.al(M.transform.zoom),Fa,ma,gn||1,on,S,Gn,ie?S.paint.get("raster-elevation"):0,2,hs,ss,Ye.range,Ts,Rs,ut),ml=M.isTileAffectedByFog(Zt),No=M.getOrCreateProgram("raster",{defines:Ye.defines,overrideFog:ml});if(M.uploadCommonUniforms(Ae,No,Is),tt instanceof o.aV){const Ii=tt.elevatedGlobeVertexBuffer,Ta=tt.elevatedGlobeIndexBuffer;if(jt||!ee)tt.boundsBuffer&&tt.boundsSegments&&No.draw(M,Be.TRIANGLES,qs,Xn.disabled,dt,Cn.disabled,mo,S.id,tt.boundsBuffer,M.quadTriangleIndexBuffer,tt.boundsSegments);else if(Ii&&Ta){const Ea=nn.zoom<=o.cJ?tt.elevatedGlobeSegments:tt.getSegmentsForLongitude(nn.center.lng);Ea&&No.draw(M,Be.TRIANGLES,qs,Xn.disabled,dt,Vt,mo,S.id,Ii,Ta,Ea)}}else if(pe){qs=new Jr(Be.LEQUAL,Jr.ReadOnly,M.depthRangeFor3D);const Ii=M.globeSharedBuffers;if(Ii){ye&&(M.terrain.setupElevationDraw(Ns,No),M.uploadCommonUniforms(Ae,No,Ns.tileID.toUnwrapped()));const[Ta,Ea,ko]=Ii.getGridBuffers(ji,!1),bl=No.getAttributeLocation(Be,"a_texture_pos");bl!==-1&&Be.vertexAttribI4ui(bl,0,0,0,0),No.draw(M,Be.TRIANGLES,qs,ds||br,M.colorModeForRenderPass(),Vt,mo,S.id,Ta,Ea,ko)}}else if(De)qs=new Jr(Be.LEQUAL,Jr.ReadWrite,M.depthRangeFor3D),M.terrain.setupElevationDraw(Ns,No),M.uploadCommonUniforms(Ae,No,Ns.tileID.toUnwrapped()),nn.pitch>20&&No.draw(M,Be.TRIANGLES,qs,Xn.disabled,Hn.disabled,Cn.frontCCW,mo,S.id,M.terrain.gridBuffer,M.terrain.gridIndexBuffer,M.terrain.gridSegments),No.draw(M,Be.TRIANGLES,qs,br,dt,Cn.backCCW,mo,S.id,M.terrain.gridBuffer,M.terrain.gridIndexBuffer,M.terrain.gridSegments);else{const{tileBoundsBuffer:Ii,tileBoundsIndexBuffer:Ta,tileBoundsSegments:Ea}=M.getTileBoundsBuffers(Ns);No.draw(M,Be.TRIANGLES,qs,br,dt,Cn.disabled,mo,S.id,Ii,Ta,Ea)}}if(!(tt instanceof o.aV)&&pe)for(const Zt of Lt){const Is=Zt.canonical.y===(1<o.d$[Rs](Is));hs.push(Is);const ss=Is.canonical.x,Ts=Is.canonical.y;for(const Rs of hs){const qs=ft.getTile(Vt?Rs.wrapped():Rs);if(!qs)continue;const Cr=qs.rasterParticleState;if(!Cr)continue;const br=Rs.canonical.x+(1<Wt.tileID)),Be&&(pe.activeTexture.set(ye.TEXTURE0),M.imageManager.bind(M.context,S.scope));const Rt=[];if(M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback"&&Rt.push("USE_MRT1"),ie){const Wt=M.getOrCreateProgram(Tt,{overrideFog:!1,overrideRtt:!0,defines:Rt}),Et=new Float32Array(o.b9([])),Lt=new o.aR(0,0,0,0,0),Vt=Be?Yp(Et,ee,G,M,0,S.scope,tt,ie,{tileID:Lt,tileSize:Ae}):cy(Et,ee,G,z.toPremultipliedRenderColor(H?null:S.lut));return void Wt.draw(M,ye.TRIANGLES,dt,ut,jt,Cn.disabled,Vt,S.id,M.viewportBuffer,M.quadTriangleIndexBuffer,M.viewportSegments)}for(const Wt of Kt){const Et=M.isTileAffectedByFog(Wt),Lt=M.getOrCreateProgram(Tt,{overrideFog:Et,defines:Rt}),Vt=Wt.toUnwrapped(),ds=P?Wt.projMatrix:M.transform.calculateProjMatrix(Vt);M.prepareDrawTile();const Zt=g?g.getTile(Wt):ft?ft[Wt.key]:new o.b0(Wt,Ae,De.zoom,M),Is=Be?Yp(ds,ee,G,M,0,S.scope,tt,ie,{tileID:Wt,tileSize:Ae}):cy(ds,ee,G,z.toPremultipliedRenderColor(H?null:S.lut));M.uploadCommonUniforms(pe,Lt,Vt);const{tileBoundsBuffer:Ns,tileBoundsIndexBuffer:er,tileBoundsSegments:lr}=M.getTileBoundsBuffers(Zt);Lt.draw(M,ye.TRIANGLES,dt,ut,jt,Cn.disabled,Is,S.id,Ns,er,lr)}},sky:function(M,g,S){const P=M._atmosphere?o.al(M.transform.zoom):1,z=S.paint.get("sky-opacity")*P;if(z===0)return;const H=M.context,G=S.paint.get("sky-type"),ee=new Jr(H.gl.LEQUAL,Jr.ReadOnly,[0,1]),ie=M.frameCounter/1e3%1;G==="atmosphere"?M.renderPass==="offscreen"?S.needsSkyboxCapture(M)&&(function(pe,ye){const De=pe.context,Ae=De.gl;let Be=ye.skyboxFbo;if(!Be){Be=ye.skyboxFbo=De.createFramebuffer(32,32,1,null),ye.skyboxGeometry=new Md(De),ye.skyboxTexture=De.gl.createTexture(),Ae.bindTexture(Ae.TEXTURE_CUBE_MAP,ye.skyboxTexture),Ae.texParameteri(Ae.TEXTURE_CUBE_MAP,Ae.TEXTURE_WRAP_S,Ae.CLAMP_TO_EDGE),Ae.texParameteri(Ae.TEXTURE_CUBE_MAP,Ae.TEXTURE_WRAP_T,Ae.CLAMP_TO_EDGE),Ae.texParameteri(Ae.TEXTURE_CUBE_MAP,Ae.TEXTURE_MIN_FILTER,Ae.LINEAR),Ae.texParameteri(Ae.TEXTURE_CUBE_MAP,Ae.TEXTURE_MAG_FILTER,Ae.LINEAR);for(let dt=0;dt<6;++dt)Ae.texImage2D(Ae.TEXTURE_CUBE_MAP_POSITIVE_X+dt,0,Ae.RGBA,32,32,0,Ae.RGBA,Ae.UNSIGNED_BYTE,null)}De.bindFramebuffer.set(Be.framebuffer),De.viewport.set([0,0,32,32]);const tt=ye.getCenter(pe,!0),Ye=pe.getOrCreateProgram("skyboxCapture"),ut=new Float64Array(16);o.b9(ut),o.ef(ut,ut,.5*-Math.PI),kf(pe,ye,Ye,ut,tt,0),o.b9(ut),o.ef(ut,ut,.5*Math.PI),kf(pe,ye,Ye,ut,tt,1),o.b9(ut),o.cE(ut,ut,.5*-Math.PI),kf(pe,ye,Ye,ut,tt,2),o.b9(ut),o.cE(ut,ut,.5*Math.PI),kf(pe,ye,Ye,ut,tt,3),o.b9(ut),kf(pe,ye,Ye,ut,tt,4),o.b9(ut),o.ef(ut,ut,Math.PI),kf(pe,ye,Ye,ut,tt,5),De.viewport.set([0,0,pe.width,pe.height])}(M,S),S.markSkyboxValid(M)):M.renderPass==="sky"&&function(pe,ye,De,Ae,Be){const tt=pe.context,Ye=tt.gl,ut=pe.transform,dt=pe.getOrCreateProgram("skybox");tt.activeTexture.set(Ye.TEXTURE0),Ye.bindTexture(Ye.TEXTURE_CUBE_MAP,ye.skyboxTexture);const jt=((Tt,ft,Kt,Rt,Wt)=>({u_matrix:Tt,u_sun_direction:ft,u_cubemap:0,u_opacity:Rt,u_temporal_offset:Wt}))(ut.skyboxMatrix,ye.getCenter(pe,!1),0,Ae,Be);pe.uploadCommonUniforms(tt,dt),dt.draw(pe,Ye.TRIANGLES,De,Xn.disabled,pe.colorModeForRenderPass(),Cn.backCW,jt,"skybox",ye.skyboxGeometry.vertexBuffer,ye.skyboxGeometry.indexBuffer,ye.skyboxGeometry.segment)}(M,S,ee,z,ie):G==="gradient"&&M.renderPass==="sky"&&function(pe,ye,De,Ae,Be){const tt=pe.context,Ye=tt.gl,ut=pe.transform,dt=pe.getOrCreateProgram("skyboxGradient");ye.skyboxGeometry||(ye.skyboxGeometry=new Md(tt)),tt.activeTexture.set(Ye.TEXTURE0);let jt=ye.colorRampTexture;jt||(jt=ye.colorRampTexture=new o.T(tt,ye.colorRamp,Ye.RGBA8)),jt.bind(Ye.LINEAR,Ye.CLAMP_TO_EDGE);const Tt=((ft,Kt,Rt,Wt,Et)=>({u_matrix:ft,u_color_ramp:0,u_center_direction:Kt,u_radius:o.ap(Rt),u_opacity:Wt,u_temporal_offset:Et}))(ut.skyboxMatrix,ye.getCenter(pe,!1),ye.paint.get("sky-gradient-radius"),Ae,Be);pe.uploadCommonUniforms(tt,dt),dt.draw(pe,Ye.TRIANGLES,De,Xn.disabled,pe.colorModeForRenderPass(),Cn.backCW,Tt,"skyboxGradient",ye.skyboxGeometry.vertexBuffer,ye.skyboxGeometry.indexBuffer,ye.skyboxGeometry.segment)}(M,S,ee,z,ie)},custom:function(M,g,S,P){const z=M.context,H=S.implementation;if(!M.transform.projection.unsupportedLayers||!M.transform.projection.unsupportedLayers.includes("custom")||M.terrain&&(M.terrain.renderingToTexture||M.renderPass==="offscreen")&&S.isDraped(g)){if(M.renderPass==="offscreen"){const G=H.prerender;if(G){if(M.setCustomLayerDefaults(),z.setColorMode(M.colorModeForRenderPass()),M.transform.projection.name==="globe"){const ee=M.transform.pointMerc;G.call(H,z.gl,M.transform.customLayerMatrix(),M.transform.getProjection(),M.transform.globeToMercatorMatrix(),o.al(M.transform.zoom),[ee.x,ee.y],M.transform.pixelsPerMeterRatio)}else G.call(H,z.gl,M.transform.customLayerMatrix());z.setDirty(),M.setBaseState()}}else if(M.renderPass==="translucent"){if(M.terrain&&M.terrain.renderingToTexture){const ee=H.renderToTile;if(ee){const ie=P[0].canonical,pe={x:ie.x+P[0].wrap*(H.wrapTileId?0:1<{pe&&(pe.useNormalOffset=!0,ye||(pe.enabled=!0))},Ae=g.getSource();if(M.renderPass==="light-beam"&&Ae.type!=="batched-model")return;if(Ae.type==="vector"||Ae.type==="geojson")return function(ft,Kt,Rt,Wt,Et){const Lt=ft.transform,Vt=Lt.projection.name==="globe",ds=Lt.getFreeCameraOptions().position;if(!ft.modelManager)return;const Zt=ft.modelManager;Rt.modelManager=Zt;const Is=ft.shadowRenderer;if(!Rt._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const Ns=Rt._unevaluatedLayout._values["model-id"],er=Object.assign({},Rt.layout.get("model-id").parameters),lr=ft.style.order.indexOf(Rt.fqid),hs=Rt.paint.get("model-opacity").constantOr(1);for(const ss of Wt){const Ts=Kt.getTile(ss).getBucket(Rt);if(!Ts||Ts.projection.name!==Lt.projection.name)continue;const Rs=Ts.getModelUris();if(Rs&&!Ts.modelsRequested&&(Zt.addModelsFromBucket(Rs,Et),Ts.modelsRequested=!0),Vt)er.zoom=ss.overscaledZ;else{const en=Sf(ss,Lt);er.zoom=en}const qs=Ns.possiblyEvaluate(er);if(yr(ft,Ts,ss),gr.shadowUniformsInitialized=!1,gr.useSingleShadowCascade=!!Is&&Is.getMaxCascadeForTile(ss.toUnwrapped())===0,ft.renderPass==="shadow"&&Is){if(ft.currentShadowCascade===1&&Ts.isInsideFirstShadowMapFrustum)continue;const en=Lt.calculatePosMatrix(ss.toUnwrapped(),Lt.worldSize);if(gr.tileMatrix.set(en),gr.shadowTileMatrix=Float32Array.from(Is.calculateShadowPassMatrixFromMatrix(en)),gr.aabb.min=[0,0,0],gr.aabb.max[0]=gr.aabb.max[1]=o.an,gr.aabb.max[2]=0,Xw(Ts,gr,ft,Rt.scope))continue}const Cr=1<0&&ft.style.isLayerClipped(Rt,Kt.getSource())&&Ts.updateReplacement(ss,ft.replacementSource,lr,Rt.scope)&&(Ts.uploaded=!1,Ts.upload(ft.context));let _r=0;const nr=new Array,on=new Array,gn=new Array;for(let en in Ts.instancesPerModel){const nn=Ts.instancesPerModel[en];nn.features.length>0&&!Vt&&(en=qs.evaluate(nn.features[0].feature,{}));const Gn=Zt.getModel(en,Et);if(Gn||Zt.hasURLBeenRequested(en)||Ts.modelUris.includes(en)||(Ts.modelUris.push(en),Ts.modelsRequested=!1),Gn&&Gn.uploaded)if(Vt){const ma=o.bJ([],[ds.x,ds.y,ds.z],ft.transform.worldSize);o.eo(ma,ma);for(let aa=0;aa0&&Fa.elevationUpdate(en.terrain,aa,zn,Gn.source),Fa.needsReEvaluation(en,Oa,Gn)&&Fa.evaluate(Gn))}})(ft,Kt,Rt,Wt),function(){const en=new Map;let nn,Gn,ma;nr?(nn=Wt.length-1,Gn=-1,ma=-1):(nn=0,Gn=Wt.length,ma=1);const aa=new Float64Array(16),Oa=o.ce(),zn=new o.P(0,0);for(let Fa=nn;Fa!==Gn;Fa+=ma){const ia=Wt[Fa],ji=Kt.getTile(ia).getBucket(Rt);if(!ji||!ji.uploaded)continue;let mo=!1;ds&&(mo=ds.getMaxCascadeForTile(ia.toUnwrapped())===0);const ml=Lt.calculatePosMatrix(ia.toUnwrapped(),Lt.worldSize),No=ji.modelTraits;!Cr&&nr&&(o.b7(aa,ml),o.ah(Oa,Is,aa),zn.x=Oa[0],zn.y=Oa[1]);const Ii=[];ji.setFilter(Rt.filter);for(const Ta of ji.getNodesInfo()){if(Ta.hiddenByReplacement||!Ta.node.meshes)continue;const Ea=Ta.node;let ko=0;ft.terrain&&Ea.elevation&&(ko=Ea.elevation*ft.terrain.exaggeration());const bl=(()=>{const Jd=Ta.aabb;return qs.min=[...Jd.min],qs.max=[...Jd.max],qs.min[2]+=ko,qs.max[2]+=ko,o.ah(qs.min,qs.min,ml),o.ah(qs.max,qs.max,ml),qs})(),Pi=Ta.evaluatedScale;if(Pi[0]<=1&&Pi[1]<=1&&Pi[2]<=1&&bl.intersects(br)===0)continue;if(!Cr&&nr){const Jd=.16666666666666666;Ta.cameraCollisionOpacity=Is[0]>bl.min[0]&&Is[0]bl.min[1]&&Is[1]!nr||Ta.opacity===1&&Ea.opacity===1?Ta.depthEa.depth?-1:1);for(const Ta of Ii){const Ea=Ta.nodeInfo,ko=Ea.node;if(ft._debugParams.show3DModelFootprints&&ko.footprint){const ni=ko.id||ko.name||"footprint";en.has(ni)||en.set(ni,{node:ko,mvp:Ta.wvpForTile})}let bl=o.aD([],hs,Ta.tileModelMatrix);o.aD(bl,er,bl);const Pi=o.b7([],bl);o.e6(Pi,Pi),o.cC(Pi,Pi,as),bl=o.aD(bl,bl,ko.globalMatrix);const ya=ft.renderPass==="light-beam",al=Rt.paint.get("model-color-use-theme").constantOr("default")==="none",fo=No&o.ez.HasMapboxMeshFeatures,lc=fo?0:Ea.evaluatedRMEA[0][2];for(let ni=0;ni=wn||xp>=wn}}const Xi=bo.material;let ex;Xi.occlusionTexture&&Xi.occlusionTexture.offsetScale&&(ex=Xi.occlusionTexture.offsetScale,Qc.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const tx=ft.getOrCreateProgram("model",Qc);!Cr&&ds&&ds.setupShadowsFromMatrix(Ta.tileModelMatrix,tx,ds.useNormalOffset),ft.uploadCommonUniforms(Et,tx,null,pp);const To=Xi.pbrMetallicRoughness;To.metallicFactor=.9,To.roughnessFactor=.5;const Po=Zp(new Float32Array(th),new Float32Array(bl),new Float32Array(Pi),new Float32Array(ko.globalMatrix),ft,Ta.opacity,To.baseColorFactor,Xi.emissiveFactor,To.metallicFactor,To.roughnessFactor,Xi,lc,Rt,[0,0,0],ex);!Pc&&(Ea.hasTranslucentParts||Ta.opacity<1)&&tx.draw(ft,Et.gl.TRIANGLES,Ts,Xn.disabled,Hn.disabled,Cn.backCCW,Po,Rt.id,bo.vertexBuffer,bo.indexBuffer,bo.segments,Rt.paint,ft.transform.zoom,void 0,Jd),tx.draw(ft,Et.gl.TRIANGLES,Pc?Rs:Ts,Xn.disabled,Pc||Ta.opacity<1||Ea.hasTranslucentParts?Hn.alphaBlended:Hn.unblended,Cn.backCCW,Po,Rt.id,bo.vertexBuffer,bo.indexBuffer,bo.segments,Rt.paint,ft.transform.zoom,void 0,Jd)}}}if(ft._debugParams.show3DModelFootprints&&en.size>0){const Fa=Array.from(en.keys()).sort();for(const ia of Fa){const{node:ji,mvp:mo}=en.get(ia);fN(ft,0,ji,mo)}}}()}(M,g,S,P),void De();if(Ae.type!=="model")return;const Be=Ae.getModels(),tt=[],Ye=M.transform.getFreeCameraOptions().position,ut=o.bJ([],[Ye.x,Ye.y,Ye.z],M.transform.worldSize);o.eo(ut,ut);const dt=[],jt=[];let Tt=0;for(const ft of Be){const Kt=g.getFeatureState("",ft.id),Rt={type:"Unknown",id:ft.id,properties:ft.featureProperties},Wt=S.paint.get("model-rotation").evaluate(Rt,Kt),Et=S.paint.get("model-scale").evaluate(Rt,Kt),Lt=S.paint.get("model-translation").evaluate(Rt,Kt),Vt=S.paint.get("model-opacity").evaluate(Rt,Kt);pN(S,ft.id,Kt,ft.featureProperties,ft.nodeOverrideNames,ft.nodeOverrides),zv(S,ft.id,Kt,ft.featureProperties,ft.materialOverrideNames,ft.materialOverrides),ft.nodeOverrides.size>0&&ft.computeBoundsAndApplyParent(),ft.computeModelMatrix(M,Wt,Et,Lt,ee,G,!1);const ds=o.b9([]),Zt=o.e2(ft.position.lat,M.transform.zoom),Is=o.bP([],[1,1,1/Zt]);o.bx(ds,ds,ut),tt.push({zScaleMatrix:Is,negCameraPosMatrix:ds});for(const Ns of ft.nodes)mN(M,Ns,ft.matrix,M.transform.expandedFarZProjMatrix,Tt,dt,jt,ft.materialOverrides,Vt);Tt++}if(dt.sort((ft,Kt)=>Kt.depth-ft.depth),M.renderPass!=="shadow"){if(M._debugParams.show3DModelFootprints){const ft=M.transform.projMatrix,Kt=new Map,Rt=(Et,Lt)=>{if(Et.footprint){const Vt=Et.id||Et.name||"footprint";if(!Kt.has(Vt)){const ds=o.aD([],ft,Lt);Kt.set(Vt,{node:Et,mvp:ds})}}};for(const Et of jt)Rt(Et.node,Et.modelMatrix);for(const Et of dt)Rt(Et.node,Et.modelMatrix);const Wt=Array.from(Kt.keys()).sort();for(const Et of Wt){const{node:Lt,mvp:Vt}=Kt.get(Et);fN(M,0,Lt,Vt)}}Id(M,S,dt,jt,tt),De()}else{for(const ft of jt)wb(ft.mesh,ft.nodeModelMatrix,M,S);for(const ft of dt)wb(ft.mesh,ft.nodeModelMatrix,M,S);De()}}},Hr={line:function(M,g,S){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 P=g.getVisibleCoordinates();for(const z of P){const H=g.getTile(z).getBucket(M);if(H&&(H.elevationType!=="none"?M.hasElevatedBuckets=!0:M.hasNonElevatedBuckets=!0,M.hasElevatedBuckets&&M.hasNonElevatedBuckets))break}}}else M.hasNonElevatedBuckets=!0},model:function(M,g,S){const P=g.getSource();if(!P.loaded())return;if(P.type==="vector"||P.type==="geojson")return void(S.modelManager&&S.modelManager.upload(S,Zw(S,M)));if(P.type==="batched-model"||P.type!=="model")return;const z=P.getModels();for(const H of z)H.upload(S.context)},raster:function(M,g,S){const P=g.getSource();if(!(P instanceof Vh&&P.loaded()))return;const z=M.sourceLayer||P.rasterLayerIds&&P.rasterLayerIds[0];if(!z)return;const H=M.paint.get("raster-array-band")||P.getInitialBand(z);if(H==null)return;const G=g.getIds().map(ee=>g.getTileByID(ee));for(const ee of G)ee.updateNeeded(M.id,H)&&P.prepareTile(ee,z,M.id,H)},"raster-particle":function(M,g,S){const P=g.getSource();if(!(P instanceof Vh&&P.loaded()))return;const z=M.sourceLayer||P.rasterLayerIds&&P.rasterLayerIds[0];if(!z)return;const H=M.paint.get("raster-particle-array-band")||P.getInitialBand(z);if(H==null)return;const G=g.getIds().map(ee=>g.getTileByID(ee));for(const ee of G)ee.updateNeeded(M.id,H)&&P.prepareTile(ee,z,M.id,H)}},Ln={fill:dy},La={fill:function(M,g,S,P){if(!S.layout||S.layout.get("fill-elevation-reference")==="none"||S.paint.get("fill-opacity").constantOr(1)===0)return;const z=M.context.gl,H=new Jr(z.LEQUAL,Jr.ReadOnly,M.depthRangeFor3D),G=new Xn({func:z.ALWAYS,mask:255},255,255,z.KEEP,z.KEEP,z.REPLACE),ee=M.transform.getFreeCameraOptions().position,ie=M.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const pe of P){const ye=g.getTile(pe),De=ye.getBucket(S);if(!De)continue;const Ae=De.elevatedStructures;if(!Ae||Ae.depthSegments.segments[0].primitiveLength===0)continue;const Be=Gg(pe.toUnwrapped(),ee),tt=M.translatePosMatrix(pe.projMatrix,ye,S.paint.get("fill-translate"),S.paint.get("fill-translate-anchor")),Ye=Dv(tt,Be,0,1,0);ie.draw(M,z.TRIANGLES,H,G,Hn.disabled,Cn.disabled,Ye,S.id,Ae.vertexBuffer,Ae.indexBuffer,Ae.depthSegments,S.paint,M.transform.zoom)}}};class ro{constructor(g,S,P,z,H){this.context=new qg(g,S),this.transform=P,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 G=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const ie of G)this._debugParams.enabledLayers[ie]=!0;for(const ie of G);this.occlusionParams=new z4,this.setup(),this.numSublayers=Xo.maxUnderzooming+Xo.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 Vl(this),this._wireframeDebugCache=new F4,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const ee=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,ee,g.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=z,this.maxFrontCutoffRawStart=0,this.worldview=H,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(g,S){const P=!!g&&!!g.terrain&&this.transform.projection.supportsTerrain;if(!(P||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new ly(this,g));const z=this._terrain;this.transform.elevation=P?z:null,z.update(g,this.transform,S),this.transform.elevation&&!z.enabled&&(this.transform.elevation=null)}_updateFog(g){const S=g.fog;if(!S||this.transform.projection.name==="globe"||S.getOpacity(this.transform.pitch)<1||S.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[P,z]=S.getFovAdjustedRange(this.transform._fov);if(P>z)return void(this.transform.fogCullDistSq=null);const H=P+.78*(z-P);this.transform.fogCullDistSq=H*H}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 ly(this,this.style)),this._forceTerrainMode=g}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(g,S){if(this.width=g*o.o.devicePixelRatio,this.height=S*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const P of this.style.order)this.style._mergedLayers[P].resize()}setup(){const g=this.context,S=new o.dB;S.emplaceBack(0,0),S.emplaceBack(o.an,0),S.emplaceBack(0,o.an),S.emplaceBack(o.an,o.an),this.tileExtentBuffer=g.createVertexBuffer(S,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const P=new o.dB;P.emplaceBack(0,0),P.emplaceBack(o.an,0),P.emplaceBack(0,o.an),P.emplaceBack(o.an,o.an),this.debugBuffer=g.createVertexBuffer(P,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const z=new o.dB;z.emplaceBack(-1,-1),z.emplaceBack(1,-1),z.emplaceBack(-1,1),z.emplaceBack(1,1),this.viewportBuffer=g.createVertexBuffer(z,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const H=new o.eH;H.emplaceBack(0,0,0,0),H.emplaceBack(o.an,0,o.an,0),H.emplaceBack(0,o.an,0,o.an),H.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=g.createVertexBuffer(H,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const G=new o.dC;G.emplaceBack(0,1,2),G.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=g.createIndexBuffer(G);const ee=new o.eJ;for(const pe of[0,1,3,2,0])ee.emplaceBack(pe);this.debugIndexBuffer=g.createIndexBuffer(ee),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 ie=this.context.gl;this.stencilClearMode=new Xn({func:ie.ALWAYS,mask:0},0,255,ie.ZERO,ie.ZERO,ie.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,Jr.disabled,this.stencilClearMode,Hn.disabled,Cn.disabled,Ow(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(g,S,P){if(!S||this.currentStencilSource===S.id||!g.isTileClipped()||!P||P.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let ee=!1;for(const ie of P)if(this._tileClippingMaskIDs[ie.key]===void 0){ee=!0;break}if(!ee)return}this.currentStencilSource=S.id;const z=this.context,H=z.gl;this.nextStencilID+P.length>256&&this.clearStencil(),z.setColorMode(Hn.disabled),z.setDepthMode(Jr.disabled);const G=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const ee of P){const ie=S.getTile(ee),pe=this._tileClippingMaskIDs[ee.key]=this.nextStencilID++,{tileBoundsBuffer:ye,tileBoundsIndexBuffer:De,tileBoundsSegments:Ae}=this.getTileBoundsBuffers(ie);G.draw(this,H.TRIANGLES,Jr.disabled,new Xn({func:H.ALWAYS,mask:0},pe,255,H.KEEP,H.KEEP,H.REPLACE),Hn.disabled,Cn.disabled,Ow(ee.projMatrix),"$clipping",ye,De,Ae)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const g=this.nextStencilID++,S=this.context.gl;return new Xn({func:S.NOTEQUAL,mask:255},g,255,S.KEEP,S.KEEP,S.REPLACE)}stencilModeForClipping(g){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(g);const S=this.context.gl;return new Xn({func:S.EQUAL,mask:255},this._tileClippingMaskIDs[g.key],0,S.KEEP,S.KEEP,S.REPLACE)}stencilConfigForOverlap(g){const S=this.context.gl,P=g.sort((G,ee)=>ee.overscaledZ-G.overscaledZ),z=P[P.length-1].overscaledZ,H=P[0].overscaledZ-z+1;if(H>1){this.currentStencilSource=void 0,this.nextStencilID+H>256&&this.clearStencil();const G={};for(let ee=0;eethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((g,S)=>g+S/this._fpsHistory.length,0))}render(g,S){const P=o.o.now();this._dt=P-this._timeStamp,this._timeStamp=P,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=g.map.repaint,this.style=g,this.options=S;const z=this.style._mergedLayers,H=!(!this.terrain||!this.terrain.enabled),G=()=>this.style._getOrder(H).filter(hs=>{const ss=z[hs];return!(ss.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[ss.type]});let ee=G(),ie=!1,pe=!1,ye=null,De=0,Ae=!1;for(const hs of ee){const ss=z[hs];ss.visibility!=="none"&&(ss.type==="circle"?ie=!0:ss.type==="building"?(ye=ss,++De):ss.type==="symbol"&&(ss.hasOcclusionOpacityProperties?pe=!0:ie=!0))}this.updateEmissiveMode();let Be=ee.map(hs=>z[hs]);const tt=this.style._mergedSourceCaches;this.imageManager=g.imageManager,this.modelManager=g.modelManager,this.symbolFadeChange=g.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const hs in tt){const ss=tt[hs];ss.used&&(ss.prepare(this.context),ss.getSource().usedInConflation&&++De)}let Ye=!1;for(const hs of Be)hs.isHidden(this.transform.zoom)||(hs.type==="clip"&&(Ye=!0),this.prepareLayer(hs));const ut={},dt={},jt={},Tt={},ft={};for(const hs in tt){const ss=tt[hs];ut[hs]=ss.getVisibleCoordinates(),dt[hs]=ut[hs].slice().reverse(),jt[hs]=ss.getVisibleCoordinates(!0).reverse(),Tt[hs]=ss.getShadowCasterCoordinates(),ft[hs]=ss.sortCoordinatesByDistance(ut[hs])}const Kt=hs=>{const ss=this.style.getLayerSourceCache(hs);return ss&&ss.used?ss.getSource():null};if(De||Ye||this._clippingActiveLastFrame){const hs=[],ss=[];let Ts=0;for(const Rs of Be)this.isSourceForClippingOrConflation(Rs,Kt(Rs))&&(hs.push(Rs),ss.push(Ts)),Ts++;if(hs&&(Ye||hs.length>1)||this._clippingActiveLastFrame){Ye=!1;const Rs=[];for(let qs=0;qs0){const Rs=Kt(ss);Rs&&(this.minCutoffZoom=Math.max(Rs.minzoom,this.minCutoffZoom)),ss.minzoom&&(this.minCutoffZoom=Math.max(ss.minzoom,this.minCutoffZoom))}ss.is3D(H)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=hs),this._lastOcclusionLayer=hs)}const Rt=this.style&&this.style.fog;Rt?(this._fogVisible=Rt.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Rt.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(jt),this.opaquePassCutoff=0,ee=G(),Be=ee.map(hs=>z[hs]));const Wt=this._shadowRenderer;if(Wt){Wt.updateShadowParameters(this.transform,this.style.directionalLight);for(const hs in tt)for(const ss of ut[hs]){let Ts={min:0,max:0};this.terrain&&(Ts=this.terrain.getMinMaxForTile(ss)||Ts),Wt.addShadowReceiver(ss.toUnwrapped(),Ts.min,Ts.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 EM(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const Et=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Lt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(Et&&!this._snow&&(this._snow=new ns(this)),!Et&&this._snow&&(this._snow.destroy(),delete this._snow),Lt&&!this._rain&&(this._rain=new Je(this)),!Lt&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),ye){this.buildingTileBorderManager||(this.buildingTileBorderManager=new Jh);const hs=this.style.getLayerSourceCache(ye);this.buildingTileBorderManager.updateBorders(hs,ye)}if(!Ge.has(this.context.gl))return;this.renderPass="offscreen";for(const hs of Be){const ss=g.getLayerSourceCache(hs);if(!hs.hasOffscreenPass()||hs.isHidden(this.transform.zoom))continue;const Ts=ss?dt[ss.id]:void 0;(hs.type==="custom"||hs.type==="raster"||hs.type==="raster-particle"||hs.isSky()||Ts&&Ts.length)&&this.renderLayer(this,ss,hs,Ts)}this.depthRangeFor3D=[0,1-(Be.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Tt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Vt=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),ds=(()=>{if(S.showOverdrawInspector)return o.aq.black;const hs=this.style.fog;if(hs&&this.transform.projection.supportsFog){const ss=this.style.getLut(hs.scope);if(!Vt){const Ts=hs.properties.get("color-use-theme")==="none",Rs=hs.properties.get("color").toNonPremultipliedRenderColor(Ts?null:ss).toArray01();return new o.aq(...Rs)}if(Vt){const Ts=hs.properties.get("space-color-use-theme")==="none",Rs=hs.properties.get("space-color").toNonPremultipliedRenderColor(Ts?null:ss).toArray01();return new o.aq(...Rs)}}return o.aq.transparent})();if(this.context.clear({color:ds,depth:1}),this.clearStencil(),this._showOverdrawInspector=S.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Vt&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=ee.length-1;this.currentLayer>=0;this.currentLayer--){const hs=Be[this.currentLayer],ss=g.getLayerSourceCache(hs);if(hs.isSky())continue;const Ts=ss?(hs.is3D(H)?ft:dt)[ss.id]:void 0;this._renderTileClippingMasks(hs,ss,Ts),this.renderLayer(this,ss,hs,Ts)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Vt&&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 Ts=this.currentLayer;this.depthOcclusion=!0;for(const Rs of this.layersWithOcclusionOpacity){this.currentLayer=Rs;const qs=Be[this.currentLayer],Cr=g.getLayerSourceCache(qs),br=Cr?dt[Cr.id]:void 0;this.terrain||this._renderTileClippingMasks(qs,Cr,Cr?ut[Cr.id]:void 0),this.renderLayer(this,Cr,qs,br)}this.depthOcclusion=!1,this.currentLayer=Ts,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 hs=null;Be.forEach(ss=>{const Ts=g.getLayerSourceCache(ss);Ts&&!ss.isHidden(this.transform.zoom)&&Ts.getVisibleCoordinates().length&&(!hs||hs.getSource().maxzoom0?S.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(g,S,P){const z=P===void 0?this.terrain&&this.terrain.renderingToTexture:P,H=[];return this.style&&this.style.enable3dLights()&&(g==="globeRaster"||g==="terrainRaster"?(H.push("LIGHTING_3D_MODE"),H.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):z||H.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(H.push("TERRAIN"),this.linearFloatFilteringSupported()&&H.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&H.push("GLOBE"),!this._fogVisible||z||S!==void 0&&!S||H.push("FOG"),z&&H.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&H.push("OVERDRAW_INSPECTOR"),H}getOrCreateProgram(g,S){this.cache=this.cache||{};const P=S&&S.defines||[],z=S&&S.config,H=this.currentGlobalDefines(g,S&&S.overrideFog,S&&S.overrideRtt).concat(P),G=Yc.cacheKey(_4[g],g,H,z);return this.cache[G]||(this.cache[G]=new Yc(this.context,g,_4[g],z,gb[g],H)),this.cache[G]}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,S){if(this.style.enable3dLights()){const P=this.style.directionalLight,z=this.style.ambientLight;if(P&&z){const H=((G,ee,ie)=>{const pe=G.properties.get("direction"),ye=G.properties.get("color-use-theme")==="none",De=G.properties.get("color").toNonPremultipliedRenderColor(ye?null:ie.getLut(G.scope)).toArray01(),Ae=G.properties.get("intensity"),Be=ee.properties.get("color-use-theme")==="none",tt=ee.properties.get("color").toNonPremultipliedRenderColor(Be?null:ie.getLut(ee.scope)).toArray01(),Ye=ee.properties.get("intensity"),ut=[pe.x,pe.y,pe.z],dt=o.dD(tt,Ye),jt=o.dD(De,Ae);return{u_lighting_ambient_color:dt,u_lighting_directional_dir:ut,u_lighting_directional_color:jt,u_ground_radiance:ub(ut,jt,dt)}})(P,z,this.style);S.setLightsUniformValues(g,H)}}}uploadCommonUniforms(g,S,P,z,H){if(this.uploadCommonLightUniforms(g,S),this.terrain&&this.terrain.renderingToTexture)return;const G=this.style.fog;if(G){const ee=G.getOpacity(this.transform.pitch),ie=((pe,ye,De,Ae,Be,tt,Ye,ut,dt,jt,Tt,ft)=>{const Kt=pe.transform,Rt=ye.properties.get("color-use-theme")==="none",Wt=ye.properties.get("color").toNonPremultipliedRenderColor(Rt?null:pe.style.getLut(ye.scope)).toArray01();Wt[3]=Ae;const Et=pe.frameCounter/1e3%1,[Lt,Vt]=ye.properties.get("vertical-range");return{u_fog_matrix:De?Kt.calculateFogTileMatrix(De):ft||pe.identityMat,u_fog_range:ye.getFovAdjustedRange(Kt._fov),u_fog_color:Wt,u_fog_horizon_blend:ye.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Lt,Vt),Vt],u_fog_temporal_offset:Et,u_frustum_tl:Be,u_frustum_tr:tt,u_frustum_br:Ye,u_frustum_bl:ut,u_globe_pos:dt,u_globe_radius:jt,u_viewport:Tt,u_globe_transition:o.al(Kt.zoom),u_is_globe:+(Kt.projection.name==="globe")}})(this,G,P,ee,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],z);S.setFogUniformValues(g,ie)}H&&S.setCutoffUniformValues(g,H.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,S=g.createTexture();return g.bindTexture(g.TEXTURE_2D,S),g.copyTexImage2D(g.TEXTURE_2D,0,g.RGBA,0,0,g.drawingBufferWidth,g.drawingBufferHeight,0),S}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,S=this._backgroundTiles={},P=this.transform.coveringTiles({tileSize:512});for(const z of P)S[z.key]=g[z.key]||new o.b0(z,512,this.transform.tileZoom,this,void 0,this.worldview);return S}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(g,S){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")&&(!S||S.type!=="batched-model")))}isTileAffectedByFog(g){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let S=this._cachedTileFogOpacities[g.key];return S||(this._cachedTileFogOpacities[g.key]=S=this.style.fog.getOpacityForTile(g)),S[0]>=wn||S[1]>=wn}setupDepthForOcclusion(g,S,P){const z=this.context,H=z.gl,G=!!P;var ee;P||(P={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),z.activeTexture.set(H.TEXTURE3),g&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(H.NEAREST,H.CLAMP_TO_EDGE),P.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],P.u_depth_range_unpack=[2/((ee=this.depthRangeFor3D)[1]-ee[0]),-1-2*ee[0]/(ee[1]-ee[0])],P.u_occluder_half_size=.5*this.occlusionParams.occluderSize,P.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(H.NEAREST,H.CLAMP_TO_EDGE),z.activeTexture.set(H.TEXTURE0),G||S.setTerrainUniformValues(z,P)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const g=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=g?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function ga(M,g){let S=!1,P=null;const z=()=>{P=null,S&&(M(),P=setTimeout(z,g),S=!1)};return()=>(S=!0,P||z(),P)}class oc{constructor(g){this._hashName=g&&encodeURIComponent(g),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=ga(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 S=no(g);if(this._hashName){const P=this._hashName;let z=!1;const H=location.hash.slice(1).split("&").map(G=>{const ee=G.split("=")[0];return ee===P?(z=!0,`${ee}=${S}`):G}).filter(G=>G);return z||H.push(`${P}=${S}`),`#${H.join("&")}`}return`#${S}`}_getCurrentHash(){const g=location.hash.replace("#","");if(this._hashName){let S;return g.split("&").map(P=>P.split("=")).forEach(P=>{P[0]===this._hashName&&(S=P)}),(S&&S[1]||"").split("/")}return g.split("/")}_onHashChange(){const g=this._map;if(!g)return!1;const S=this._getCurrentHash();if(S.length>=3&&!S.some(P=>isNaN(Number(P)))){const P=g.dragRotate.isEnabled()&&g.touchZoomRotate.isEnabled()?+(S[3]||0):g.getBearing();return g.jumpTo({center:[+S[2],+S[1]],zoom:+S[0],bearing:P,pitch:+(S[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function no(M,g){const S=M.getCenter(),P=Math.round(100*M.getZoom())/100,z=Math.ceil((P*Math.LN2+Math.log(512/360/.5))/Math.LN10),H=Math.pow(10,z),G=Math.round(S.lng*H)/H,ee=Math.round(S.lat*H)/H,ie=M.getBearing(),pe=M.getPitch();let ye=g?`/${G}/${ee}/${P}`:`${P}/${ee}/${G}`;return(ie||pe)&&(ye+="/"+Math.round(10*ie)/10),pe&&(ye+=`/${Math.round(pe)}`),ye}const eh={linearity:.3,easing:o.eN(0,0,.3,1)},Cf=Object.assign({deceleration:2500,maxSpeed:1400},eh),Fr=Object.assign({deceleration:20,maxSpeed:1400},eh),Us=Object.assign({deceleration:1e3,maxSpeed:360},eh),rr=Object.assign({deceleration:1e3,maxSpeed:90},eh);class Na{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,S=o.o.now();for(;g.length>0&&S-g[0].time>160;)g.shift()}_onMoveEnd(g){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const S={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:H}of this._inertiaBuffer)S.zoom+=H.zoomDelta||0,S.bearing+=H.bearingDelta||0,S.pitch+=H.pitchDelta||0,H.panDelta&&S.pan._add(H.panDelta),H.around&&(S.around=H.around),H.pinchAround&&(S.pinchAround=H.pinchAround);const P=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,z={};if(S.pan.mag()){const H=Ai(S.pan.mag(),P,Object.assign({},Cf,g||{}));z.offset=S.pan.mult(H.amount/S.pan.mag()),z.center=this._map.transform.center,Ra(z,H)}if(S.zoom){const H=Ai(S.zoom,P,Fr);z.zoom=this._map.transform.zoom+H.amount,Ra(z,H)}if(S.bearing){const H=Ai(S.bearing,P,Us);z.bearing=this._map.transform.bearing+o.aC(H.amount,-179,179),Ra(z,H)}if(S.pitch){const H=Ai(S.pitch,P,rr);z.pitch=this._map.transform.pitch+H.amount,Ra(z,H)}if(z.zoom||z.bearing){const H=S.pinchAround===void 0?S.around:S.pinchAround;z.around=H?this._map.unproject(H):this._map.getCenter()}return this.clear(),z.noMoveStart=!0,z}}function Ra(M,g){(!M.duration||M.durationS.unproject(ie)),ee=H.reduce((ie,pe,ye,De)=>ie.add(pe.div(De.length)),new o.P(0,0));super(g,{points:H,point:ee,lngLats:G,lngLat:S.unproject(ee),originalEvent:P}),this._defaultPrevented=!1}}class Pd extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(g,S){super("wheel",{originalEvent:S}),this._defaultPrevented=!1}}class Qo{constructor(g,S){this._map=g,this._clickTolerance=S.clickTolerance}reset(){this._mousedownPos=void 0}wheel(g){return this._firePreventable(new Pd(this._map,g))}mousedown(g,S){return this._mousedownPos=S,this._firePreventable(new Ja(g.type,this._map,g))}mouseup(g){this._map.fire(new Ja(g.type,this._map,g))}preclick(g){const S=new MouseEvent("preclick",g);this._map.fire(new Ja(S.type,this._map,S))}click(g,S){this._mousedownPos&&this._mousedownPos.dist(S)>=this._clickTolerance||(this.preclick(g),this._map.fire(new Ja(g.type,this._map,g)))}dblclick(g){return this._firePreventable(new Ja(g.type,this._map,g))}mouseover(g){this._map.fire(new Ja(g.type,this._map,g))}mouseout(g){this._map.fire(new Ja(g.type,this._map,g))}touchstart(g){return this._firePreventable(new eo(g.type,this._map,g))}touchmove(g){this._map.fire(new eo(g.type,this._map,g))}touchend(g){this._map.fire(new eo(g.type,this._map,g))}touchcancel(g){this._map.fire(new eo(g.type,this._map,g))}_firePreventable(g){if(this._map.fire(g),g.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Vx{constructor(g){this._map=g}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(g){this._map.fire(new Ja(g.type,this._map,g))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Ja("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(g){this._delayContextMenu?this._contextMenuEvent=g:this._map.fire(new Ja(g.type,this._map,g)),this._map.listens("contextmenu")&&g.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class $4{constructor(g,S){this._map=g,this._el=g.getCanvasContainer(),this._container=g.getContainer(),this._clickTolerance=S.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(g,S){this.isEnabled()&&g.shiftKey&&g.button===0&&(A(),this._startPos=this._lastPos=S,this._active=!0)}mousemoveWindow(g,S){if(!this._active)return;const P=S,z=this._startPos,H=this._lastPos;if(!z||!H||H.equals(P)||!this._box&&P.dist(z){this._box&&(this._box.style.transform=`translate(${G}px,${ie}px)`,this._box.style.width=ee-G+"px",this._box.style.height=pe-ie+"px")})}mouseupWindow(g,S){if(!this._active)return;const P=this._startPos,z=S;if(P&&g.button===0){if(this.reset(),R(),P.x!==z.x||P.y!==z.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:g})),{cameraAnimation:H=>H.fitScreenCoordinates(P,z,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,S){return this._map.fire(new o.C(g,{originalEvent:S}))}}function U4(M,g){const S={};for(let P=0;Pthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=g.timeStamp),P.length===this.numTouches&&(this.centroid=function(z){const H=new o.P(0,0);for(const G of z)H._add(G);return H.div(z.length)}(S),this.touches=U4(P,S)))}touchmove(g,S,P){if(this.aborted||!this.centroid)return;const z=U4(P,S);for(const H in this.touches){const G=z[H];(!G||G.dist(this.touches[H])>30)&&(this.aborted=!0)}}touchend(g,S,P){if((!this.centroid||g.timeStamp-this.startTime>500)&&(this.aborted=!0),P.length===0){const z=!this.aborted&&this.centroid;if(this.reset(),z)return z}}}class fy{constructor(g){this.singleTap=new Hx(g),this.numTaps=g.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(g,S,P){this.singleTap.touchstart(g,S,P)}touchmove(g,S,P){this.singleTap.touchmove(g,S,P)}touchend(g,S,P){const z=this.singleTap.touchend(g,S,P);if(z){const H=g.timeStamp-this.lastTime<500,G=!this.lastTap||this.lastTap.dist(z)<30;if(H&&G||this.reset(),this.count++,this.lastTime=g.timeStamp,this.lastTap=z,this.count===this.numTaps)return this.reset(),z}}}class vN{constructor(){this._zoomIn=new fy({numTouches:1,numTaps:2}),this._zoomOut=new fy({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(g,S,P){this._zoomIn.touchstart(g,S,P),this._zoomOut.touchstart(g,S,P)}touchmove(g,S,P){this._zoomIn.touchmove(g,S,P),this._zoomOut.touchmove(g,S,P)}touchend(g,S,P){const z=this._zoomIn.touchend(g,S,P),H=this._zoomOut.touchend(g,S,P);return z?(this._active=!0,g.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:G=>G.easeTo({duration:300,zoom:G.getZoom()+1,around:G.unproject(z)},{originalEvent:g})}):H?(this._active=!0,g.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:G=>G.easeTo({duration:300,zoom:G.getZoom()-1,around:G.unproject(H)},{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 MM=0,wD=2,jD={[MM]:1,[wD]:2},$v={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class q4{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,S){return!1}_move(g,S){return{}}mousedown(g,S){if(this._lastPoint)return;const P=B(g);this._correctButton(g,P)&&(this._lastPoint=S,this._eventButton=P)}mousemoveWindow(g,S){const P=this._lastPoint;if(P){if(g.preventDefault(),this._eventButton!=null&&function(z,H){const G=jD[H];return z.buttons===void 0||(z.buttons&G)!==G}(g,this._eventButton))this.reset();else if(this._moved||!(S.dist(P)0&&(this._active=!0);const z=U4(P,S),H=new o.P(0,0),G=new o.P(0,0);let ee=0;for(const pe in z){const ye=z[pe],De=this._touches[pe];De&&(H._add(ye),G._add(ye.sub(De)),ee++,z[pe]=ye)}if(this._touches=z,ee{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class H4{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(g){}_move(g,S,P){return{}}touchstart(g,S,P){this._firstTwoTouches||P.length<2||(this._firstTwoTouches=[P[0].identifier,P[1].identifier],this._start([S[0],S[1]]))}touchmove(g,S,P){const z=this._firstTwoTouches;if(!z)return;g.preventDefault();const[H,G]=z,ee=Gl(P,S,H),ie=Gl(P,S,G);if(!ee||!ie)return;const pe=this._aroundCenter?null:ee.add(ie).div(2);return this._move([ee,ie],pe,g)}touchend(g,S,P){if(!this._firstTwoTouches)return;const[z,H]=this._firstTwoTouches,G=Gl(P,S,z),ee=Gl(P,S,H);G&&ee||(this._active&&R(),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 Gl(M,g,S){for(let P=0;PMath.abs(M.x)}class SD extends H4{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,G4(g[0].sub(g[1]))&&(this._valid=!1)}_move(g,S,P){const z=this._lastPoints;if(!z)return;const H=g[0].sub(z[0]),G=g[1].sub(z[1]);return this._map._cooperativeGestures&&!o.eO()&&P.touches.length<3||(this._valid=this.gestureBeginsVertically(H,G,P.timeStamp),!this._valid)?void 0:(this._lastPoints=g,this._active=!0,{pitchDelta:(H.y+G.y)/2*-.5})}gestureBeginsVertically(g,S,P){if(this._valid!==void 0)return this._valid;const z=g.mag()>=2,H=S.mag()>=2;if(!z&&!H)return;if(!z||!H)return this._firstMove==null&&(this._firstMove=P),P-this._firstMove<100&&void 0;const G=g.y>0==S.y>0;return G4(g)&&G4(S)&&G}}const CD={panStep:100,bearingStep:15,pitchStep:10};class ej{constructor(){const g=CD;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 S=0,P=0,z=0,H=0,G=0;switch(g.keyCode){case 61:case 107:case 171:case 187:S=1;break;case 189:case 109:case 173:S=-1;break;case 37:g.shiftKey?P=-1:(g.preventDefault(),H=-1);break;case 39:g.shiftKey?P=1:(g.preventDefault(),H=1);break;case 38:g.shiftKey?z=1:(g.preventDefault(),G=-1);break;case 40:g.shiftKey?z=-1:(g.preventDefault(),G=1);break;default:return}return this._rotationDisabled&&(P=0,z=0),{cameraAnimation:ee=>{const ie=ee.getZoom();ee.easeTo({duration:300,easeId:"keyboardHandler",easing:TD,zoom:S?Math.round(ie)+S*(g.shiftKey?2:1):ie,bearing:ee.getBearing()+P*this._bearingStep,pitch:ee.getPitch()+z*this._pitchStep,offset:[-H*this._panStep,-G*this._panStep],center:ee.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 TD(M){return M*(2-M)}const tj=4.000244140625,ED=1/450;class DM{constructor(g,S){this._map=g,this._el=g.getCanvasContainer(),this._handler=S,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=ED,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 S=g.deltaMode===WheelEvent.DOM_DELTA_LINE?40*g.deltaY:g.deltaY;const P=o.o.now(),z=P-(this._lastWheelEventTime||0);this._lastWheelEventTime=P,S!==0&&S%tj===0?this._type="wheel":S!==0&&Math.abs(S)<4?this._type="trackpad":z>400?(this._type=null,this._lastValue=S,this._timeout=window.setTimeout(this._onTimeout,40,g)):this._type||(this._type=Math.abs(z*S)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,S+=this._lastValue)),g.shiftKey&&S&&(S/=4),this._type&&(this._lastWheelEvent=g,this._delta-=S,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 S=F(this._el,g);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:S,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 S=()=>g._terrainEnabled()&&this._aroundCoord?g.computeZoomRelativeTo(this._aroundCoord):g.zoom;if(this._delta!==0){const pe=this._type==="wheel"&&Math.abs(this._delta)>tj?this._wheelZoomRate:this._defaultZoomRate;let ye=2/(1+Math.exp(-Math.abs(this._delta*pe)));this._delta<0&&ye!==0&&(ye=1/ye);const De=S(),Ae=Math.pow(2,De),Be=typeof this._targetZoom=="number"?g.zoomScale(this._targetZoom):Ae;this._targetZoom=Math.min(g.maxZoom,Math.max(g.minZoom,g.scaleZoom(Be*ye))),this._type==="wheel"&&(this._startZoom=De,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const P=typeof this._targetZoom=="number"?this._targetZoom:S(),z=this._startZoom,H=this._easing;let G,ee=!1;if(this._type==="wheel"&&z&&H){const pe=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),ye=H(pe);G=o.am(z,P,ye),pe<1?this._frameId||(this._frameId=!0):ee=!0}else G=P,ee=!0;this._active=!0,ee&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let ie=G-S();return ie*this._lastDelta<0&&(ie=0),{noInertia:!0,needsRenderFrame:!ee,zoomDelta:ie,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(g){let S=o.eP;if(this._prevEase){const P=this._prevEase,z=(o.o.now()-P.start)/P.duration,H=P.easing(z+.01)-P.easing(z),G=.27/Math.sqrt(H*H+1e-4)*.01,ee=Math.sqrt(.0729-G*G);S=o.eN(G,ee,.25,1)}return this._prevEase={start:o.o.now(),duration:g,easing:S},S}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 RM{constructor(g,S){this._clickZoom=g,this._tapZoom=S}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 OM{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(g,S){return g.preventDefault(),{cameraAnimation:P=>{P.easeTo({duration:300,zoom:P.getZoom()+(g.shiftKey?-1:1),around:P.unproject(S)},{originalEvent:g})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class h${constructor(){this._tap=new fy({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,S,P){this._swipePoint||(this._tapTime&&g.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?P.length>0&&(this._swipePoint=S[0],this._swipeTouch=P[0].identifier):this._tap.touchstart(g,S,P))}touchmove(g,S,P){if(this._tapTime){if(this._swipePoint){if(P[0].identifier!==this._swipeTouch)return;const z=S[0],H=z.y-this._swipePoint.y;return this._swipePoint=z,g.preventDefault(),this._active=!0,{zoomDelta:H/128}}}else this._tap.touchmove(g,S,P)}touchend(g,S,P){this._tapTime?this._swipePoint&&P.length===0&&this.reset():this._tap.touchend(g,S,P)&&(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 AD{constructor(g,S,P){this._el=g,this._mousePan=S,this._touchPan=P}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 m${constructor(g,S,P){this._pitchWithRotate=g.pitchWithRotate,this._mouseRotate=S,this._mousePitch=P}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 f${constructor(g,S,P,z){this._el=g,this._touchZoom=S,this._touchRotate=P,this._tapDragZoom=z,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 W4=M=>M.zoom||M.drag||M.pitch||M.rotate;class p$ extends o.C{}class x${constructor(){this.constants=[1,1,.01],this.radius=0}setup(g,S){const P=o.ax([],S,g);this.radius=o.ai(P[2]<0?o.eR([],P,this.constants):[P[0],P[1],0])}projectRay(g){o.eR(g,g,this.constants),o.ay(g,g),o.eS(g,g,this.constants);const S=o.bJ([],g,this.radius);if(S[2]>0){const P=o.bJ([],[0,0,1],o.bi(S,[0,0,1])),z=o.bJ([],o.ay([],[S[0],S[1],0]),this.radius),H=o.cT([],S,o.bJ([],o.ax([],o.cT([],z,P),S),2));S[0]=H[0],S[1]=H[1]}return S}}function K4(M){return M.panDelta&&M.panDelta.mag()||M.zoomDelta||M.bearingDelta||M.pitchDelta}class g${constructor(g,S){this._map=g,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Na(g),this._bearingSnap=S.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new x$,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(S),o.aZ(["handleEvent","handleWindowEvent"],this);const P=this._el;this._listeners=[[P,"touchstart",{passive:!0}],[P,"touchmove",{passive:!1}],[P,"touchend",void 0],[P,"touchcancel",void 0],[P,"mousedown",void 0],[P,"mousemove",void 0],[P,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[P,"mouseover",void 0],[P,"mouseout",void 0],[P,"dblclick",void 0],[P,"click",void 0],[P,"keydown",{capture:!1}],[P,"keyup",void 0],[P,"wheel",{passive:!1}],[P,"contextmenu",void 0],[window,"blur",void 0]];for(const[z,H,G]of this._listeners){const ee=z===document?this.handleWindowEvent:this.handleEvent;z.addEventListener(H,ee,G)}}destroy(){for(const[g,S,P]of this._listeners){const z=g===document?this.handleWindowEvent:this.handleEvent;g.removeEventListener(S,z,P)}}_addDefaultHandlers(g){const S=this._map,P=S.getCanvasContainer();this._add("mapEvent",new Qo(S,g));const z=S.boxZoom=new $4(S,g);this._add("boxZoom",z);const H=new vN,G=new OM;S.doubleClickZoom=new RM(G,H),this._add("tapZoom",H),this._add("clickZoom",G);const ee=new h$;this._add("tapDragZoom",ee);const ie=S.touchPitch=new SD(S);this._add("touchPitch",ie);const pe=new IM(g),ye=new V4(g);S.dragRotate=new m$(g,pe,ye),this._add("mouseRotate",pe,["mousePitch"]),this._add("mousePitch",ye,["mouseRotate"]);const De=new Gx(g),Ae=new ND(S,g);S.dragPan=new AD(P,De,Ae),this._add("mousePan",De),this._add("touchPan",Ae,["touchZoom","touchRotate"]);const Be=new Jw,tt=new kD;S.touchZoomRotate=new f$(P,tt,Be,ee),this._add("touchRotate",Be,["touchPan","touchZoom"]),this._add("touchZoom",tt,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Vx(S));const Ye=S.scrollZoom=new DM(S,this);this._add("scrollZoom",Ye,["mousePan"]);const ut=S.keyboard=new ej;this._add("keyboard",ut);for(const dt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])g.interactive&&g[dt]&&S[dt].enable(g[dt])}_add(g,S,P){this._handlers.push({handlerName:g,handler:S,allowed:P}),this._handlersById[g]=S}stop(g){if(!this._updatingCamera){for(const{handler:S}of this._handlers)S.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!!W4(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(g,S,P){for(const z in g)if(z!==P&&(!S||S.indexOf(z)<0))return!0;return!1}handleWindowEvent(g){this.handleEvent(g,`${g.type}Window`)}_getMapTouches(g){const S=[];for(const P of g)this._el.contains(P.target)&&S.push(P);return S}handleEvent(g,S){this._updatingCamera=!0;const P=g.type==="renderFrame",z=P?void 0:g,H={needsRenderFrame:!1},G={},ee={},ie=g.touches?this._getMapTouches(g.touches):void 0,pe=ie?O(this._el,ie):P?void 0:F(this._el,g);for(const{handlerName:Ae,handler:Be,allowed:tt}of this._handlers){if(!Be.isEnabled())continue;let Ye;this._blockedByActive(ee,tt,Ae)?Be.reset():Be[S||g.type]&&(Ye=Be[S||g.type](g,pe,ie),this.mergeHandlerResult(H,G,Ye,Ae,z),Ye&&Ye.needsRenderFrame&&this._triggerRenderFrame()),(Ye||Be.isActive())&&(ee[Ae]=Be)}const ye={};for(const Ae in this._previousActiveHandlers)ee[Ae]||(ye[Ae]=z);this._previousActiveHandlers=ee,(Object.keys(ye).length||K4(H))&&(this._changes.push([H,G,ye]),this._triggerRenderFrame()),(Object.keys(ee).length||K4(H))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:De}=H;De&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],De(this._map))}mergeHandlerResult(g,S,P,z,H){if(!P)return;Object.assign(g,P);const G={handlerName:z,originalEvent:P.originalEvent||H};P.zoomDelta!==void 0&&(S.zoom=G),P.panDelta!==void 0&&(S.drag=G),P.pitchDelta!==void 0&&(S.pitch=G),P.bearingDelta!==void 0&&(S.rotate=G)}_applyChanges(){const g={},S={},P={};for(const[z,H,G]of this._changes)z.panDelta&&(g.panDelta=(g.panDelta||new o.P(0,0))._add(z.panDelta)),z.zoomDelta&&(g.zoomDelta=(g.zoomDelta||0)+z.zoomDelta),z.bearingDelta&&(g.bearingDelta=(g.bearingDelta||0)+z.bearingDelta),z.pitchDelta&&(g.pitchDelta=(g.pitchDelta||0)+z.pitchDelta),z.around!==void 0&&(g.around=z.around),z.aroundCoord!==void 0&&(g.aroundCoord=z.aroundCoord),z.pinchAround!==void 0&&(g.pinchAround=z.pinchAround),z.noInertia&&(g.noInertia=z.noInertia),Object.assign(S,H),Object.assign(P,G);this._updateMapTransform(g,S,P),this._changes=[]}_updateMapTransform(g,S,P){const z=this._map,H=z.transform,G=jt=>[jt.x,jt.y,jt.z];if((()=>{const jt=this._eventsInProgress.drag;return jt&&!this._handlersById[jt.handlerName].isActive()})()&&!K4(g)){const jt=H.zoom;H.cameraElevationReference="sea",this._originalZoom!=null&&H._orthographicProjectionAtLowPitch&&H.projection.name!=="globe"&&H.pitch===0?(H.cameraElevationReference="ground",H.zoom=this._originalZoom):(H.recenterOnTerrain(),H.cameraElevationReference="ground"),jt!==H.zoom&&this._map._update(!0)}if(H._isCameraConstrained&&z._stop(!0),!K4(g))return void this._fireEvents(S,P,!0);let{panDelta:ee,zoomDelta:ie,bearingDelta:pe,pitchDelta:ye,around:De,aroundCoord:Ae,pinchAround:Be}=g;H._isCameraConstrained&&(ie>0&&(ie=0),H._isCameraConstrained=!1),Be!==void 0&&(De=Be),(ie||(jt=>S[jt]&&!this._eventsInProgress[jt])("drag"))&&De&&(this._dragOrigin=G(H.pointCoordinate3D(De)),this._originalZoom=H.zoom,this._trackingEllipsoid.setup(H._camera.position,this._dragOrigin)),H.cameraElevationReference="sea",z._stop(!0),De=De||z.transform.centerPoint,pe&&(H.bearing+=pe),ye&&(H.pitch+=ye),H._updateCameraState();const tt=[0,0,0];if(ee)if(H.projection.name==="mercator"){const jt=this._trackingEllipsoid.projectRay(H.screenPointToMercatorRay(De).dir),Tt=this._trackingEllipsoid.projectRay(H.screenPointToMercatorRay(De.sub(ee)).dir);tt[0]=Tt[0]-jt[0],tt[1]=Tt[1]-jt[1]}else{const jt=H.pointCoordinate(De);if(H.projection.name==="globe"){ee=ee.rotate(-H.angle);const Tt=H._pixelsPerMercatorPixel/H.worldSize;tt[0]=-ee.x*o.eQ(o.bV(jt.y))*Tt,tt[1]=-ee.y*o.eQ(H.center.lat)*Tt}else{const Tt=H.pointCoordinate(De.sub(ee));jt&&Tt&&(tt[0]=Tt.x-jt.x,tt[1]=Tt.y-jt.y)}}const Ye=H.zoom,ut=[0,0,0];if(ie){const jt=G(Ae||H.pointCoordinate3D(De)),Tt={dir:o.ay([],o.ax([],jt,H._camera.position))};if(Tt.dir[2]<0){const ft=H.zoomDeltaToMovement(jt,ie);o.bJ(ut,Tt.dir,ft)}}const dt=o.cT(tt,tt,ut);H._translateCameraConstrained(dt),ie&&Math.abs(H.zoom-Ye)>1e-4&&H.recenterOnTerrain(),H.cameraElevationReference="ground",this._map._update(),g.noInertia||this._inertia.record(g),this._fireEvents(S,P,!0)}_fireEvents(g,S,P){const z=W4(this._eventsInProgress),H=W4(g),G={};for(const ye in g){const{originalEvent:De}=g[ye];this._eventsInProgress[ye]||(G[`${ye}start`]=De),this._eventsInProgress[ye]=g[ye]}!z&&H&&this._fireEvent("movestart",H.originalEvent);for(const ye in G)this._fireEvent(ye,G[ye]);H&&this._fireEvent("move",H.originalEvent);for(const ye in g){const{originalEvent:De}=g[ye];this._fireEvent(ye,De)}const ee={};let ie;for(const ye in this._eventsInProgress){const{handlerName:De,originalEvent:Ae}=this._eventsInProgress[ye];this._handlersById[De].isActive()||(delete this._eventsInProgress[ye],ie=S[De]||Ae,ee[`${ye}end`]=ie)}for(const ye in ee)this._fireEvent(ye,ee[ye]);const pe=W4(this._eventsInProgress);if(P&&(z||H)&&!pe){this._updatingCamera=!0;const ye=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),De=Ae=>Ae!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new p$("renderFrame",{timeStamp:g})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const MD="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class y$ extends o.E{constructor(g,S){super(),this._moving=!1,this._zooming=!1,this.transform=g,this._bearingSnap=S.bearingSnap,this._respectPrefersReducedMotion=S.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(g,S){return this.jumpTo({center:g},S)}panBy(g,S,P){return g=o.P.convert(g).mult(-1),this.panTo(this.transform.center,Object.assign({offset:g},S),P)}panTo(g,S,P){return this.easeTo(Object.assign({center:g},S),P)}getZoom(){return this.transform.zoom}setZoom(g,S){return this.jumpTo({zoom:g},S),this}zoomTo(g,S,P){return this.easeTo(Object.assign({zoom:g},S),P)}zoomIn(g,S){return this.zoomTo(this.getZoom()+1,g,S),this}zoomOut(g,S){return this.zoomTo(this.getZoom()-1,g,S),this}getBearing(){return this.transform.bearing}setBearing(g,S){return this.jumpTo({bearing:g},S),this}getPadding(){return this.transform.padding}setPadding(g,S){return this.jumpTo({padding:g},S),this}rotateTo(g,S,P){return this.easeTo(Object.assign({bearing:g},S),P)}resetNorth(g,S){return this.rotateTo(0,Object.assign({duration:1e3},g),S),this}resetNorthPitch(g,S){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},g),S),this}snapToNorth(g,S){return Math.abs(this.getBearing())g.aspect?P/(2*Math.tan(.5*g.fovX)*g.aspect):z/(2*Math.tan(.5*g.fovY)*g.aspect)}_cameraForBoundsOnGlobe(g,S,P,z,H,G){const ee=g.clone(),ie=this._extendCameraOptions(G);ee.bearing=z,ee.pitch=H;const pe=o.aU.convert(S),ye=o.aU.convert(P),De=.5*(pe.lat+ye.lat),Ae=.5*(pe.lng+ye.lng),Be=o.eT(De,Ae),tt=o.ay([],Be),Ye=o.ay([],o.bh([],tt,[0,1,0])),ut=o.bh([],Ye,tt),dt=[Ye[0],Ye[1],Ye[2],0,ut[0],ut[1],ut[2],0,tt[0],tt[1],tt[2],0,0,0,0,1],jt=[Be,o.eT(pe.lat,pe.lng),o.eT(ye.lat,pe.lng),o.eT(ye.lat,ye.lng),o.eT(pe.lat,ye.lng),o.eT(De,pe.lng),o.eT(De,ye.lng),o.eT(pe.lat,Ae),o.eT(ye.lat,Ae)];let Tt=o.cU.fromPoints(jt.map(Rs=>[o.bi(Ye,Rs),o.bi(ut,Rs),o.bi(tt,Rs)]));const ft=o.ah([],Tt.center,dt);o.eU(ft)===0&&o.eV(ft,0,0,1),o.ay(ft,ft),o.bJ(ft,ft,o.aF),ee.center=o.eW(ft);const Kt=ee.getWorldToCameraMatrix(),Rt=o.b7(new Float64Array(16),Kt);Tt=o.cU.applyTransform(Tt,o.aD([],Kt,dt));const Wt=this._extendAABB(Tt,ee,ie,z);if(!Wt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Tt=Wt,o.ah(ft,ft,Kt);const Et=.5*(Tt.max[2]-Tt.min[2]),Lt=this._minimumAABBFrustumDistance(ee,Tt),Vt=o.bJ([],[0,0,1],Et),ds=o.cT(Vt,ft,Vt),Zt=Lt+(ee.pitch===0?0:o.bf(ft,ds)),Is=ee.globeCenterInViewSpace,Ns=o.ax([],ft,[Is[0],Is[1],Is[2]]);o.ay(Ns,Ns),o.bJ(Ns,Ns,Zt);const er=o.cT([],ft,Ns);o.ah(er,er,Rt);const lr=o.eD/o.aF,hs=o.ai(er),ss=o.bU(Math.max(hs*lr-o.eD,Number.EPSILON),0),Ts=Math.min(ee.zoomFromMercatorZAdjusted(ss),ie.maxZoom);return Ts>.5*(o.cJ+o.cv)?(ee.setProjection({name:"mercator"}),ee.zoom=Ts,this._cameraForBounds(ee,S,P,z,H,G)):{center:ee.center,zoom:Ts,bearing:z,pitch:H}}_extendAABB(g,S,P,z){const H=.5*((P.padding.left||0)+(P.padding.right||0)),G=.5*((P.padding.top||0)+(P.padding.bottom||0)),ee=G,ie=H,pe=H,ye=G,De=S.width-(ie+pe),Ae=S.height-(ee+ye),Be=o.ax([],g.max,g.min),tt=Math.min(De/Be[0],Ae/Be[1]),Ye=Math.min(S.scaleZoom(S.scale*tt),P.maxZoom);if(isNaN(Ye))return null;const ut=S.scale/S.zoomScale(Ye),dt=new o.cU([g.min[0]-ie*ut,g.min[1]-ye*ut,g.min[2]],[g.max[0]+pe*ut,g.max[1]+ee*ut,g.max[2]]),jt=(typeof P.offset.x=="number"&&typeof P.offset.y=="number"?new o.P(P.offset.x,P.offset.y):o.P.convert(P.offset)).rotate(-o.ap(z));return dt.center[0]-=jt.x*ut,dt.center[1]+=jt.y*ut,dt}queryTerrainElevation(g,S){const P=this.transform.elevation;return P?(S=Object.assign({},{exaggerated:!0},S),P.getAtPoint(o.ag.fromLngLat(g),null,S.exaggerated)):null}_cameraForBounds(g,S,P,z,H,G){if(g.projection.name==="globe")return this._cameraForBoundsOnGlobe(g,S,P,z,H,G);const ee=g.clone(),ie=this._extendCameraOptions(G);ee.bearing=z,ee.pitch=H;const pe=o.aU.convert(S),ye=o.aU.convert(P),De=new o.aU(pe.lng,ye.lat),Ae=new o.aU(ye.lng,pe.lat),Be=ee.project(pe),tt=ee.project(ye),Ye=this.queryTerrainElevation(pe),ut=this.queryTerrainElevation(ye),dt=this.queryTerrainElevation(De),jt=this.queryTerrainElevation(Ae),Tt=[[Be.x,Be.y,Math.min(Ye||0,ut||0,dt||0,jt||0)],[tt.x,tt.y,Math.max(Ye||0,ut||0,dt||0,jt||0)]];let ft=o.cU.fromPoints(Tt);const Kt=ee.getWorldToCameraMatrix(),Rt=o.b7(new Float64Array(16),Kt);ft=o.cU.applyTransform(ft,Kt);const Wt=this._extendAABB(ft,ee,ie,z);if(!Wt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");ft=Wt;const Et=.5*o.ax([],ft.max,ft.min)[2],Lt=this._minimumAABBFrustumDistance(ee,ft),Vt=[0,0,1,0];o.aE(Vt,Vt,Kt),o.eX(Vt,Vt);const ds=o.bJ([],Vt,Lt+Et),Zt=o.cT([],ft.center,ds);o.ah(ft.center,ft.center,Rt),o.ah(Zt,Zt,Rt);const Is=ee.unproject(new o.P(ft.center[0],ft.center[1])),Ns=o.eY(ee.projection,Is),er=Math.pow(2,Ns),lr=Math.min(ee._zoomFromMercatorZ(Zt[2]*ee.pixelsPerMeter*er/ee.worldSize),ie.maxZoom);return ee.mercatorFromTransition&&lr<.5*(o.cJ+o.cv)?(ee.setProjection({name:"globe"}),ee.zoom=lr,this._cameraForBounds(ee,S,P,z,H,G)):{center:Is,zoom:lr,bearing:z,pitch:H}}fitBounds(g,S,P){const z=this.cameraForBounds(g,S);return this._fitInternal(z,S,P)}fitScreenCoordinates(g,S,P,z,H){const G=o.P.convert(g),ee=o.P.convert(S),ie=new o.P(Math.min(G.x,ee.x),Math.min(G.y,ee.y)),pe=new o.P(Math.max(G.x,ee.x),Math.max(G.y,ee.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(G,ee))return this;const ye=this.transform.pointLocation3D(ie),De=this.transform.pointLocation3D(pe),Ae=this.transform.pointLocation3D(new o.P(ie.x,pe.y)),Be=this.transform.pointLocation3D(new o.P(pe.x,ie.y)),tt=[Math.min(ye.lng,De.lng,Ae.lng,Be.lng),Math.min(ye.lat,De.lat,Ae.lat,Be.lat)],Ye=[Math.max(ye.lng,De.lng,Ae.lng,Be.lng),Math.max(ye.lat,De.lat,Ae.lat,Be.lat)],ut=z&&z.pitch?z.pitch:this.getPitch(),dt=this._cameraForBounds(this.transform,tt,Ye,P,ut,z);return this._fitInternal(dt,z,H)}_fitInternal(g,S,P){return g?(S=Object.assign(g,S)).linear?this.easeTo(S,P):this.flyTo(S,P):this}jumpTo(g,S){this.stop();const P=g.preloadOnly?this.transform.clone():this.transform;let z=!1,H=!1,G=!1;"zoom"in g&&P.zoom!==+g.zoom&&(z=!0,P.zoom=+g.zoom),g.center!==void 0&&(P.center=o.aU.convert(g.center)),"bearing"in g&&P.bearing!==+g.bearing&&(H=!0,P.bearing=+g.bearing),"pitch"in g&&P.pitch!==+g.pitch&&(G=!0,P.pitch=+g.pitch);const ee=typeof g.padding=="number"?this._extendPadding(g.padding):g.padding;if(g.padding!=null&&!P.isPaddingEqual(ee))if(g.retainPadding===!1){const ie=P.clone();ie.padding=ee,P.setLocationAtPoint(P.center,ie.centerPoint)}else P.padding=ee;return g.preloadOnly?(this._preloadTiles(P),this):(this.fire(new o.C("movestart",S)).fire(new o.C("move",S)),z&&this.fire(new o.C("zoomstart",S)).fire(new o.C("zoom",S)).fire(new o.C("zoomend",S)),H&&this.fire(new o.C("rotatestart",S)).fire(new o.C("rotate",S)).fire(new o.C("rotateend",S)),G&&this.fire(new o.C("pitchstart",S)).fire(new o.C("pitch",S)).fire(new o.C("pitchend",S)),this.fire(new o.C("moveend",S)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(MD),this.transform.getFreeCameraOptions()}setFreeCameraOptions(g,S){const P=this.transform;if(!P.projection.supportsFreeCamera)return o.w(MD),this;this.stop();const z=P.zoom,H=P.pitch,G=P.bearing;P.setFreeCameraOptions(g);const ee=z!==P.zoom,ie=H!==P.pitch,pe=G!==P.bearing;return this.fire(new o.C("movestart",S)).fire(new o.C("move",S)),ee&&this.fire(new o.C("zoomstart",S)).fire(new o.C("zoom",S)).fire(new o.C("zoomend",S)),pe&&this.fire(new o.C("rotatestart",S)).fire(new o.C("rotate",S)).fire(new o.C("rotateend",S)),ie&&this.fire(new o.C("pitchstart",S)).fire(new o.C("pitch",S)).fire(new o.C("pitchend",S)),this.fire(new o.C("moveend",S)),this}easeTo(g,S){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 P=this.transform,z=this.getZoom(),H=this.getBearing(),G=this.getPitch(),ee=this.getPadding(),ie="zoom"in g?+g.zoom:z,pe="bearing"in g?this._normalizeBearing(g.bearing,H):H,ye="pitch"in g?+g.pitch:G,De=this._extendPadding(g.padding),Ae=o.P.convert(g.offset);let Be,tt,Ye;if(P.projection.name==="globe"){const Vt=o.ag.fromLngLat(P.center),ds=Ae.rotate(-P.angle);Vt.x+=ds.x/P.worldSize,Vt.y+=ds.y/P.worldSize;const Zt=Vt.toLngLat(),Is=o.aU.convert(g.center||Zt);this._normalizeCenter(Is),Be=P.centerPoint.add(ds),tt=new o.P(Vt.x,Vt.y).mult(P.worldSize),Ye=new o.P(o.aH(Is.lng),o.aL(Is.lat)).mult(P.worldSize).sub(tt)}else{Be=P.centerPoint.add(Ae);const Vt=P.pointLocation(Be),ds=o.aU.convert(g.center||Vt);this._normalizeCenter(ds),tt=P.project(Vt),Ye=P.project(ds).sub(tt)}const ut=P.zoomScale(ie-z);let dt,jt;g.around&&(dt=o.aU.convert(g.around),jt=P.locationPoint(dt));const Tt=this._zooming||ie!==z,ft=this._rotating||H!==pe,Kt=this._pitching||ye!==G,Rt=!P.isPaddingEqual(De),Wt=g.retainPadding===!1?P.clone():P,Et=Vt=>ds=>{if(Tt&&(Vt.zoom=o.am(z,ie,ds)),ft&&(Vt.bearing=o.am(H,pe,ds)),Kt&&(Vt.pitch=o.am(G,ye,ds)),Rt&&(Wt.interpolatePadding(ee,De,ds),Be=Wt.centerPoint.add(Ae)),dt)Vt.setLocationAtPoint(dt,jt);else{const Zt=Vt.zoomScale(Vt.zoom-z),Is=ie>z?Math.min(2,ut):Math.max(.5,ut),Ns=Math.pow(Is,1-ds),er=Vt.unproject(tt.add(Ye.mult(ds*Ns)).mult(Zt));Vt.setLocationAtPoint(Vt.renderWorldCopies?er.wrap():er,Be)}return g.preloadOnly||this._fireMoveEvents(S),Vt};if(g.preloadOnly){const Vt=this._emulate(Et,g.duration,P);return this._preloadTiles(Vt),this}const Lt={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Tt,this._rotating=ft,this._pitching=Kt,this._padding=Rt,this._easeId=g.easeId,this._prepareEase(S,g.noMoveStart,Lt),this._ease(Et(P),Vt=>{P.cameraElevationReference==="sea"&&P.recenterOnTerrain(),this._afterEase(S,Vt)},g),this}_prepareEase(g,S,P={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),S||P.moving||this.fire(new o.C("movestart",g)),this._zooming&&!P.zooming&&this.fire(new o.C("zoomstart",g)),this._rotating&&!P.rotating&&this.fire(new o.C("rotatestart",g)),this._pitching&&!P.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,S){if(this._easeId&&S&&this._easeId===S)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const P=this._zooming,z=this._rotating,H=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,P&&this.fire(new o.C("zoomend",g)),z&&this.fire(new o.C("rotateend",g)),H&&this.fire(new o.C("pitchend",g)),this.fire(new o.C("moveend",g))}flyTo(g,S){if(this._prefersReducedMotion(g)){const Rs=o.aJ(g,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(Rs,S)}this.stop(),g=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},g);const P=this.transform,z=this.getZoom(),H=this.getBearing(),G=this.getPitch(),ee=this.getPadding(),ie="zoom"in g?o.aC(+g.zoom,P.minZoom,P.maxZoom):z,pe="bearing"in g?this._normalizeBearing(g.bearing,H):H,ye="pitch"in g?+g.pitch:G,De=this._extendPadding(g.padding),Ae=P.zoomScale(ie-z),Be=o.P.convert(g.offset);let tt=P.centerPoint.add(Be);const Ye=P.pointLocation(tt),ut=o.aU.convert(g.center||Ye);this._normalizeCenter(ut);const dt=P.project(Ye),jt=P.project(ut).sub(dt);let Tt=g.curve;const ft=Math.max(P.width,P.height),Kt=ft/Ae,Rt=jt.mag();if("minZoom"in g){const Rs=o.aC(Math.min(g.minZoom,z,ie),P.minZoom,P.maxZoom),qs=ft/P.zoomScale(Rs-z);Tt=Math.sqrt(qs/Rt*2)}const Wt=Tt*Tt;function Et(Rs){const qs=(Kt*Kt-ft*ft+(Rs?-1:1)*Wt*Wt*Rt*Rt)/(2*(Rs?Kt:ft)*Wt*Rt);return Math.log(Math.sqrt(qs*qs+1)-qs)}function Lt(Rs){return(Math.exp(Rs)-Math.exp(-Rs))/2}function Vt(Rs){return(Math.exp(Rs)+Math.exp(-Rs))/2}const ds=Et(0);let Zt=function(Rs){return Vt(ds)/Vt(ds+Tt*Rs)},Is=function(Rs){return ft*((Vt(ds)*(Lt(qs=ds+Tt*Rs)/Vt(qs))-Lt(ds))/Wt)/Rt;var qs},Ns=(Et(1)-ds)/Tt;if(Math.abs(Rt)<1e-6||!isFinite(Ns)){if(Math.abs(ft-Kt)<1e-6)return this.easeTo(g,S);const Rs=Ktg.maxDuration&&(g.duration=0);const er=H!==pe,lr=ye!==G,hs=!P.isPaddingEqual(De),ss=g.retainPadding===!1?P.clone():P,Ts=Rs=>qs=>{const Cr=qs*Ns,br=1/Zt(Cr);Rs.zoom=qs===1?ie:z+Rs.scaleZoom(br),er&&(Rs.bearing=o.am(H,pe,qs)),lr&&(Rs.pitch=o.am(G,ye,qs)),hs&&(ss.interpolatePadding(ee,De,qs),tt=ss.centerPoint.add(Be));const _r=qs===1?ut:Rs.unproject(dt.add(jt.mult(Is(Cr))).mult(br));return Rs.setLocationAtPoint(Rs.renderWorldCopies?_r.wrap():_r,tt),Rs._updateCameraOnTerrain(),g.preloadOnly||this._fireMoveEvents(S),Rs};if(g.preloadOnly){const Rs=this._emulate(Ts,g.duration,P);return this._preloadTiles(Rs),this}return this._zooming=!0,this._rotating=er,this._pitching=lr,this._padding=hs,this._prepareEase(S,!1),this._ease(Ts(P),()=>this._afterEase(S),g),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(g){}_cancelRenderFrame(g){}_stop(g,S){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const P=this._onEaseEnd;this._onEaseEnd=void 0,P.call(this,S)}if(!g){const P=this.handlers;P&&P.stop(!1)}return this}_ease(g,S,P){P.animate===!1||P.duration===0?(g(1),S()):(this._easeStart=o.o.now(),this._easeOptions=P,this._onEaseFrame=g,this._onEaseEnd=S,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const g=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),S=this._onEaseFrame;S&&S(this._easeOptions.easing(g)),g<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(g,S){g=o.bs(g,-180,180);const P=Math.abs(g-S);return Math.abs(g-360-S)180?-360:P<-180?360:0}_prefersReducedMotion(g){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(g&&g.essential)}_emulate(g,S,P){const z=Math.ceil(15*S/1e3),H=[],G=g(P.clone());for(let ee=0;ee<=z;ee++){const ie=G(ee/z);H.push(ie.clone())}return H}_preloadTiles(g,S){}}class ID{constructor(g={}){this.options=g,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(g){const S=this.options&&this.options.compact,P=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",P);const z=_("span","mapboxgl-ctrl-icon",this._compactButton);return z.setAttribute("aria-hidden","true"),z.setAttribute("title",P),this._innerContainer=_("div","mapboxgl-ctrl-attrib-inner",this._container),S&&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),S===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 S=[{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 P=S.reduce((z,H,G)=>(H.value&&(z+=`${H.key}=${H.value}${Gz.length-H.length),g=g.filter((z,H)=>{for(let G=H+1;G=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?g=[...this.options.customAttribution,...g]:g.unshift(this.options.customAttribution));const P=g.map(z=>function(H){const G=new DOMParser().parseFromString(H,"text/html");return Array.from(G.body.querySelectorAll("*")).reverse().forEach(ee=>{const ie=ee.textContent||"";if(ee.tagName!=="A")return void ee.replaceWith(...ee.childNodes);const pe=ee.getAttribute("href");if(!pe||!/^(https?:|mailto:)/i.test(pe))return void ee.replaceWith(G.createTextNode(ie));const ye=G.createElement("a");ye.href=pe,ye.textContent=ie,ye.rel="noopener nofollow";const De=ee.getAttribute("class");De&&(ye.className=De),ee.replaceWith(ye)}),G.body.innerHTML}(z)).join(" | ");P!==this._attribHTML&&(this._attribHTML=P,g.length?(this._innerContainer.innerHTML=P,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 PD{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(g){this._map=g,this._container=_("div","mapboxgl-ctrl");const S=_("a","mapboxgl-ctrl-logo");return S.target="_blank",S.rel="noopener nofollow",S.href="https://www.mapbox.com/",S.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),S.setAttribute("rel","noopener nofollow"),this._container.appendChild(S),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 S in g){const P=g[S].getSource();if(P.hasOwnProperty("mapbox_logo")&&!P.mapbox_logo)return!1}return!0}_updateCompact(){const g=this._container.children;if(g.length){const S=g[0];this._map.getCanvasContainer().offsetWidth<250?S.classList.add("mapboxgl-compact"):S.classList.remove("mapboxgl-compact")}}}class v${constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(g){const S=++this._id;return this._queue.push({callback:g,id:S,cancelled:!1}),S}remove(g){const S=this._currentlyRunning,P=S?this._queue.concat(S):this._queue;for(const z of P)if(z.id===g)return void(z.cancelled=!0)}run(g=0){const S=this._currentlyRunning=this._queue;this._queue=[];for(const P of S)if(!P.cancelled&&(P.callback(g),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class sve{constructor(g){this.jumpTo(g)}getValue(g){if(g<=this._startTime)return this._start;if(g>=this._endTime)return this._end;const S=o.dn((g-this._startTime)/(this._endTime-this._startTime));return this._start*(1-S)+this._end*S}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,S,P){this._start=this.getValue(S),this._end=g,this._startTime=S,this._endTime=S+P}}const rve={"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 jo extends o.C{constructor(g,S,P,z){const{point:H,lngLat:G,originalEvent:ee,target:ie}=g;super(g.type,{point:H,lngLat:G,originalEvent:ee,target:ie}),this.preventDefault=()=>{g.preventDefault()},this.id=S,this.interaction=P,this.feature=z}}class FM{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,S){if(this.typeById.has(g))throw new Error(`Interaction id "${g}" already exists.`);const P=S.filter;let z=S.type;P&&this.filters.set(g,o.dg(P)),z==="mouseover"&&(z="mouseenter"),z==="mouseout"&&(z="mouseleave");const H=this.interactionsByType.get(z)||new Map;z==="mouseenter"||z==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(g,S)):H.size===0&&this.map.on(z,this.handleType),H.size===0&&this.interactionsByType.set(z,H),H.set(g,S),this.typeById.set(g,z)}get(g){const S=this.typeById.get(g);if(!S)return;const P=this.interactionsByType.get(S);return P?P.get(g):void 0}remove(g){const S=this.typeById.get(g);if(!S)return;this.typeById.delete(g),this.filters.delete(g);const P=this.interactionsByType.get(S);P&&(P.delete(g),S==="mouseenter"||S==="mouseleave"?(this.delegatedInteractions.delete(g),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):P.size===0&&this.map.off(S,this.handleType))}queryTargets(g,S){const P=[];for(const[z,H]of S)H.target&&P.push({targetId:z,target:H.target,filter:this.filters.get(z)});return this.map.style.queryRenderedTargets(g,P,this.map.transform)}handleMove(g){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const S=this.queryTargets(g.point,Array.from(this.delegatedInteractions).reverse());S.length&&(g.type="mouseenter",this.handleType(g,S));const P=new Map;for(const[z,{feature:H}]of this.prevHoveredFeatures)this.hoveredFeatures.has(z)||P.set(H.id,H);P.size&&(g.type="mouseleave",this.handleType(g,Array.from(P.values())))}handleOut(g){const S=Array.from(this.hoveredFeatures.values()).map(({feature:P})=>P);S.length&&(g.type="mouseleave",this.handleType(g,S)),this.hoveredFeatures.clear()}handleType(g,S){const P=g.type==="mouseenter";if(P&&!this.interactionsByType.has(g.type))return void o.w("mouseenter interaction required for mouseleave to work.");const z=Array.from(this.interactionsByType.get(g.type)).reverse(),H=!!S;S=S||this.queryTargets(g.point,z);let G=!1;const ee=new Set;for(const ie of S){for(const[pe,ye]of z){if(!ye.target)continue;const De=ie.variants?ie.variants[pe]:null;if(De){for(const Ae of De){if(Xu(Ae,ie,ee,pe))continue;const Be=new o.di(ie,Ae),tt=rp(Ae,ie,pe);H&&Be.id!==void 0&&(Be.state=this.map.getFeatureState(Be));const Ye=P?this.prevHoveredFeatures.get(tt):null,ut=new jo(g,pe,ye,Be),dt=Ye?Ye.stop:ye.handler(ut);if(P&&this.hoveredFeatures.set(tt,{feature:ie,stop:dt}),dt!==!1){G=!0;break}}if(G)break}}if(G)break}if(!G)for(const[ie,pe]of z){const{handler:ye,target:De}=pe;if(!De&&ye(new jo(g,ie,pe,null))!==!1)break}}}function nve(M,g){if(Array.isArray(M)&&Array.isArray(g)){const S=new Set(M),P=new Set(g);return S.size===P.size&&M.every(z=>P.has(z))}return o.b6(M,g)}const ave={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},ive={showCompass:!0,showZoom:!0,visualizePitch:!1};class Y4{constructor(g,S,P=!1){this._clickTolerance=10,this.element=S,this.mouseRotate=new IM({clickTolerance:g.dragRotate._mouseRotate._clickTolerance}),this.map=g,P&&(this.mousePitch=new V4({clickTolerance:g.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),S.addEventListener("mousedown",this.mousedown),S.addEventListener("touchstart",this.touchstart,{passive:!1}),S.addEventListener("touchmove",this.touchmove),S.addEventListener("touchend",this.touchend),S.addEventListener("touchcancel",this.reset)}down(g,S){this.mouseRotate.mousedown(g,S),this.mousePitch&&this.mousePitch.mousedown(g,S),A()}move(g,S){const P=this.map,z=this.mouseRotate.mousemoveWindow(g,S),H=z&&z.bearingDelta;if(H&&P.setBearing(P.getBearing()+H),this.mousePitch){const G=this.mousePitch.mousemoveWindow(g,S),ee=G&&G.pitchDelta;ee&&P.setPitch(P.getPitch()+ee)}}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()}),F(this.element,g)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(g){this.move(g,F(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=O(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=O(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)S.width||g.y>S.height;S.locationPoint3D(P).distSqr(g)180;){const P=S.locationPoint3D(M);if(P.x>=0&&P.y>=0&&P.x<=S.width&&P.y<=S.height)break;M.lng>S.center.lng?M.lng-=360:M.lng+=360}return M}const Z4={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%)"},Jp={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Wx extends o.E{constructor(g,S){super(),(g instanceof HTMLElement||S)&&(g=Object.assign({element:g},S)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:P="center",color:z="#3FB1CE",scale:H=1,draggable:G=!1,clickTolerance:ee=0,rotation:ie=Jp.rotation,rotationAlignment:pe=Jp.rotationAlignment,pitchAlignment:ye=Jp.pitchAlignment,occludedOpacity:De=Jp.occludedOpacity,altitude:Ae=Jp.altitude}=g||{};this._anchor=P,this._color=z,this._scale=H,this._draggable=G,this._clickTolerance=ee,this._rotation=ie,this._rotationAlignment=pe,this._pitchAlignment=ye,this._occludedOpacity=De,this._altitude=Ae,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",Ye=>{Ye.preventDefault()}),this._element.addEventListener("mousedown",Ye=>{Ye.preventDefault()});const Be=this._element.classList;for(const Ye in Z4)Be.remove(`mapboxgl-marker-anchor-${Ye}`);Be.add(`mapboxgl-marker-anchor-${this._anchor}`);const tt=g&&g.className?g.className.trim().split(/\s+/):[];Be.add(...tt),this._popup=null}_createDefaultMarker(){const g=_("div"),S=b("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},g);if(this._altitude===0){const P=b("radialGradient",{id:"shadowGradient"},b("defs",{},S));b("stop",{offset:"10%","stop-opacity":.4},P),b("stop",{offset:"100%","stop-opacity":.05},P),b("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},S)}return b("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},S),b("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},S),b("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},S),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||Jp.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 z=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":[z,-1*(38.1-13.5+z)],"bottom-right":[-z,-1*(38.1-13.5+z)],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 S=g.code,P=g.charCode||g.keyCode;S!=="Space"&&S!=="Enter"&&P!==32&&P!==13||this.togglePopup()}_onMapClick(g){const S=g.originalEvent.target,P=this._element;this._popup&&(S===P||P.contains(S))&&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,S=this._pos;if(!g||!S)return!1;const P=g.unproject(S,this._altitude),z=g.getFreeCameraOptions();if(!z.position)return!1;const H=z.position.toLngLat();return H.distanceTo(P)<.9*H.distanceTo(this._lngLat)}_evaluateOpacity(){const g=this._map;if(!g)return;const S=this._pos;if(!S||S.x<0||S.x>g.transform.width||S.y<0||S.y>g.transform.height)return void this._clearFadeTimer();const P=g.unproject(S,this._altitude);let z;g._showingGlobe()&&o.e$(g.transform,this._lngLat)?z=0:(z=1-g._queryFogOpacity(P),g.transform._terrainEnabled()&&g.getTerrain()&&this._behindTerrain()&&(z*=this._occludedOpacity)),this._element.style.opacity=`${z}`,this._element.style.pointerEvents=z>0?"auto":"none",this._popup&&this._popup._setOpacity(z),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const g=this._pos;if(!g||!this._map)return;const S=this._offset.mult(this._scale);this._element.style.transform=` translate(${g.x}px,${g.y}px) ${Z4[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${S.x}px,${S.y}px) `}_calculateXYTransform(){const g=this._pos,S=this._map,P=this.getPitchAlignment();if(!S||!g||P!=="map")return"";if(!S._showingGlobe()){const ie=S.getPitch();return ie?`rotateX(${ie}deg)`:""}const z=o.cH(o.f0(S.transform,this._lngLat)),H=g.sub(o.f1(S.transform)),G=Math.abs(H.x)+Math.abs(H.y);if(G===0)return"";const ee=z/G;return`rotateX(${-H.y*ee}deg) rotateY(${H.x*ee}deg)`}_calculateZTransform(){const g=this._pos,S=this._map;if(!S||!g)return"";let P=0;const z=this.getRotationAlignment();if(z==="map")if(S._showingGlobe()){const H=S.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),G=S.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(H);P=o.cH(Math.atan2(G.y,G.x))-90}else P=-S.getBearing();else if(z==="horizon"){const H=o.aj(4,6,S.getZoom()),G=o.f1(S.transform);G.y+=H*S.transform.height;const ee=g.sub(G),ie=o.cH(Math.atan2(ee.y,ee.x));P=(ie>90?ie-270:ie+90)*(1-H)}return P+=this._rotation,P?`rotateZ(${P}deg)`:""}_update(g){cancelAnimationFrame(this._updateFrameId);const S=this._map;S&&(S.transform.renderWorldCopies&&(this._lngLat=LD(this._lngLat,this._pos,S.transform)),this._pos=S.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(),S._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(S._showingGlobe()||S.getTerrain()||S.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 S=this._map;if(!S)return;const P=this._pointerdownPos,z=this._positionDelta;if(P&&z){if(!this._isDragging){const H=this._clickTolerance||S._clickTolerance;if(g.point.dist(P)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 Fm(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 v$,this._domRenderTaskQueue=new v$,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},rve,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 sve(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 S=me(M.accessToken||o.g.ACCESS_TOKEN);if(S&&"atlas"in S&&typeof S.atlas=="number"&&(this._tokenExpiration=S.atlas),this._silenceAuthErrors=!!M.testMode,this._contextCreateOptions=M.contextCreateOptions?Object.assign({},M.contextCreateOptions):{},typeof M.container=="string"){const P=document.getElementById(M.container);if(!P)throw new Error(`Container '${M.container.toString()}' not found.`);this._container=P}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 g$(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 oc(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 P=M.bounds;P&&(this.resize(),this.fitBounds(P,Object.assign({},M.fitBoundsOptions,{duration:0})))}this.resize(),M.attributionControl&&this.addControl(new ID({customAttribution:M.customAttribution})),this._logoControl=new PD,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",P=>{this._update(P.dataType==="style"),this.fire(new o.C(`${P.dataType}data`,P))}),this.on("dataloading",P=>{this.fire(new o.C(`${P.dataType}dataloading`,P))}),this._interactions=new FM(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 S=M.onAdd(this);this._controls.push(M);const P=this._controlPositions[g];return g.indexOf("bottom")!==-1?P.insertBefore(S,P.firstChild):P.appendChild(S),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 S of this._controls)S._setLanguage&&S._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 S;g==="globe"&&M.zoom>=o.cv?(M.setMercatorFromTransition(),S=!0):g==="mercator"&&M.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(M),this.style.applyProjectionUpdate();const P=this.transform.getProjection().name==="mercator"&&S!==this.transform.mercatorFromTransition;return(g||P)&&(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,S){const P=z=>{let H=[];if(Array.isArray(g)){const G=g.filter(ee=>this.getLayer(ee));H=G.length?this.queryRenderedFeatures(z,{layers:G}):[]}else H=this.queryRenderedFeatures(z,{target:g});return H};if(M==="mouseenter"||M==="mouseover"){let z=!1;return{listener:S,targets:g,delegates:{mousemove:G=>{const ee=P(G.point);ee.length?z||(z=!0,S.call(this,new Ja(M,this,G.originalEvent,{features:ee}))):z=!1},mouseout:()=>{z=!1}}}}if(M==="mouseleave"||M==="mouseout"){let z=!1;return{listener:S,targets:g,delegates:{mousemove:ee=>{P(ee.point).length?z=!0:z&&(z=!1,S.call(this,new Ja(M,this,ee.originalEvent)))},mouseout:ee=>{z&&(z=!1,S.call(this,new Ja(M,this,ee.originalEvent)))}}}}{const z=H=>{const G=P(H.point);G.length&&(H.features=G,S.call(this,H),delete H.features)};return{listener:S,targets:g,delegates:{[M]:z}}}}on(M,g,S){if(typeof g=="function"||S===void 0)return super.on(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const P=this._createDelegatedListener(M,g,S);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[M]=this._delegatedListeners[M]||[],this._delegatedListeners[M].push(P);for(const z in P.delegates)this.on(z,P.delegates[z]);return this}once(M,g,S){if(typeof g=="function"||S===void 0)return super.once(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const P=this._createDelegatedListener(M,g,S);for(const z in P.delegates)this.once(z,P.delegates[z]);return this}off(M,g,S){if(typeof g=="function"||S===void 0)return super.off(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const P=this._delegatedListeners?this._delegatedListeners[M]:void 0;return P&&(z=>{for(let H=0;H{if(S){const z=typeof S=="string"?S:S instanceof Error?S.message:S.error;o.w(`Unable to perform style diff: ${z}. Rebuilding the style from scratch.`),this._updateStyle(M,g)}else P&&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 S=Object.assign({},g);g&&g.config&&(S.initialConfig=g.config,delete S.config),this.style=new Ic(this,S).load(M),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Ic(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,S){this._lazyInitEmptyStyle(),this.style.addSourceType(M,g,S)}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:S=1,sdf:P=!1,stretchX:z,stretchY:H,content:G}={}){this._lazyInitEmptyStyle();const ee=o.I.from(M);if(g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap){const{width:ie,height:pe,data:ye}=o.o.getImageData(g);this.style.addImage(ee,{data:new o.q({width:ie,height:pe},ye),pixelRatio:S,stretchX:z,stretchY:H,content:G,sdf:P,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:ie,height:pe}=g,ye=g;this.style.addImage(ee,{data:new o.q({width:ie,height:pe},new Uint8Array(ye.data)),pixelRatio:S,stretchX:z,stretchY:H,content:G,sdf:P,usvg:!1,version:0,userImage:ye}),ye.onAdd&&ye.onAdd(this,M)}}updateImage(M,g){this._lazyInitEmptyStyle();const S=o.I.from(M),P=this.style.getImage(S);if(!P)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 z=g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap?o.o.getImageData(g):g,{width:H,height:G,data:ee}=z;if(H===void 0||G===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(H!==(P.usvg?P.icon.usvg_tree.width:P.data.width)||G!==(P.usvg?P.icon.usvg_tree.height:P.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${H}, ${G}) must be that same as the previous version of the image (${P.data.width}, ${P.data.height})`)));const ie=!(g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap);let pe=!1;P.usvg?(P.data=new o.q({width:H,height:G},new Uint8Array(ee)),P.usvg=!1,P.icon=void 0,pe=!0):P.data.replace(ee,ie),this.style.updateImage(S,P,pe)}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),(S,P)=>{g(S,P)})}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(S=>this.fire(new o.B(new Error("Failed to add import",S)))),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,S){return this._isValidId(M)?(this.style.setLayerZoomRange(M,g,S),this._update(!0)):this}setFilter(M,g,S={}){return this._isValidId(M)?(this.style.setFilter(M,g,S),this._update(!0)):this}getFilter(M){return this._isValidId(M)?this.style.getFilter(M):null}setPaintProperty(M,g,S,P={}){return this._isValidId(M)?(this.style.setPaintProperty(M,g,S,P),this._update(!0)):this}getPaintProperty(M,g){return this._isValidId(M)?this.style.getPaintProperty(M,g):null}setLayoutProperty(M,g,S,P={}){return this._isValidId(M)?(this.style.setLayoutProperty(M,g,S,P),this._update(!0)):this}getLayoutProperty(M,g){return this._isValidId(M)?this.style.getLayoutProperty(M,g):null}setLayerProperty(M,g,S,P={}){return this._isValidId(M)?(g==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(M,g,S,P),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,S){return this.style.setConfigProperty(M,g,S),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 S,P,z,H=this._container;for(;H&&(!P||!z);){const G=window.getComputedStyle(H).transform;G&&G!=="none"&&(S=G.match(/matrix.*\((.+)\)/)[1].split(", "),S[0]&&S[0]!=="0"&&S[0]!=="1"&&(P=S[0]),S[3]&&S[3]!=="0"&&S[3]!=="1"&&(z=S[3])),H=H.parentElement}this._containerWidth=P?Math.abs(M/P):M,this._containerHeight=z?Math.abs(g/z):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 S=this._controlContainer=_("div","mapboxgl-control-container",M),P=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(z=>{P[z]=_("div",`mapboxgl-ctrl-${z}`,S)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(M,g){const S=o.o.devicePixelRatio||1;this._canvas.width=S*Math.ceil(M),this._canvas.height=S*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?(We(g,!0),this.painter=new ro(g,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",S=>{if(S.dataType==="source"){const P=this.transform.elevation?this.transform.elevation._source():null;P&&S.sourceCacheId===P.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 S=this.painter.context.extTimerQuery,P=o.o.now(),z=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(g=z.createQuery(),z.beginQuery(S.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 H=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const ie=this.transform.zoom,pe=this.transform.pitch,ye=o.o.now(),De=new o.ae(ie,{now:ye,fadeDuration:H,pitch:pe,transition:this.style.transition,worldview:this._worldview});this.style.update(De)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let G=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),G=this._updateAverageElevation(P),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):G=this._updateAverageElevation(P),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,H,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:H,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 ie=o.o.now()-P;z.endQuery(S.TIME_ELAPSED_EXT),setTimeout(()=>{const pe=z.getQueryParameter(g,z.QUERY_RESULT)/1e6;z.deleteQuery(g),this.fire(new o.C("gpu-timing-frame",{cpuTime:ie,gpuTime:pe}))},50)}if(this.listens("gpu-timing-layer")){const ie=this.painter.collectGpuTimers();setTimeout(()=>{const pe=this.painter.queryGpuTimers(ie);this.fire(new o.C("gpu-timing-layer",{layerTimes:pe}))},50)}if(this.listens("gpu-timing-deferred-render")){const ie=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const pe=this.painter.queryGpuTimeDeferredRender(ie);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:pe}))},50)}const ee=this._sourcesDirty||this._styleDirty||this._placementDirty||G;if(ee||this._repaint)this.triggerRepaint();else{const ie=this.idle();if(ie&&(G=this._updateAverageElevation(P,!0)),G)this.triggerRepaint();else if(this._triggerFrame(!1),ie&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const pe=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:pe})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||ee||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&we(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 S=z=>(this.transform.averageElevation=z,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&S(0);const P=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(P||(g||M-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(M)){const z=this.transform.averageElevation;let H=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(H)?H=0:this._averageElevationLastSampledAt=M;const G=Math.abs(z-H);if(G>1){if(this._isInitialLoad||P)return this._averageElevation.jumpTo(H),S(H);this._averageElevation.easeTo(H,M,300)}else if(G>1e-4)return this._averageElevation.jumpTo(H),S(H)}return!!this._averageElevation.isEasing(M)&&S(this._averageElevation.getValue(M))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const M=this.painter.context.gl;We(M,!1),this._logoControl instanceof PD&&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(){Se(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,M=>{M&&(M.message!==Q&&M.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),Oe(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&ze(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Le(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){ve(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 S=this.painter.context.gl,P=S.createFramebuffer();function z(H){S.framebufferTexture2D(S.FRAMEBUFFER,S.COLOR_ATTACHMENT0,S.TEXTURE_2D,H,0);const G=new Uint8Array(S.drawingBufferWidth*S.drawingBufferHeight*4);return S.readPixels(0,0,S.drawingBufferWidth,S.drawingBufferHeight,S.RGBA,S.UNSIGNED_BYTE,G),G}return S.bindFramebuffer(S.FRAMEBUFFER,P),this._canvasPixelComparison(z(M),g.canvasCopies.map(z),g.timeStamps)}_canvasPixelComparison(M,g,S){let P=S[1]-S[0];const z=M.length/4;for(let H=0;H{const S=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,S&&this._render(g)}))}_preloadTiles(M){const g=this.style?this.style.getSourceCaches():[];return o.t(g,(S,P)=>S._preloadTiles(M,P),()=>{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({},ive,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 S=this._map;S&&(this.options.visualizePitch?S.resetNorthPitch({},{originalEvent:g}):S.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(),S=g===M.getMaxZoom(),P=g===M.getMinZoom();this._zoomInButton.disabled=S,this._zoomOutButton.disabled=P,this._zoomInButton.setAttribute("aria-disabled",S.toString()),this._zoomOutButton.setAttribute("aria-disabled",P.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 Y4(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 S=_("button",M,this._container);return S.type="button",S.addEventListener("click",g),S}_setButtonTitle(M,g){if(!this._map)return;const S=this._map._getUIString(`NavigationControl.${g}`);M.setAttribute("aria-label",S),M.firstElementChild&&M.firstElementChild.setAttribute("title",S)}},GeolocateControl:class extends o.E{constructor(M={}){super();const g=navigator.geolocation;this.options=Object.assign({geolocation:g},X4,M),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=ga(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=(S=!!this.options.geolocation)=>{this._supportsGeolocation=S,M(S)};this._supportsGeolocation!==void 0?M(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(S=>g(S.state!=="denied")).catch(()=>g()):g()}_isOutOfMapMaxBounds(M){const g=this._map.getMaxBounds(),S=M.coords;return!!g&&(S.longitudeg.getEast()||S.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),S=M.coords.accuracy,P=this._map.getBearing(),z=Object.assign({bearing:P},this.options.fitBoundsOptions);this._map.fitBounds(g.toBounds(S),z,{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,S=Math.ceil(2*this._accuracy*g);this._circleElement.style.width=`${S}px`,this._circleElement.style.height=`${S}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 Wx({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=_("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Wx({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??X4.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:ID,ScaleControl:class{constructor(M={}){this.options=Object.assign({},Xc,M),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const M=this.options.maxWidth||100,g=this._map,S=g._containerHeight/2,P=g._containerWidth/2-M/2,z=g.unproject([P,S]),H=g.unproject([P+M,S]),G=z.distanceTo(H);if(this.options.unit==="imperial"){const ee=3.2808*G;ee>5280?this._setScale(M,ee/5280,"mile"):this._setScale(M,ee,"foot")}else this.options.unit==="nautical"?this._setScale(M,G/1852,"nautical-mile"):G>=1e3?this._setScale(M,G/1e3,"kilometer"):this._setScale(M,G,"meter")}_setScale(M,g,S){this._map._requestDomTask(()=>{const P=function(H){const G=Math.pow(10,`${Math.floor(H)}`.length-1);let ee=H/G;return ee=ee>=10?10:ee>=5?5:ee>=3?3:ee>=2?2:ee>=1?1:function(ie){const pe=Math.pow(10,Math.ceil(-Math.log(ie)/Math.LN10));return Math.round(ie*pe)/pe}(ee),G*ee}(g),z=P/g;this._container.innerHTML=S!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:S}).format(P):`${P} ${Kx[S]}`,this._container.style.width=M*z+"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 S=_("button",M,this._container);return S.type="button",S.addEventListener("click",g),S}_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 S=!g||g.floors.length!==M.floors.length||g.floors.some((P,z)=>P.id!==M.floors[z].id);if(S&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),M.selectedFloorId){if(M.selectedFloorId!==this._lastSelectedFloorId||S){const P=M.floors.findIndex(z=>z.id===M.selectedFloorId);if(P!==-1){const z=M.floors.length;let H,G;z<=5?(H=0,G=z-1):this._visibleFloorStart===0?(H=0,G=3):this._visibleFloorStart>=z-3?(H=z-3-1,G=z-1):(H=this._visibleFloorStart,G=this._visibleFloorStart+3-1),PG&&(this._visibleFloorStart=P-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,S=g.length;if(S<=5)return void g.forEach(G=>this._createFloorButton(G));const P=this._visibleFloorStart===0,z=this._visibleFloorStart>=S-3;if(P)this._createFloorButton(g[0]);else{const G=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);_("span","mapboxgl-ctrl-icon",G).setAttribute("aria-hidden","true"),this._container.appendChild(G)}let H=[];if(H=P?g.slice(1,4):z?g.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):g.slice(this._visibleFloorStart,this._visibleFloorStart+3),H.forEach(G=>this._createFloorButton(G)),z)this._createFloorButton(g[S-1]);else{const G=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);_("span","mapboxgl-ctrl-icon",G).setAttribute("aria-hidden","true"),this._container.appendChild(G)}}_createFloorButton(M){const g=this._createButton("mapboxgl-ctrl-level-button",()=>{const H=M.id;this._model&&this._model.selectedFloorId===H&&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(H))}),S=(M.name||"").trim(),P=M.zIndex.toString(),z=S?Array.from(S).slice(0,3).join(""):P;this._setButtonTitle(g,z),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(Q4),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(),S=document.createElement("body");let P;for(S.innerHTML=M;P=S.firstChild,P;)g.appendChild(P);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 S=this._closeButton=_("button","mapboxgl-popup-close-button",g);S.type="button",S.setAttribute("aria-label","Close popup"),S.innerHTML='',S.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,S=this._container,P=this._pos;if(!g||!S||!P)return"bottom";const z=S.offsetWidth,H=S.offsetHeight,G=P.xg.transform.width-z/2;if(P.y+Mg.transform.height-H){if(G)return"bottom-left";if(ee)return"bottom-right"}return G?"left":ee?"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,S=this._content;if(!g||!this._lngLat&&!this._trackPointer||!S)return;let P=this._container;if(P||(P=this._container=_("div","mapboxgl-popup",g.getContainer()),this._tip=_("div","mapboxgl-popup-tip",P),P.appendChild(S)),this.options.maxWidth&&P.style.maxWidth!==this.options.maxWidth&&(P.style.maxWidth=this.options.maxWidth),g.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=LD(this._lngLat,this._pos,g.transform)),!this._trackPointer||M){const z=this._pos=this._trackPointer&&M instanceof o.P?M:g.project(this._lngLat,this._altitude),H=zM(this.options.offset),G=this._anchor=this._getAnchor(H.y),ee=zM(this.options.offset,G),ie=z.add(ee).round();g._requestDomTask(()=>{this._container&&G&&(this._container.style.transform=`${Z4[G]} translate(${ie.x}px,${ie.y}px)`)})}if(!this._marker&&g._showingGlobe()){const z=o.e$(g.transform,this._lngLat)?0:1;this._setOpacity(z)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const M=this._container.querySelector(ove);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:Wx,Style:Ic,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:rb,Evented:o.E,config:o.g,prewarm:function(){Yt().acquire(rt)},clearPrewarmedResources:function(){const M=kt;M&&(M.isPreloaded()&&M.numActive()===1?(M.release(rt),kt=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 ct.workerCount},set workerCount(M){ct.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 et.workerUrl},set workerUrl(M){et.workerUrl=M},get workerClass(){return et.workerClass},set workerClass(M){et.workerClass=M},get workerParams(){return et.workerParams},set workerParams(M){et.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})})(Vnt);var MDt=Vnt.exports;const ol=gl(MDt),qFe={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},VFe={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 IDt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function PDt({listings:s,isLoading:t}){const r=qr(),n=k.useRef(null),a=k.useRef(null),i=k.useRef([]),[l,o]=k.useState(""),[c,d]=k.useState(!0);return k.useEffect(()=>{(async()=>{d(!0);try{const{data:f}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();f!=null&&f.value&&o(f.value)}catch(f){console.error("Error fetching mapbox token:",f)}d(!1)})()},[]),k.useEffect(()=>{if(!n.current||!l||a.current)return;ol.accessToken=l;const m=s.filter(y=>y.latitude!=null&&y.longitude!=null);let f=[-98.5795,39.8283],x=4;if(m.length>0){const y=m.reduce((b,j)=>b+j.longitude,0)/m.length,_=m.reduce((b,j)=>b+j.latitude,0)/m.length;f=[y,_],x=m.length===1?12:10}return a.current=new ol.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:x,center:f}),a.current.addControl(new ol.NavigationControl,"top-right"),()=>{var y;(y=a.current)==null||y.remove(),a.current=null}},[l]),k.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(f=>f.remove()),i.current=[];const m=s.filter(f=>f.latitude!=null&&f.longitude!=null);if(m.forEach(f=>{var A,E,D;const x=qFe[f.status]||"#10B981",y=((A=f.photos)==null?void 0:A.find(R=>R.is_primary))||((E=f.photos)==null?void 0:E[0]),b=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${f.slug||f.id}`:`/public/listing/${f.slug||f.id}`,j=document.createElement("div");j.className="cursor-pointer",j.innerHTML=`

`;const N=new ol.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${y!=null&&y.photo_url?``:""}
${IDt(f.price)}
${f.property_address||""}
${f.city}, ${f.state}
${VFe[f.status]||f.status} ${f.bedrooms?`${f.bedrooms} bed`:""} ${f.bathrooms?`${f.bathrooms} bath`:""}
${(D=f.agent)!=null&&D.name?`
Listed by ${f.agent.name}
`:""}
Click to view details →
`),C=new ol.Marker(j).setLngLat([f.longitude,f.latitude]).setPopup(N).addTo(a.current);i.current.push(C)}),m.length>1){const f=new ol.LngLatBounds;m.forEach(x=>f.extend([x.longitude,x.latitude])),a.current.fitBounds(f,{padding:60,maxZoom:13})}else m.length===1&&a.current.flyTo({center:[m[0].longitude,m[0].latitude],zoom:12})},[s,l]),k.useEffect(()=>(window.__navigateToPublicListing__=m=>{r(m)},()=>{delete window.__navigateToPublicListing__}),[r]),c||t?e.jsx(dr,{className:"w-full h-[500px] rounded-lg"}):!l||s.filter(m=>m.latitude!=null&&m.longitude!=null).length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(qFe).map(([m,f])=>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:f}}),e.jsx("span",{className:"text-xs text-gray-600",children:VFe[m]})]},m))}),e.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const $be={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},LDt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},_6="#0d0d0d",HFe="#1a1a1a",fl="#c9a84c",RN="#f0d78c";function Gnt(){const[s,t]=k.useState(""),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(-1),u=k.useRef(null),[m,f]=k.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:x}=NDt(),y=k.useMemo(()=>{if(!x)return[];const K=s.trim().toLowerCase(),Z=[...x.cities.map(W=>({label:W.label,value:W.city,type:"city",count:W.count})),...x.neighborhoods.map(W=>({label:W.label,value:W.neighborhood,type:"neighborhood",count:W.count})),...x.zips.map(W=>({label:`ZIP ${W.label}`,value:W.zip,type:"zip",count:W.count}))];return(K?Z.filter(W=>W.label.toLowerCase().includes(K)||W.value.toLowerCase().includes(K)):Z).slice(0,8)},[x,s]);k.useEffect(()=>{const K=Z=>{u.current&&!u.current.contains(Z.target)&&o(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[]);const{data:_,isLoading:b}=jDt({city:s||void 0,status:m.status||void 0,propertyType:m.propertyType||void 0,minPrice:m.minPrice?Number(m.minPrice):void 0,maxPrice:m.maxPrice?Number(m.maxPrice):void 0}),j=K=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(K),N=()=>{f({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},C=s||m.status||m.propertyType||m.minPrice||m.maxPrice,A=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),E=K=>A?`/${K.slug||K.id}`:`/public/listing/${K.slug||K.id}`,{featured:D,restListings:R,luxeCount:F,cities:O,activeCount:B}=k.useMemo(()=>{const K=_||[],Z=K.filter(Ee=>Ee.status==="active"),Q=Z.length>0?Z:K,W=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[te,ne,ae]=W.split("-").map(Number),ue=Math.floor(Date.UTC(te,ne-1,ae)/864e5),me=Q.length>0?Q[ue%Q.length]:void 0,de=K.filter(Ee=>!me||Ee.id!==me.id),fe=Array.from(new Set(K.map(Ee=>Ee.city).filter(Boolean))).slice(0,8),je=K.filter(Ee=>(Ee.price||0)>=1e6).length,xe=Z.length;return{featured:me,restListings:de,luxeCount:je,cities:fe,activeCount:xe}},[_]);return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{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:_6,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: ${fl}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${fl}, 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(Vn,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:ome,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(Vn,{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 ${fl}`,color:fl},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(K=>!K),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${fl}`,color:fl},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx($r,{className:"w-5 h-5"}):e.jsx(aS,{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(Vn,{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 ${fl}`,color:fl},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:ADt,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:fl}}),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:RN},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 ${fl}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:fl}}),e.jsx(Ne,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:K=>{t(K.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:K=>{if(!(!l||y.length===0))if(K.key==="ArrowDown")K.preventDefault(),d(Z=>Math.min(Z+1,y.length-1));else if(K.key==="ArrowUp")K.preventDefault(),d(Z=>Math.max(Z-1,0));else if(K.key==="Enter"&&c>=0){K.preventDefault();const Z=y[c];t(Z.value),o(!1)}else K.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:()=>n(!r),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(dS,{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:fl,color:_6},onClick:()=>o(!1),children:[e.jsx(_n,{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:fl},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:y.map((K,Z)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(Z),onClick:()=>{t(K.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:[K.type==="city"&&e.jsx(Ma,{className:"h-4 w-4 shrink-0",style:{color:fl}}),K.type==="neighborhood"&&e.jsx(Ga,{className:"h-4 w-4 shrink-0",style:{color:fl}}),K.type==="zip"&&e.jsx(Pn,{className:"h-4 w-4 shrink-0",style:{color:fl}}),e.jsx("span",{className:"text-white/90 truncate",children:K.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[K.count," ",K.count===1?"listing":"listings"]})]})},`${K.type}-${K.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."}),r&&e.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),e.jsxs(Ds,{value:m.status||"all",onValueChange:K=>f({...m,status:K==="all"?"":K}),children:[e.jsx(Ps,{className:"lu-input-dark",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"Any status"}),Object.entries($be).map(([K,Z])=>e.jsx(lt,{value:K,children:Z},K))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(Ds,{value:m.propertyType||"all",onValueChange:K=>f({...m,propertyType:K==="all"?"":K}),children:[e.jsx(Ps,{className:"lu-input-dark",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"Any type"}),Object.entries(LDt).map(([K,Z])=>e.jsx(lt,{value:K,children:Z},K))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(Ne,{type:"number",placeholder:"No min",value:m.minPrice,onChange:K=>f({...m,minPrice:K.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(Ne,{type:"number",placeholder:"No max",value:m.maxPrice,onChange:K=>f({...m,maxPrice:K.target.value}),className:"lu-input-dark"})]}),C&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs(q,{variant:"ghost",size:"sm",onClick:N,className:"text-white/70 hover:text-white gap-1",children:[e.jsx($r,{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:B.toString()},{label:"Luxury $1M+",value:F.toString()}].map(K=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:RN},children:K.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:K.label})]},K.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(Co,{className:"h-4 w-4 animate-bounce"})]})]})]}),O.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:HFe,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:[...O,...O,...O].map((K,Z)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[K,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:fl}})]},Z))})}),D&&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(Ir,{className:"h-4 w-4",style:{color:fl}}),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:RN},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(Vn,{to:E(D),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,Q;const K=((Z=D.photos)==null?void 0:Z.find(W=>W.is_primary))||((Q=D.photos)==null?void 0:Q[0]);return K?e.jsx("img",{src:K.photo_url,alt:D.property_address||D.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(Pn,{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:fl,color:_6},children:$be[D.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(Ma,{className:"h-3.5 w-3.5",style:{color:fl}}),D.city,D.state?`, ${D.state}`:""]}),D.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:D.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:RN},children:j(D.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[D.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(k0,{className:"h-4 w-4",style:{color:fl}}),D.bedrooms," bd"]}),D.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(of,{className:"h-4 w-4",style:{color:fl}}),D.bathrooms," ba"]}),D.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(C0,{className:"h-4 w-4",style:{color:fl}}),D.square_footage.toLocaleString()," sf"]})]}),D.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:D.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:fl},children:["View Residence ",e.jsx(ci,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:HFe},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:fl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:fl}})]}),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:RN},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."})]}),b?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((K,Z)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(dr,{className:"aspect-[4/5] bg-white/5"}),e.jsx(dr,{className:"h-6 w-32 bg-white/5"}),e.jsx(dr,{className:"h-4 w-full bg-white/5"})]},Z))}):R.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:R.map(K=>{var Q,W,te,ne,ae;const Z=((Q=K.photos)==null?void 0:Q.find(ue=>ue.is_primary))||((W=K.photos)==null?void 0:W[0]);return e.jsxs(Vn,{to:E(K),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:K.property_address||K.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(Pn,{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:fl,border:`1px solid ${fl}`},children:$be[K.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:[K.bedrooms&&e.jsxs("span",{children:[K.bedrooms," bd"]}),K.bathrooms&&e.jsxs("span",{children:[K.bathrooms," ba"]}),K.square_footage&&e.jsxs("span",{children:[K.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(Ma,{className:"h-3 w-3",style:{color:fl}}),K.city,K.state?`, ${K.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:RN},children:j(K.price)}),K.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:K.property_address}),((te=K.agent)==null?void 0:te.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(Ga,{className:"h-3 w-3"}),K.agent.name,(((ne=K.agent.brokerage)==null?void 0:ne.name)||K.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((ae=K.agent.brokerage)==null?void 0:ae.name)||K.agent.brokerage_name]})]})]})]},K.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 ${fl}`},children:e.jsx(Pn,{className:"h-8 w-8",style:{color:fl}})}),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."}),C&&e.jsx(q,{onClick:N,style:{background:fl,color:_6},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:fl}}),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:RN},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(PDt,{listings:_,isLoading:b})})]})}),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%, ${_6} 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:fl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:fl}})]}),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:RN},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:fl,color:_6},children:["Explore LevelUp",e.jsx(ci,{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:ome,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(N8t,{}),e.jsx(k8t,{})]})}const DDt=k.lazy(()=>vi(()=>import("./PublicHomeValue-CFbSILWH.js"),[]));function RDt(){const s=vc(),t=window.location.hostname;if(!(t==="listings.relevelup.com"||t.startsWith("listings.")))return null;const n=s.pathname.slice(1);return!n||n===""?e.jsx(Gnt,{}):n==="home-value"||n==="whats-my-home-worth"?e.jsx(k.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(DDt,{})}):n.startsWith("public/")?null:e.jsx(qnt,{slugOverride:n})}function ege({card:s,variant:t}){const r=s.brokerage_display_name||s.brokerage_logo_url,n=s.team_name||s.team_logo_url;if(!r&&!n)return null;const a={standard:{container:"bg-slate-50 border border-slate-100",text:"text-slate-600",subtext:"text-slate-400"},luxury:{container:"bg-[#1e2636] border border-[#c9a84c]/10",text:"text-[#e2e8f0]",subtext:"text-[#4a5568]"},bold:{container:"bg-gray-50 border border-gray-100",text:"text-[#1a1a2e]",subtext:"text-gray-400"},classic:{container:"bg-white border border-[#d4cfc5] shadow-sm",text:"text-[#1b3a4b]",subtext:"text-[#a0aec0]"}}[t];return e.jsx("div",{className:`rounded-2xl p-4 mb-6 ${a.container}`,children:e.jsxs("div",{className:`flex flex-col items-center gap-3 ${r&&n?"divide-y divide-current/10":""}`,children:[r&&e.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[s.brokerage_logo_url&&e.jsx("img",{src:s.brokerage_logo_url,alt:s.brokerage_display_name||"Brokerage",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[280px] object-contain"}),s.brokerage_display_name&&!s.brokerage_logo_url&&e.jsx("p",{className:`text-sm font-medium ${a.text}`,children:s.brokerage_display_name})]}),n&&e.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${r?"pt-3":""}`,children:[s.team_logo_url&&e.jsx("img",{src:s.team_logo_url,alt:s.team_name||"Team",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[280px] object-contain"}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:`text-sm font-medium ${a.text}`,children:s.team_name})]})]})})}const Wnt=s=>pt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:r}=await U.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(r)throw r;const{data:n}=await U.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(n!=null&&n.brokerage_id){const{data:o}=await U.from("brokerages").select("name").eq("id",n.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await U.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await U.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=U.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...n||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(n==null?void 0:n.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),ODt=()=>pt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await U.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),FDt=s=>pt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s}),Knt=()=>{const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("agent_cards").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),he.success("Agent card created")},onError:t=>he.error(t.message)})},Ynt=()=>{const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("agent_cards").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),he.success("Agent card updated")},onError:t=>he.error(t.message)})},ll=async(s,t,r,n)=>{const a=new URLSearchParams(window.location.search);await U.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:r||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:a.get("utm_source")||null,utm_medium:a.get("utm_medium")||null,utm_campaign:a.get("utm_campaign")||null,metadata:{}})},zDt=async(s,t)=>{const{error:r}=await U.from("agent_card_leads").insert({card_id:s,...t});if(r)throw r},Znt=s=>pt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(r)throw r;const{data:n,error:a}=await U.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:n||[],interactions:t||[]}},enabled:!!s});function tge({open:s,onOpenChange:t,cardId:r,type:n,agentName:a}){const[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(!1),j=async N=>{if(N.preventDefault(),!i.trim()){he.error("Please enter your name");return}b(!0);try{await zDt(r,{lead_type:n,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:x.trim()||void 0,intent:m||void 0}),ll(r,"lead_submitted",n),U.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:x.trim()||void 0,intent:m||void 0}}).catch(C=>console.error("Card lead notify failed:",C)),he.success(n==="booking"?"Request sent! They'll be in touch soon.":n==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),f(""),y("")}catch{he.error("Something went wrong. Please try again.")}finally{b(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(an,{children:n==="booking"?`Let ${a} know you'd like to connect.`:n==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:j,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"lead-name",children:"Name *"}),e.jsx(Ne,{id:"lead-name",value:i,onChange:N=>l(N.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(Ne,{id:"lead-phone",type:"tel",value:d,onChange:N=>u(N.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"lead-email",children:"Email"}),e.jsx(Ne,{id:"lead-email",type:"email",value:o,onChange:N=>c(N.target.value),placeholder:"you@example.com"})]}),n==="booking"&&e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(Ds,{value:m,onValueChange:f,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select one"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"buy",children:"Buy a home"}),e.jsx(lt,{value:"sell",children:"Sell my home"}),e.jsx(lt,{value:"both",children:"Buy & Sell"}),e.jsx(lt,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(Ne,{id:"lead-message",value:x,onChange:N=>y(N.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(q,{type:"submit",className:"w-full rounded-2xl",disabled:_,children:_?"Sending...":"Submit"})]})]})})}const BDt=s=>pt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s}),$Dt=s=>pt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s}),UDt=()=>{const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("card_blocks").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["card-blocks",r.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",r.card_id]}),he.success("Block added")},onError:t=>he.error(t.message)})},qDt=()=>{const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("card_blocks").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),he.success("Block updated")},onError:t=>he.error(t.message)})},VDt=()=>{const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("card_blocks").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),he.success("Block removed")},onError:t=>he.error(t.message)})};function HDt(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 GDt(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 WDt={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 KDt({block:s,variant:t}){const r=s.config;if(!r.video_url)return null;const n=r.video_url.includes("mediadelivery.net")||r.video_url.includes("bunnycdn.com"),a=GDt(r.video_url),i=n||!!a,l=n?HDt(r.video_url):a||r.video_url;return e.jsx("div",{className:WDt[t],children:i?e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:l,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsx("video",{src:r.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const YDt={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 ZDt({block:s,variant:t}){const n=s.config.testimonials||[],[a,i]=k.useState(0);if(n.length===0)return null;const l=YDt[t],o=n[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(u2,{className:"h-4 w-4 mb-2 opacity-30"}),e.jsxs("p",{className:`${l.quote} mb-3`,children:['"',o.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:l.name,children:o.name}),o.role&&e.jsx("p",{className:l.role,children:o.role})]})]}),n.length>1&&e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[e.jsx("button",{onClick:()=>i(c=>(c-1+n.length)%n.length),className:l.nav,children:e.jsx(jl,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex gap-1.5",children:n.map((c,d)=>e.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${d===a?l.dot:l.dotInactive}`,onClick:()=>i(d)},d))}),e.jsx("button",{onClick:()=>i(c=>(c+1)%n.length),className:l.nav,children:e.jsx(Ia,{className:"h-4 w-4"})})]})]})}const XDt={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 QDt({block:s,variant:t}){const n=s.config.tags||[];if(n.length===0)return null;const a=XDt[t];return e.jsx("div",{className:a.container,children:n.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const JDt={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 eRt({block:s,cardId:t,variant:r}){const a=s.config.links||[];if(a.length===0)return null;const i=JDt[r];return e.jsx("div",{className:i.container,children:a.map((l,o)=>e.jsxs("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ll(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(un,{className:`h-4 w-4 ${i.icon}`})]},o))})}const YNe={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 tRt({path:s,color:t,size:r=20}){return e.jsx("svg",{viewBox:"0 0 24 24",width:r,height:r,fill:t,children:e.jsx("path",{d:s})})}const sRt={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 rRt({block:s,cardId:t,variant:r}){const a=s.config.platforms||[],i=sRt[r];return a.length===0?null:e.jsxs("div",{className:i.container,children:[e.jsx("h3",{className:i.title,children:"Follow Me"}),e.jsx("div",{className:"flex flex-wrap gap-3 justify-center",children:a.map((l,o)=>{const c=YNe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ll(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(tRt,{path:c.icon,color:c.color})},o)})})]})}function sge({cardId:s,variant:t}){const{data:r}=BDt(s);if(!r||r.length===0)return null;const n=r.filter(l=>l.block_type==="social_media"&&l.is_visible),a=r.filter(l=>l.block_type!=="social_media"),i=n.length>0?{...n[0],config:{platforms:n.flatMap(l=>l.config.platforms||[])}}:null;return r.findIndex(l=>l.block_type==="social_media"),e.jsxs(e.Fragment,{children:[a.map(l=>{switch(l.block_type){case"video_intro":return e.jsx(KDt,{block:l,variant:t},l.id);case"testimonials":return e.jsx(ZDt,{block:l,variant:t},l.id);case"specialties":return e.jsx(QDt,{block:l,variant:t},l.id);case"custom_links":return e.jsx(eRt,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(rRt,{block:i,cardId:s,variant:t})]})}async function nRt(s){try{const t=await fetch(s);if(!t.ok)return null;const r=await t.blob(),n=r.type||"image/jpeg";return new Promise(a=>{const i=new FileReader;i.onloadend=()=>{const o=i.result.split(",")[1];a({base64:o,mimeType:n})},i.onerror=()=>a(null),i.readAsDataURL(r)})}catch{return null}}function aRt(s){const t=s.trim().split(/\s+/);if(t.length<=1)return{first:t[0]||"",last:""};const r=t.pop();return{first:t.join(" "),last:r}}async function rge(s){const{first:t,last:r}=aRt(s.name),n=["BEGIN:VCARD","VERSION:3.0",`FN:${s.name}`,`N:${r};${t};;;`];if(s.phone&&n.push(`TEL;TYPE=CELL:${s.phone}`),s.email&&n.push(`EMAIL;TYPE=INTERNET:${s.email}`),s.brokerage&&n.push(`ORG:${s.brokerage}`),n.push(`URL:${s.cardUrl}`),s.avatarUrl){const o=await nRt(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}n.push("END:VCARD");const a=new Blob([n.join(`\r `)],{type:"text/vcard"}),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=`${s.name.replace(/\s+/g,"_")}.vcf`,l.click(),URL.revokeObjectURL(i),he.success("Contact saved!")}function iRt({card:s}){var j;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(N=>N[0]).join("").toUpperCase().slice(0,2),o=(N,C)=>{ll(s.id,"button_click",N),C()},c=()=>o("call",()=>{var N;(N=s.profile)!=null&&N.phone?window.location.href=`tel:${s.profile.phone}`:he.error("Phone number not available")}),d=()=>o("text",()=>{var N;(N=s.profile)!=null&&N.phone?window.location.href=`sms:${s.profile.phone}`:he.error("Phone number not available")}),u=()=>o("email",()=>{var N;(N=s.profile)!=null&&N.email?window.location.href=`mailto:${s.profile.email}`:he.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),ll(s.id,"button_click","book"))},f=()=>{var N,C;ll(s.id,"contact_saved"),rge({name:i,phone:(N=s.profile)==null?void 0:N.phone,email:(C=s.profile)==null?void 0:C.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{ll(s.id,"share_event");const N=`https://cards.relevelup.com/${s.slug}`,C="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:C,url:N})}catch{}else await navigator.clipboard.writeText(N),he.success("Link copied!")},y=()=>{a("referral"),r(!0),ll(s.id,"button_click","refer")},_=()=>{a("connect"),r(!0),ll(s.id,"button_click","connect")},b={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Wn,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Xa,{src:s.avatar_url||void 0,alt:i}),e.jsx(Kn,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:l})]}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',s.positioning_statement,'"']})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs(q,{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(Mn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(q,{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(Ui,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(q,{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(Ks,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs(q,{onClick:m,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(vn,{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(fa,{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(ege,{card:s,variant:"standard"}),e.jsx(sge,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(q,{variant:"ghost",onClick:f,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(li,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(q,{variant:"ghost",onClick:()=>{ll(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(fa,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(q,{variant:"ghost",onClick:y,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Dr,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(q,{variant:"ghost",onClick:_,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(xl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(q,{variant:"ghost",onClick:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Ec,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((N,C)=>e.jsx("a",{href:N.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ll(s.id,"button_click",`social_${N.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:b[N.platform.toLowerCase()]||"🔗"},C))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(tge,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function oRt({card:s}){var j;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(N=>N[0]).join("").toUpperCase().slice(0,2),o=(N,C)=>{ll(s.id,"button_click",N),C()},c=()=>o("call",()=>{var N;(N=s.profile)!=null&&N.phone?window.location.href=`tel:${s.profile.phone}`:he.error("Phone number not available")}),d=()=>o("text",()=>{var N;(N=s.profile)!=null&&N.phone?window.location.href=`sms:${s.profile.phone}`:he.error("Phone number not available")}),u=()=>o("email",()=>{var N;(N=s.profile)!=null&&N.email?window.location.href=`mailto:${s.profile.email}`:he.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),ll(s.id,"button_click","book"))},f=()=>{var N,C;ll(s.id,"contact_saved"),rge({name:i,phone:(N=s.profile)==null?void 0:N.phone,email:(C=s.profile)==null?void 0:C.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{ll(s.id,"share_event");const N=`https://cards.relevelup.com/${s.slug}`,C="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:C,url:N})}catch{}else await navigator.clipboard.writeText(N),he.success("Link copied!")},y=()=>{a("referral"),r(!0),ll(s.id,"button_click","refer")},_=()=>{a("connect"),r(!0),ll(s.id,"button_click","connect")},b={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Wn,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(Xa,{src:s.avatar_url||void 0,alt:i}),e.jsx(Kn,{className:"text-2xl font-serif bg-[#c9a84c]/20 text-[#e8d48b]",children:l})]}),e.jsx("h1",{className:"text-2xl font-serif font-bold text-white tracking-wide mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-[#e8d48b] mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-[#c9a84c] tracking-widest uppercase mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-[#a0aec0] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',s.positioning_statement,'"']})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Mn,label:"Call",handler:c},{icon:Ui,label:"Text",handler:d},{icon:Ks,label:"Email",handler:u}].map(({icon:N,label:C,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(N,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:C})]},C))}),e.jsxs("button",{onClick:m,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[e.jsx(vn,{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(fa,{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(ege,{card:s,variant:"luxury"}),e.jsx(sge,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&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(li,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ll(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(fa,{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(Dr,{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(xl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Ec,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((N,C)=>e.jsx("a",{href:N.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ll(s.id,"button_click",`social_${N.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:b[N.platform.toLowerCase()]||"🔗"},C))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(tge,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function lRt({card:s}){var C,A,E,D;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((C=s.profile)==null?void 0:C.name)||"Agent",l=i.split(" ").map(R=>R[0]).join("").toUpperCase().slice(0,2),o={accent:((A=s.bold_theme_colors)==null?void 0:A.accent)||"#ff5722",dark:((E=s.bold_theme_colors)==null?void 0:E.dark)||"#1a1a2e",button:((D=s.bold_theme_colors)==null?void 0:D.button)||"#ff5722"},c=(R,F)=>{const O=parseInt(R.replace("#",""),16),B=Math.max(0,(O>>16)-F),K=Math.max(0,(O>>8&255)-F),Z=Math.max(0,(O&255)-F);return`#${(B<<16|K<<8|Z).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(R,F)=>{ll(s.id,"button_click",R),F()},u=()=>d("call",()=>{var R;(R=s.profile)!=null&&R.phone?window.location.href=`tel:${s.profile.phone}`:he.error("Phone number not available")}),m=()=>d("text",()=>{var R;(R=s.profile)!=null&&R.phone?window.location.href=`sms:${s.profile.phone}`:he.error("Phone number not available")}),f=()=>d("email",()=>{var R;(R=s.profile)!=null&&R.email?window.location.href=`mailto:${s.profile.email}`:he.error("Email not available")}),x=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),ll(s.id,"button_click","book"))},y=()=>{var R,F;ll(s.id,"contact_saved"),rge({name:i,phone:(R=s.profile)==null?void 0:R.phone,email:(F=s.profile)==null?void 0:F.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},_=async()=>{ll(s.id,"share_event");const R=`https://cards.relevelup.com/${s.slug}`,F="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:F,url:R})}catch{}else await navigator.clipboard.writeText(R),he.success("Link copied!")},b=()=>{a("referral"),r(!0),ll(s.id,"button_click","refer")},j=()=>{a("connect"),r(!0),ll(s.id,"button_click","connect")},N={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(Wn,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(Xa,{src:s.avatar_url||void 0,alt:i}),e.jsx(Kn,{className:"text-2xl font-black text-white",style:{backgroundColor:o.accent},children:l})]}),e.jsx("h1",{className:"text-3xl font-black text-white tracking-tight mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-bold mb-1",style:{color:`${o.accent}cc`},children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-bold uppercase tracking-wider mb-1",style:{color:o.accent},children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-bold text-white/60 uppercase tracking-wider",children:s.team_name})]}),e.jsxs("div",{className:"max-w-md mx-auto px-5 -mt-6",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl px-5 py-8",children:[s.positioning_statement&&e.jsx("p",{className:"text-center font-bold text-lg leading-snug mb-6 max-w-xs mx-auto",style:{color:o.dark},children:s.positioning_statement}),e.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Mn,label:"Call",handler:u},{icon:Ui,label:"Text",handler:m},{icon:Ks,label:"Email",handler:f}].map(({icon:R,label:F,handler:O})=>e.jsxs("button",{onClick:O,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:o.dark},children:[e.jsx(R,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:F})]},F))}),e.jsxs("button",{onClick:x,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(vn,{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(fa,{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(ege,{card:s,variant:"bold"}),e.jsx(sge,{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(li,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ll(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(fa,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Dr,{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(xl,{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(Ec,{className:"h-4 w-4",style:{color:o.accent}})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-6",children:s.social_links.slice(0,3).map((R,F)=>e.jsx("a",{href:R.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ll(s.id,"button_click",`social_${R.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:o.dark},children:N[R.platform.toLowerCase()]||"🔗"},F))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(tge,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function cRt({card:s}){var j;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(N=>N[0]).join("").toUpperCase().slice(0,2),o=(N,C)=>{ll(s.id,"button_click",N),C()},c=()=>o("call",()=>{var N;(N=s.profile)!=null&&N.phone?window.location.href=`tel:${s.profile.phone}`:he.error("Phone number not available")}),d=()=>o("text",()=>{var N;(N=s.profile)!=null&&N.phone?window.location.href=`sms:${s.profile.phone}`:he.error("Phone number not available")}),u=()=>o("email",()=>{var N;(N=s.profile)!=null&&N.email?window.location.href=`mailto:${s.profile.email}`:he.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),ll(s.id,"button_click","book"))},f=()=>{var N,C;ll(s.id,"contact_saved"),rge({name:i,phone:(N=s.profile)==null?void 0:N.phone,email:(C=s.profile)==null?void 0:C.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{ll(s.id,"share_event");const N=`https://cards.relevelup.com/${s.slug}`,C="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:C,url:N})}catch{}else await navigator.clipboard.writeText(N),he.success("Link copied!")},y=()=>{a("referral"),r(!0),ll(s.id,"button_click","refer")},_=()=>{a("connect"),r(!0),ll(s.id,"button_click","connect")},b={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[e.jsx("div",{className:"bg-[#1b3a4b] h-2"}),e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Wn,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Xa,{src:s.avatar_url||void 0,alt:i}),e.jsx(Kn,{className:"text-2xl font-serif bg-[#1b3a4b] text-white",children:l})]}),e.jsx("h1",{className:"text-2xl font-serif font-bold text-[#1b3a4b] mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-[#4a5568] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',s.positioning_statement,'"']})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Mn,label:"Call",handler:c},{icon:Ui,label:"Text",handler:d},{icon:Ks,label:"Email",handler:u}].map(({icon:N,label:C,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(N,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:C})]},C))}),e.jsxs("button",{onClick:m,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[e.jsx(vn,{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(fa,{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(ege,{card:s,variant:"classic"}),e.jsx(sge,{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: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(li,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ll(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(fa,{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(Dr,{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(xl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Ec,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((N,C)=>e.jsx("a",{href:N.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ll(s.id,"button_click",`social_${N.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:b[N.platform.toLowerCase()]||"🔗"},C))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(tge,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function rTe({card:s}){switch(s.theme){case"luxury":return e.jsx(oRt,{card:s});case"bold":return e.jsx(lRt,{card:s});case"classic":return e.jsx(cRt,{card:s});case"standard":default:return e.jsx(iRt,{card:s})}}function dRt(){const s=vc();k.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):e.jsx(uRt,{slug:t})}function uRt({slug:s}){return e.jsx(hRt,{slug:s})}function hRt({slug:s}){var i;const{data:t,isLoading:r,error:n}=Wnt(s);if(k.useEffect(()=>{t!=null&&t.id&&ll(t.id,"card_view")},[t==null?void 0:t.id]),r)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(dr,{className:"h-28 w-28 rounded-full"}),e.jsx(dr,{className:"h-6 w-48"}),e.jsx(dr,{className:"h-4 w-36"})]}),e.jsx(dr,{className:"h-12 w-full"}),e.jsx(dr,{className:"h-12 w-full"})]})});if(n||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{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(rTe,{card:t})]})}function Xnt({presentationId:s,ctaLabel:t,agentName:r,prefillName:n,prefillEmail:a,prefillPhone:i}){const[l,o]=k.useState(n||""),[c,d]=k.useState(a||""),[u,m]=k.useState(i||""),[f,x]=k.useState(""),[y,_]=k.useState(""),[b,j]=k.useState(!1),[N,C]=k.useState(!1),A=async E=>{if(E.preventDefault(),!l.trim()){he.error("Please enter your name");return}j(!0);try{const{error:D}=await U.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:f||null,message:y.trim()||null});if(D)throw D;try{await U.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}U.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:f||void 0,message:y.trim()||void 0}}).catch(R=>console.error("Presentation lead notify failed:",R)),C(!0)}catch{he.error("Something went wrong. Please try again.")}finally{j(!1)}};return N?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(la,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:r?`${r} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:A,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(Ne,{id:"pres-lead-name",value:l,onChange:E=>o(E.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(Ne,{id:"pres-lead-phone",type:"tel",value:u,onChange:E=>m(E.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(Ne,{id:"pres-lead-email",type:"email",value:c,onChange:E=>d(E.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(Ds,{value:f,onValueChange:x,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select one"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"buy",children:"Buy a home"}),e.jsx(lt,{value:"sell",children:"Sell my home"}),e.jsx(lt,{value:"both",children:"Buy & Sell"}),e.jsx(lt,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(Ne,{id:"pres-lead-message",value:y,onChange:E=>_(E.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(q,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:b,children:b?"Sending...":t})]})}function mRt(){const s=vc();k.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):e.jsx(fRt,{shareToken:t})}function fRt({shareToken:s}){var y;const[t,r]=k.useState(null),[n,a]=k.useState(!0),[i,l]=k.useState(0),[o,c]=k.useState(!1);k.useEffect(()=>{d()},[s]);const d=async()=>{const{data:_,error:b}=await U.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(b||!_){c(!0),a(!1);return}const{data:j}=await U.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",_.owner_user_id).single();let N;if(j!=null&&j.brokerage_id){const{data:A}=await U.from("brokerages").select("name").eq("id",j.brokerage_id).single();N=(A==null?void 0:A.name)||void 0}let C=null;if(_.contact_id){const{data:A}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",_.contact_id).single();C=A}r({..._,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:N,contact_name:C?[C.first_name,C.last_name].filter(Boolean).join(" "):void 0,contact_email:(C==null?void 0:C.email)||void 0,contact_phone:(C==null?void 0:C.phone)||void 0}),a(!1);try{await U.rpc("log_presentation_view",{p_presentation_id:_.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await U.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},m=_=>{const b=_.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(b)return`https://www.youtube.com/embed/${b[1]}?rel=0`;if(_.includes("iframe.mediadelivery.net/play/")){const C=_.replace("/play/","/embed/"),A=C.includes("?")?"&":"?";return`${C}${A}responsive=true`}if(_.includes("iframe.mediadelivery.net")){const C=_.includes("?")?"&":"?";return`${_}${C}responsive=true`}const j=_.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(j)return`https://www.loom.com/embed/${j[1]}`;const N=_.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return N?`https://iframe.mediadelivery.net/embed/${N[1]}/${N[2]}?responsive=true`:_};if(n)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(dr,{className:"h-12 w-3/4 mx-auto"}),e.jsx(dr,{className:"h-64 w-full"}),e.jsx(dr,{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 f=t.sections.filter(_=>_.is_visible!==!1),x=f[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:[x!=null&&x.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:m(x.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):x!=null&&x.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:x.image_url,alt:x.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:x==null?void 0:x.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:x==null?void 0:x.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:x==null?void 0:x.description})]}),(x==null?void 0:x.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:x.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:f.map((_,b)=>e.jsx("button",{onClick:()=>l(b),className:zt("w-full text-left p-4 rounded-xl border transition-all",i===b?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(b+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:_.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})]})]})},b))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(y=t.cta_url)!=null&&y.trim()?e.jsxs(q,{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(un,{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(Xnt,{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 uv=()=>{const s=xa();return pt({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:r}=await U.from("team_members").select("id, team_id, role").eq("user_id",s).maybeSingle();if(console.log("[useUserTeam] membership query:",{userId:s,membership:t,error:r}),r)throw r;if(!t)return null;const{data:n,error:a}=await U.from("teams").select("*").eq("id",t.team_id).single();if(a)throw a;return{membershipId:t.id,teamId:t.team_id,role:t.role,team:n}},enabled:!!s,staleTime:5*60*1e3})};function pRt(){const{user:s}=Cs(),t=xa(),{data:r}=uv();return pt({queryKey:["open-houses",t,r==null?void 0:r.teamId,r==null?void 0:r.role],queryFn:async()=>{const{data:n,error:a}=await U.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=n||[];if((r==null?void 0:r.role)==="team_leader"&&r.teamId){const{data:l,error:o}=await U.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(m=>m.agent_id))],d={};if(c.length>0){const{data:m}=await U.from("profiles").select("id, name").in("id",c);m==null||m.forEach(f=>{f.name&&(d[f.id]=f.name)})}const u=l.map(m=>({...m,agent_name:d[m.agent_id]||void 0}));i=[...i,...u]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function Rnr(s){const{user:t}=Cs();return pt({queryKey:["open-house",s],queryFn:async()=>{const{data:r,error:n}=await U.from("open_houses").select("*").eq("id",s).single();if(n)throw n;return r},enabled:!!t&&!!s})}function Qnt(s){const{user:t}=Cs(),r=is();return k.useEffect(()=>{if(!s)return;const n=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=U.channel(n).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{r.invalidateQueries({queryKey:["open-house-visitors",s]}),r.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{U.removeChannel(a)}},[s,r]),pt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:n,error:a}=await U.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return n},enabled:!!t&&!!s})}function xRt(){const s=is(),t=xa();return Mt({mutationFn:async r=>{const{data:n,error:a}=await U.from("open_houses").insert({...r,agent_id:t}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Dn({title:"Open house created!"})},onError:r=>{Dn({title:"Error",description:r.message,variant:"destructive"})}})}function Jnt(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{error:n}=await U.from("open_houses").update(r).eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",r.id]})}})}function gRt(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("open_houses").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Dn({title:"Open house deleted"})}})}function yRt(s){return pt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:r}=await U.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(r)throw r;let n=null;if(t.agent_id){const{data:a}=await U.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(n=a.slug)}return{...t,agent_card_slug:n}},enabled:!!s})}function vRt(s){const{user:t}=Cs();return pt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:r,error:n}=await U.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;return r},enabled:!!t&&!!s})}function bRt(s){return pt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:r}=await U.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(r)throw r;return t},enabled:!!s})}function _Rt(){return Mt({mutationFn:async s=>{const{error:t}=await U.from("open_house_survey_responses").insert(s);if(t)throw t}})}function wRt(s){const{user:t}=Cs();return pt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:r,error:n}=await U.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const a=(r||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await U.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:r,responses:i||[]}},enabled:!!t&&!!s})}function jRt(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("open_house_survey_questions").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function NRt(){const s=is();return Mt({mutationFn:async({id:t,open_house_id:r,...n})=>{const{error:a}=await U.from("open_house_survey_questions").update(n).eq("id",t);if(a)throw a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function kRt(){const s=is();return Mt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await U.from("open_house_survey_questions").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function SRt(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.rpc("seed_default_survey_questions",{_open_house_id:t});if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r]})}})}function CRt(){return Mt({mutationFn:async s=>{const{data:t,error:r}=await U.from("open_house_visitors").insert(s).select("id").single();if(r)throw r;return t}})}function TRt(){return Mt({mutationFn:async({visitor_id:s,...t})=>{const{error:r}=await U.from("open_house_visitors").update(t).eq("id",s);if(r)throw r}})}function ERt(){return Mt({mutationFn:async s=>{await U.rpc("increment_open_house_scan",{_slug:s})}})}async function eat(s){const{data:t,error:r}=await U.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const n=t||[];if(n.length===0)return[];const a=n.map(c=>c.id),{data:i,error:l}=await U.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),n.map(c=>({...c,media:o[c.id]||[]}))}function ARt(s){const{user:t}=Cs();return pt({queryKey:["open-house-rooms",s],queryFn:()=>eat(s),enabled:!!t&&!!s})}function MRt(s){return pt({queryKey:["public-open-house-rooms",s],queryFn:()=>eat(s),enabled:!!s})}function IRt(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("open_house_rooms").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function PRt(){const s=is();return Mt({mutationFn:async({id:t,open_house_id:r,...n})=>{const{error:a}=await U.from("open_house_rooms").update(n).eq("id",t);if(a)throw a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function LRt(){const s=is();return Mt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await U.from("open_house_rooms").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function DRt(){const s=is();return Mt({mutationFn:async({open_house_id:t,...r})=>{const{data:n,error:a}=await U.from("open_house_room_media").insert(r).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function RRt(){const s=is();return Mt({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await U.from("open_house_room_media").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function ORt(s){const{user:t}=Cs();return pt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:r,error:n}=await U.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return r||[]},enabled:!!t&&!!s})}function FRt(){const s=is();return Mt({mutationFn:async({id:t,status:r,open_house_id:n})=>{const{error:a}=await U.from("open_house_leads").update({status:r}).eq("id",t);if(a)throw a;return{open_house_id:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var nge="Switch",[zRt,Onr]=bu(nge),[BRt,$Rt]=zRt(nge),tat=k.forwardRef((s,t)=>{const{__scopeSwitch:r,name:n,checked:a,defaultChecked:i,required:l,disabled:o,value:c="on",onCheckedChange:d,form:u,...m}=s,[f,x]=k.useState(null),y=_i(t,C=>x(C)),_=k.useRef(!1),b=f?u||!!f.closest("form"):!0,[j,N]=df({prop:a,defaultProp:i??!1,onChange:d,caller:nge});return e.jsxs(BRt,{scope:r,checked:j,disabled:o,children:[e.jsx(Yn.button,{type:"button",role:"switch","aria-checked":j,"aria-required":l,"data-state":aat(j),"data-disabled":o?"":void 0,disabled:o,value:c,...m,ref:y,onClick:dn(s.onClick,C=>{N(A=>!A),b&&(_.current=C.isPropagationStopped(),_.current||C.stopPropagation())})}),b&&e.jsx(nat,{control:f,bubbles:!_.current,name:n,value:c,checked:j,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});tat.displayName=nge;var sat="SwitchThumb",rat=k.forwardRef((s,t)=>{const{__scopeSwitch:r,...n}=s,a=$Rt(sat,r);return e.jsx(Yn.span,{"data-state":aat(a.checked),"data-disabled":a.disabled?"":void 0,...n,ref:t})});rat.displayName=sat;var URt="SwitchBubbleInput",nat=k.forwardRef(({__scopeSwitch:s,control:t,checked:r,bubbles:n=!0,...a},i)=>{const l=k.useRef(null),o=_i(l,i),c=yB(r),d=rB(t);return k.useEffect(()=>{const u=l.current;if(!u)return;const m=window.HTMLInputElement.prototype,x=Object.getOwnPropertyDescriptor(m,"checked").set;if(c!==r&&x){const y=new Event("click",{bubbles:n});x.call(u,r),u.dispatchEvent(y)}},[c,r,n]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});nat.displayName=URt;function aat(s){return s?"checked":"unchecked"}var iat=tat,qRt=rat;const Rr=k.forwardRef(({className:s,...t},r)=>e.jsx(iat,{className:zt("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",s),...t,ref:r,children:e.jsx(qRt,{className:zt("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")})}));Rr.displayName=iat.displayName;function Wa(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 hc(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Dc(s,t){const r=Wa(s);return isNaN(t)?hc(s,NaN):(t&&r.setDate(r.getDate()+t),r)}function Ex(s,t){const r=Wa(s);if(isNaN(t))return hc(s,NaN);if(!t)return r;const n=r.getDate(),a=hc(s,r.getTime());a.setMonth(r.getMonth()+t+1,0);const i=a.getDate();return n>=i?a:(r.setFullYear(a.getFullYear(),a.getMonth(),n),r)}function oat(s,t){const r=+Wa(s);return hc(s,r+t)}const nTe=6048e5,VRt=864e5,age=6e4,vB=36e5,HRt=1e3,dq=43200,GFe=1440;function WFe(s,t){return oat(s,t*vB)}let GRt={};function e4(){return GRt}function Mp(s,t){var o,c,d,u;const r=e4(),n=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((u=(d=r.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=Wa(s),i=a.getDay(),l=(i=a.getTime()?r+1:t.getTime()>=l.getTime()?r:r-1}function Ax(s){const t=Wa(s);return t.setHours(0,0,0,0),t}function LS(s){const t=Wa(s),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+s-+r}function cg(s,t){const r=Ax(s),n=Ax(t),a=+r-LS(r),i=+n-LS(n);return Math.round((a-i)/VRt)}function WRt(s){const t=lat(s),r=hc(s,0);return r.setFullYear(t,0,4),r.setHours(0,0,0,0),C2(r)}function vI(s,t){return oat(s,t*age)}function KT(s,t){const r=t*7;return Dc(s,r)}function KRt(s,t){return Ex(s,t*12)}function YRt(s){let t;return s.forEach(function(r){const n=Wa(r);(t===void 0||t{const n=Wa(r);(!t||t>n||isNaN(+n))&&(t=n)}),t||new Date(NaN)}function Fue(s,t){const r=Wa(s),n=Wa(t),a=r.getTime()-n.getTime();return a<0?-1:a>0?1:a}function aTe(s){return hc(s,Date.now())}function pc(s,t){const r=Ax(s),n=Ax(t);return+r==+n}function iTe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function ZNe(s){if(!iTe(s)&&typeof s!="number")return!1;const t=Wa(s);return!isNaN(Number(t))}function dL(s,t){const r=Wa(s),n=Wa(t),a=r.getFullYear()-n.getFullYear(),i=r.getMonth()-n.getMonth();return a*12+i}function XRt(s,t,r){const n=Mp(s,r),a=Mp(t,r),i=+n-LS(n),l=+a-LS(a);return Math.round((i-l)/nTe)}function lv(s,t){const r=Wa(s),n=Wa(t),a=KFe(r,n),i=Math.abs(cg(r,n));r.setDate(r.getDate()-a*i);const l=+(KFe(r,n)===-a),o=a*(i-l);return o===0?0:o}function KFe(s,t){const r=s.getFullYear()-t.getFullYear()||s.getMonth()-t.getMonth()||s.getDate()-t.getDate()||s.getHours()-t.getHours()||s.getMinutes()-t.getMinutes()||s.getSeconds()-t.getSeconds()||s.getMilliseconds()-t.getMilliseconds();return r<0?-1:r>0?1:r}function cat(s){return t=>{const r=Math.trunc,n=r(t);return n===0?0:n}}function dat(s,t){return+Wa(s)-+Wa(t)}function QRt(s,t,r){const n=dat(s,t)/vB;return cat()(n)}function JRt(s){const t=Wa(s);return t.setHours(23,59,59,999),t}function Py(s){const t=Wa(s),r=t.getMonth();return t.setFullYear(t.getFullYear(),r+1,0),t.setHours(23,59,59,999),t}function eOt(s){const t=Wa(s);return+JRt(t)==+Py(t)}function tOt(s,t){const r=Wa(s),n=Wa(t),a=Fue(r,n),i=Math.abs(dL(r,n));let l;if(i<1)l=0;else{r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-a*i);let o=Fue(r,n)===-a;eOt(Wa(s))&&i===1&&Fue(s,n)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function sOt(s,t,r){const n=dat(s,t)/1e3;return cat()(n)}function rOt(s,t){const r=Wa(s.start),n=Wa(s.end);let a=+r>+n;const i=a?+r:+n,l=a?n:r;l.setHours(0,0,0,0);let o=1;const c=[];for(;+l<=i;)c.push(Wa(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function qd(s){const t=Wa(s);return t.setDate(1),t.setHours(0,0,0,0),t}function uat(s){const t=Wa(s),r=hc(s,0);return r.setFullYear(t.getFullYear(),0,1),r.setHours(0,0,0,0),r}function ige(s,t){var o,c,d,u;const r=e4(),n=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((u=(d=r.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=Wa(s),i=a.getDay(),l=(i{let n;const a=nOt[s];return typeof a=="string"?n=a:t===1?n=a.one:n=a.other.replace("{{count}}",t.toString()),r!=null&&r.addSuffix?r.comparison&&r.comparison>0?"in "+n:n+" ago":n};function Ube(s){return(t={})=>{const r=t.width?String(t.width):s.defaultWidth;return s.formats[r]||s.formats[s.defaultWidth]}}const iOt={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},oOt={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},lOt={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},cOt={date:Ube({formats:iOt,defaultWidth:"full"}),time:Ube({formats:oOt,defaultWidth:"full"}),dateTime:Ube({formats:lOt,defaultWidth:"full"})},dOt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},uOt=(s,t,r,n)=>dOt[s];function OR(s){return(t,r)=>{const n=r!=null&&r.context?String(r.context):"standalone";let a;if(n==="formatting"&&s.formattingValues){const l=s.defaultFormattingWidth||s.defaultWidth,o=r!=null&&r.width?String(r.width):l;a=s.formattingValues[o]||s.formattingValues[l]}else{const l=s.defaultWidth,o=r!=null&&r.width?String(r.width):s.defaultWidth;a=s.values[o]||s.values[l]}const i=s.argumentCallback?s.argumentCallback(t):t;return a[i]}}const hOt={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},mOt={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},fOt={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"]},pOt={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"]},xOt={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"}},gOt={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"}},yOt=(s,t)=>{const r=Number(s),n=r%100;if(n>20||n<10)switch(n%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},vOt={ordinalNumber:yOt,era:OR({values:hOt,defaultWidth:"wide"}),quarter:OR({values:mOt,defaultWidth:"wide",argumentCallback:s=>s-1}),month:OR({values:fOt,defaultWidth:"wide"}),day:OR({values:pOt,defaultWidth:"wide"}),dayPeriod:OR({values:xOt,defaultWidth:"wide",formattingValues:gOt,defaultFormattingWidth:"wide"})};function FR(s){return(t,r={})=>{const n=r.width,a=n&&s.matchPatterns[n]||s.matchPatterns[s.defaultMatchWidth],i=t.match(a);if(!i)return null;const l=i[0],o=n&&s.parsePatterns[n]||s.parsePatterns[s.defaultParseWidth],c=Array.isArray(o)?_Ot(o,m=>m.test(l)):bOt(o,m=>m.test(l));let d;d=s.valueCallback?s.valueCallback(c):c,d=r.valueCallback?r.valueCallback(d):d;const u=t.slice(l.length);return{value:d,rest:u}}}function bOt(s,t){for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)&&t(s[r]))return r}function _Ot(s,t){for(let r=0;r{const n=t.match(s.matchPattern);if(!n)return null;const a=n[0],i=t.match(s.parsePattern);if(!i)return null;let l=s.valueCallback?s.valueCallback(i[0]):i[0];l=r.valueCallback?r.valueCallback(l):l;const o=t.slice(a.length);return{value:l,rest:o}}}const jOt=/^(\d+)(th|st|nd|rd)?/i,NOt=/\d+/i,kOt={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},SOt={any:[/^b/i,/^(a|c)/i]},COt={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},TOt={any:[/1/i,/2/i,/3/i,/4/i]},EOt={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},AOt={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]},MOt={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},IOt={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]},POt={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},LOt={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}},DOt={ordinalNumber:wOt({matchPattern:jOt,parsePattern:NOt,valueCallback:s=>parseInt(s,10)}),era:FR({matchPatterns:kOt,defaultMatchWidth:"wide",parsePatterns:SOt,defaultParseWidth:"any"}),quarter:FR({matchPatterns:COt,defaultMatchWidth:"wide",parsePatterns:TOt,defaultParseWidth:"any",valueCallback:s=>s+1}),month:FR({matchPatterns:EOt,defaultMatchWidth:"wide",parsePatterns:AOt,defaultParseWidth:"any"}),day:FR({matchPatterns:MOt,defaultMatchWidth:"wide",parsePatterns:IOt,defaultParseWidth:"any"}),dayPeriod:FR({matchPatterns:POt,defaultMatchWidth:"any",parsePatterns:LOt,defaultParseWidth:"any"})},oge={code:"en-US",formatDistance:aOt,formatLong:cOt,formatRelative:uOt,localize:vOt,match:DOt,options:{weekStartsOn:0,firstWeekContainsDate:1}};function ROt(s){const t=Wa(s);return cg(t,uat(t))+1}function oTe(s){const t=Wa(s),r=+C2(t)-+WRt(t);return Math.round(r/nTe)+1}function lTe(s,t){var u,m,f,x;const r=Wa(s),n=r.getFullYear(),a=e4(),i=(t==null?void 0:t.firstWeekContainsDate)??((m=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:m.firstWeekContainsDate)??a.firstWeekContainsDate??((x=(f=a.locale)==null?void 0:f.options)==null?void 0:x.firstWeekContainsDate)??1,l=hc(s,0);l.setFullYear(n+1,0,i),l.setHours(0,0,0,0);const o=Mp(l,t),c=hc(s,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const d=Mp(c,t);return r.getTime()>=o.getTime()?n+1:r.getTime()>=d.getTime()?n:n-1}function OOt(s,t){var o,c,d,u;const r=e4(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.firstWeekContainsDate)??r.firstWeekContainsDate??((u=(d=r.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,a=lTe(s,t),i=hc(s,0);return i.setFullYear(a,0,n),i.setHours(0,0,0,0),Mp(i,t)}function cTe(s,t){const r=Wa(s),n=+Mp(r,t)-+OOt(r,t);return Math.round(n/nTe)+1}function dc(s,t){const r=s<0?"-":"",n=Math.abs(s).toString().padStart(t,"0");return r+n}const ON={y(s,t){const r=s.getFullYear(),n=r>0?r:1-r;return dc(t==="yy"?n%100:n,t.length)},M(s,t){const r=s.getMonth();return t==="M"?String(r+1):dc(r+1,2)},d(s,t){return dc(s.getDate(),t.length)},a(s,t){const r=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(s,t){return dc(s.getHours()%12||12,t.length)},H(s,t){return dc(s.getHours(),t.length)},m(s,t){return dc(s.getMinutes(),t.length)},s(s,t){return dc(s.getSeconds(),t.length)},S(s,t){const r=t.length,n=s.getMilliseconds(),a=Math.trunc(n*Math.pow(10,r-3));return dc(a,t.length)}},w6={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},YFe={G:function(s,t,r){const n=s.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return r.era(n,{width:"abbreviated"});case"GGGGG":return r.era(n,{width:"narrow"});case"GGGG":default:return r.era(n,{width:"wide"})}},y:function(s,t,r){if(t==="yo"){const n=s.getFullYear(),a=n>0?n:1-n;return r.ordinalNumber(a,{unit:"year"})}return ON.y(s,t)},Y:function(s,t,r,n){const a=lTe(s,n),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return dc(l,2)}return t==="Yo"?r.ordinalNumber(i,{unit:"year"}):dc(i,t.length)},R:function(s,t){const r=lat(s);return dc(r,t.length)},u:function(s,t){const r=s.getFullYear();return dc(r,t.length)},Q:function(s,t,r){const n=Math.ceil((s.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return dc(n,2);case"Qo":return r.ordinalNumber(n,{unit:"quarter"});case"QQQ":return r.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return r.quarter(n,{width:"wide",context:"formatting"})}},q:function(s,t,r){const n=Math.ceil((s.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return dc(n,2);case"qo":return r.ordinalNumber(n,{unit:"quarter"});case"qqq":return r.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return r.quarter(n,{width:"wide",context:"standalone"})}},M:function(s,t,r){const n=s.getMonth();switch(t){case"M":case"MM":return ON.M(s,t);case"Mo":return r.ordinalNumber(n+1,{unit:"month"});case"MMM":return r.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return r.month(n,{width:"wide",context:"formatting"})}},L:function(s,t,r){const n=s.getMonth();switch(t){case"L":return String(n+1);case"LL":return dc(n+1,2);case"Lo":return r.ordinalNumber(n+1,{unit:"month"});case"LLL":return r.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return r.month(n,{width:"wide",context:"standalone"})}},w:function(s,t,r,n){const a=cTe(s,n);return t==="wo"?r.ordinalNumber(a,{unit:"week"}):dc(a,t.length)},I:function(s,t,r){const n=oTe(s);return t==="Io"?r.ordinalNumber(n,{unit:"week"}):dc(n,t.length)},d:function(s,t,r){return t==="do"?r.ordinalNumber(s.getDate(),{unit:"date"}):ON.d(s,t)},D:function(s,t,r){const n=ROt(s);return t==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):dc(n,t.length)},E:function(s,t,r){const n=s.getDay();switch(t){case"E":case"EE":case"EEE":return r.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(n,{width:"short",context:"formatting"});case"EEEE":default:return r.day(n,{width:"wide",context:"formatting"})}},e:function(s,t,r,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return dc(i,2);case"eo":return r.ordinalNumber(i,{unit:"day"});case"eee":return r.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(a,{width:"short",context:"formatting"});case"eeee":default:return r.day(a,{width:"wide",context:"formatting"})}},c:function(s,t,r,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return dc(i,t.length);case"co":return r.ordinalNumber(i,{unit:"day"});case"ccc":return r.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(a,{width:"narrow",context:"standalone"});case"cccccc":return r.day(a,{width:"short",context:"standalone"});case"cccc":default:return r.day(a,{width:"wide",context:"standalone"})}},i:function(s,t,r){const n=s.getDay(),a=n===0?7:n;switch(t){case"i":return String(a);case"ii":return dc(a,t.length);case"io":return r.ordinalNumber(a,{unit:"day"});case"iii":return r.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(n,{width:"short",context:"formatting"});case"iiii":default:return r.day(n,{width:"wide",context:"formatting"})}},a:function(s,t,r){const a=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(s,t,r){const n=s.getHours();let a;switch(n===12?a=w6.noon:n===0?a=w6.midnight:a=n/12>=1?"pm":"am",t){case"b":case"bb":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(s,t,r){const n=s.getHours();let a;switch(n>=17?a=w6.evening:n>=12?a=w6.afternoon:n>=4?a=w6.morning:a=w6.night,t){case"B":case"BB":case"BBB":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(s,t,r){if(t==="ho"){let n=s.getHours()%12;return n===0&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return ON.h(s,t)},H:function(s,t,r){return t==="Ho"?r.ordinalNumber(s.getHours(),{unit:"hour"}):ON.H(s,t)},K:function(s,t,r){const n=s.getHours()%12;return t==="Ko"?r.ordinalNumber(n,{unit:"hour"}):dc(n,t.length)},k:function(s,t,r){let n=s.getHours();return n===0&&(n=24),t==="ko"?r.ordinalNumber(n,{unit:"hour"}):dc(n,t.length)},m:function(s,t,r){return t==="mo"?r.ordinalNumber(s.getMinutes(),{unit:"minute"}):ON.m(s,t)},s:function(s,t,r){return t==="so"?r.ordinalNumber(s.getSeconds(),{unit:"second"}):ON.s(s,t)},S:function(s,t){return ON.S(s,t)},X:function(s,t,r){const n=s.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return XFe(n);case"XXXX":case"XX":return LT(n);case"XXXXX":case"XXX":default:return LT(n,":")}},x:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"x":return XFe(n);case"xxxx":case"xx":return LT(n);case"xxxxx":case"xxx":default:return LT(n,":")}},O:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+ZFe(n,":");case"OOOO":default:return"GMT"+LT(n,":")}},z:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+ZFe(n,":");case"zzzz":default:return"GMT"+LT(n,":")}},t:function(s,t,r){const n=Math.trunc(s.getTime()/1e3);return dc(n,t.length)},T:function(s,t,r){const n=s.getTime();return dc(n,t.length)}};function ZFe(s,t=""){const r=s>0?"-":"+",n=Math.abs(s),a=Math.trunc(n/60),i=n%60;return i===0?r+String(a):r+String(a)+t+dc(i,2)}function XFe(s,t){return s%60===0?(s>0?"-":"+")+dc(Math.abs(s)/60,2):LT(s,t)}function LT(s,t=""){const r=s>0?"-":"+",n=Math.abs(s),a=dc(Math.trunc(n/60),2),i=dc(n%60,2);return r+a+t+i}const QFe=(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"})}},mat=(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"})}},FOt=(s,t)=>{const r=s.match(/(P+)(p+)?/)||[],n=r[1],a=r[2];if(!a)return QFe(s,t);let i;switch(n){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;case"PPPP":default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",QFe(n,t)).replace("{{time}}",mat(a,t))},XNe={p:mat,P:FOt},zOt=/^D+$/,BOt=/^Y+$/,$Ot=["D","DD","YY","YYYY"];function fat(s){return zOt.test(s)}function pat(s){return BOt.test(s)}function QNe(s,t,r){const n=UOt(s,t,r);if(console.warn(n),$Ot.includes(s))throw new RangeError(n)}function UOt(s,t,r){const n=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${t}\`) for formatting ${n} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const qOt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,VOt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,HOt=/^'([^]*?)'?$/,GOt=/''/g,WOt=/[a-zA-Z]/;function As(s,t,r){var u,m,f,x,y,_,b,j;const n=e4(),a=(r==null?void 0:r.locale)??n.locale??oge,i=(r==null?void 0:r.firstWeekContainsDate)??((m=(u=r==null?void 0:r.locale)==null?void 0:u.options)==null?void 0:m.firstWeekContainsDate)??n.firstWeekContainsDate??((x=(f=n.locale)==null?void 0:f.options)==null?void 0:x.firstWeekContainsDate)??1,l=(r==null?void 0:r.weekStartsOn)??((_=(y=r==null?void 0:r.locale)==null?void 0:y.options)==null?void 0:_.weekStartsOn)??n.weekStartsOn??((j=(b=n.locale)==null?void 0:b.options)==null?void 0:j.weekStartsOn)??0,o=Wa(s);if(!ZNe(o))throw new RangeError("Invalid time value");let c=t.match(VOt).map(N=>{const C=N[0];if(C==="p"||C==="P"){const A=XNe[C];return A(N,a.formatLong)}return N}).join("").match(qOt).map(N=>{if(N==="''")return{isToken:!1,value:"'"};const C=N[0];if(C==="'")return{isToken:!1,value:KOt(N)};if(YFe[C])return{isToken:!0,value:N};if(C.match(WOt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+C+"`");return{isToken:!1,value:N}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(N=>{if(!N.isToken)return N.value;const C=N.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&pat(C)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&fat(C))&&QNe(C,t,String(s));const A=YFe[C[0]];return A(o,C,a.localize,d)}).join("")}function KOt(s){const t=s.match(HOt);return t?t[1].replace(GOt,"'"):s}function YOt(s,t,r){const n=e4(),a=(r==null?void 0:r.locale)??n.locale??oge,i=2520,l=Fue(s,t);if(isNaN(l))throw new RangeError("Invalid time value");const o=Object.assign({},r,{addSuffix:r==null?void 0:r.addSuffix,comparison:l});let c,d;l>0?(c=Wa(t),d=Wa(s)):(c=Wa(s),d=Wa(t));const u=sOt(d,c),m=(LS(d)-LS(c))/1e3,f=Math.round((u-m)/60);let x;if(f<2)return r!=null&&r.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):f===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",f,o);if(f<45)return a.formatDistance("xMinutes",f,o);if(f<90)return a.formatDistance("aboutXHours",1,o);if(fn.getTime()}function gS(s,t){const r=Wa(s),n=Wa(t);return+r<+n}function sFt(s){return+Wa(s)>Date.now()}function rFt(s,t){const r=t instanceof Date?hc(t,0):new t(0);return r.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),r.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),r}const nFt=10;class xat{constructor(){_a(this,"subPriority",0)}validate(t,r){return!0}}class aFt extends xat{constructor(t,r,n,a,i){super(),this.value=t,this.validateValue=r,this.setValue=n,this.priority=a,i&&(this.subPriority=i)}validate(t,r){return this.validateValue(t,this.value,r)}set(t,r,n){return this.setValue(t,r,this.value,n)}}class iFt extends xat{constructor(){super(...arguments);_a(this,"priority",nFt);_a(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:hc(r,rFt(r,Date))}}class Jl{run(t,r,n,a){const i=this.parse(t,r,n,a);return i?{setter:new aFt(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,r,n){return!0}}class oFt extends Jl{constructor(){super(...arguments);_a(this,"priority",140);_a(this,"incompatibleTokens",["R","u","t","T"])}parse(r,n,a){switch(n){case"G":case"GG":case"GGG":return a.era(r,{width:"abbreviated"})||a.era(r,{width:"narrow"});case"GGGGG":return a.era(r,{width:"narrow"});case"GGGG":default:return a.era(r,{width:"wide"})||a.era(r,{width:"abbreviated"})||a.era(r,{width:"narrow"})}}set(r,n,a){return n.era=a,r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}}const dh={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}/},i_={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 uh(s,t){return s&&{value:t(s.value),rest:s.rest}}function hu(s,t){const r=t.match(s);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function o_(s,t){const r=t.match(s);if(!r)return null;if(r[0]==="Z")return{value:0,rest:t.slice(1)};const n=r[1]==="+"?1:-1,a=r[2]?parseInt(r[2],10):0,i=r[3]?parseInt(r[3],10):0,l=r[5]?parseInt(r[5],10):0;return{value:n*(a*vB+i*age+l*HRt),rest:t.slice(r[0].length)}}function gat(s){return hu(dh.anyDigitsSigned,s)}function Wu(s,t){switch(s){case 1:return hu(dh.singleDigit,t);case 2:return hu(dh.twoDigits,t);case 3:return hu(dh.threeDigits,t);case 4:return hu(dh.fourDigits,t);default:return hu(new RegExp("^\\d{1,"+s+"}"),t)}}function lme(s,t){switch(s){case 1:return hu(dh.singleDigitSigned,t);case 2:return hu(dh.twoDigitsSigned,t);case 3:return hu(dh.threeDigitsSigned,t);case 4:return hu(dh.fourDigitsSigned,t);default:return hu(new RegExp("^-?\\d{1,"+s+"}"),t)}}function dTe(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 yat(s,t){const r=t>0,n=r?t:1-t;let a;if(n<=50)a=s||100;else{const i=n+50,l=Math.trunc(i/100)*100,o=s>=i%100;a=s+l-(o?100:0)}return r?a:1-a}function vat(s){return s%400===0||s%4===0&&s%100!==0}class lFt extends Jl{constructor(){super(...arguments);_a(this,"priority",130);_a(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(r,n,a){const i=l=>({year:l,isTwoDigitYear:n==="yy"});switch(n){case"y":return uh(Wu(4,r),i);case"yo":return uh(a.ordinalNumber(r,{unit:"year"}),i);default:return uh(Wu(n.length,r),i)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,a){const i=r.getFullYear();if(a.isTwoDigitYear){const o=yat(a.year,i);return r.setFullYear(o,0,1),r.setHours(0,0,0,0),r}const l=!("era"in n)||n.era===1?a.year:1-a.year;return r.setFullYear(l,0,1),r.setHours(0,0,0,0),r}}class cFt extends Jl{constructor(){super(...arguments);_a(this,"priority",130);_a(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(r,n,a){const i=l=>({year:l,isTwoDigitYear:n==="YY"});switch(n){case"Y":return uh(Wu(4,r),i);case"Yo":return uh(a.ordinalNumber(r,{unit:"year"}),i);default:return uh(Wu(n.length,r),i)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,a,i){const l=lTe(r,i);if(a.isTwoDigitYear){const c=yat(a.year,l);return r.setFullYear(c,0,i.firstWeekContainsDate),r.setHours(0,0,0,0),Mp(r,i)}const o=!("era"in n)||n.era===1?a.year:1-a.year;return r.setFullYear(o,0,i.firstWeekContainsDate),r.setHours(0,0,0,0),Mp(r,i)}}class dFt extends Jl{constructor(){super(...arguments);_a(this,"priority",130);_a(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(r,n){return lme(n==="R"?4:n.length,r)}set(r,n,a){const i=hc(r,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),C2(i)}}class uFt extends Jl{constructor(){super(...arguments);_a(this,"priority",130);_a(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(r,n){return lme(n==="u"?4:n.length,r)}set(r,n,a){return r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}}class hFt extends Jl{constructor(){super(...arguments);_a(this,"priority",120);_a(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"Q":case"QQ":return Wu(n.length,r);case"Qo":return a.ordinalNumber(r,{unit:"quarter"});case"QQQ":return a.quarter(r,{width:"abbreviated",context:"formatting"})||a.quarter(r,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(r,{width:"wide",context:"formatting"})||a.quarter(r,{width:"abbreviated",context:"formatting"})||a.quarter(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=1&&n<=4}set(r,n,a){return r.setMonth((a-1)*3,1),r.setHours(0,0,0,0),r}}class mFt extends Jl{constructor(){super(...arguments);_a(this,"priority",120);_a(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"q":case"qq":return Wu(n.length,r);case"qo":return a.ordinalNumber(r,{unit:"quarter"});case"qqq":return a.quarter(r,{width:"abbreviated",context:"standalone"})||a.quarter(r,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(r,{width:"wide",context:"standalone"})||a.quarter(r,{width:"abbreviated",context:"standalone"})||a.quarter(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=1&&n<=4}set(r,n,a){return r.setMonth((a-1)*3,1),r.setHours(0,0,0,0),r}}class fFt extends Jl{constructor(){super(...arguments);_a(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);_a(this,"priority",110)}parse(r,n,a){const i=l=>l-1;switch(n){case"M":return uh(hu(dh.month,r),i);case"MM":return uh(Wu(2,r),i);case"Mo":return uh(a.ordinalNumber(r,{unit:"month"}),i);case"MMM":return a.month(r,{width:"abbreviated",context:"formatting"})||a.month(r,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(r,{width:"wide",context:"formatting"})||a.month(r,{width:"abbreviated",context:"formatting"})||a.month(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.setMonth(a,1),r.setHours(0,0,0,0),r}}class pFt extends Jl{constructor(){super(...arguments);_a(this,"priority",110);_a(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(r,n,a){const i=l=>l-1;switch(n){case"L":return uh(hu(dh.month,r),i);case"LL":return uh(Wu(2,r),i);case"Lo":return uh(a.ordinalNumber(r,{unit:"month"}),i);case"LLL":return a.month(r,{width:"abbreviated",context:"standalone"})||a.month(r,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(r,{width:"wide",context:"standalone"})||a.month(r,{width:"abbreviated",context:"standalone"})||a.month(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.setMonth(a,1),r.setHours(0,0,0,0),r}}function xFt(s,t,r){const n=Wa(s),a=cTe(n,r)-t;return n.setDate(n.getDate()-a*7),n}class gFt extends Jl{constructor(){super(...arguments);_a(this,"priority",100);_a(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(r,n,a){switch(n){case"w":return hu(dh.week,r);case"wo":return a.ordinalNumber(r,{unit:"week"});default:return Wu(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,a,i){return Mp(xFt(r,a,i),i)}}function yFt(s,t){const r=Wa(s),n=oTe(r)-t;return r.setDate(r.getDate()-n*7),r}class vFt extends Jl{constructor(){super(...arguments);_a(this,"priority",100);_a(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(r,n,a){switch(n){case"I":return hu(dh.week,r);case"Io":return a.ordinalNumber(r,{unit:"week"});default:return Wu(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,a){return C2(yFt(r,a))}}const bFt=[31,28,31,30,31,30,31,31,30,31,30,31],_Ft=[31,29,31,30,31,30,31,31,30,31,30,31];class wFt extends Jl{constructor(){super(...arguments);_a(this,"priority",90);_a(this,"subPriority",1);_a(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"d":return hu(dh.date,r);case"do":return a.ordinalNumber(r,{unit:"date"});default:return Wu(n.length,r)}}validate(r,n){const a=r.getFullYear(),i=vat(a),l=r.getMonth();return i?n>=1&&n<=_Ft[l]:n>=1&&n<=bFt[l]}set(r,n,a){return r.setDate(a),r.setHours(0,0,0,0),r}}class jFt extends Jl{constructor(){super(...arguments);_a(this,"priority",90);_a(this,"subpriority",1);_a(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(r,n,a){switch(n){case"D":case"DD":return hu(dh.dayOfYear,r);case"Do":return a.ordinalNumber(r,{unit:"date"});default:return Wu(n.length,r)}}validate(r,n){const a=r.getFullYear();return vat(a)?n>=1&&n<=366:n>=1&&n<=365}set(r,n,a){return r.setMonth(0,a),r.setHours(0,0,0,0),r}}function uTe(s,t,r){var m,f,x,y;const n=e4(),a=(r==null?void 0:r.weekStartsOn)??((f=(m=r==null?void 0:r.locale)==null?void 0:m.options)==null?void 0:f.weekStartsOn)??n.weekStartsOn??((y=(x=n.locale)==null?void 0:x.options)==null?void 0:y.weekStartsOn)??0,i=Wa(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 Dc(i,u)}class NFt extends Jl{constructor(){super(...arguments);_a(this,"priority",90);_a(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"E":case"EE":case"EEE":return a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=uTe(r,a,i),r.setHours(0,0,0,0),r}}class kFt extends Jl{constructor(){super(...arguments);_a(this,"priority",90);_a(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(r,n,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(n){case"e":case"ee":return uh(Wu(n.length,r),l);case"eo":return uh(a.ordinalNumber(r,{unit:"day"}),l);case"eee":return a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"eeeee":return a.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=uTe(r,a,i),r.setHours(0,0,0,0),r}}class SFt extends Jl{constructor(){super(...arguments);_a(this,"priority",90);_a(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(r,n,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(n){case"c":case"cc":return uh(Wu(n.length,r),l);case"co":return uh(a.ordinalNumber(r,{unit:"day"}),l);case"ccc":return a.day(r,{width:"abbreviated",context:"standalone"})||a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"});case"ccccc":return a.day(r,{width:"narrow",context:"standalone"});case"cccccc":return a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(r,{width:"wide",context:"standalone"})||a.day(r,{width:"abbreviated",context:"standalone"})||a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=uTe(r,a,i),r.setHours(0,0,0,0),r}}function CFt(s,t){const r=Wa(s),n=QOt(r),a=t-n;return Dc(r,a)}class TFt extends Jl{constructor(){super(...arguments);_a(this,"priority",90);_a(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(r,n,a){const i=l=>l===0?7:l;switch(n){case"i":case"ii":return Wu(n.length,r);case"io":return a.ordinalNumber(r,{unit:"day"});case"iii":return uh(a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i);case"iiiii":return uh(a.day(r,{width:"narrow",context:"formatting"}),i);case"iiiiii":return uh(a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i);case"iiii":default:return uh(a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i)}}validate(r,n){return n>=1&&n<=7}set(r,n,a){return r=CFt(r,a),r.setHours(0,0,0,0),r}}class EFt extends Jl{constructor(){super(...arguments);_a(this,"priority",80);_a(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(r,n,a){switch(n){case"a":case"aa":case"aaa":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(dTe(a),0,0,0),r}}class AFt extends Jl{constructor(){super(...arguments);_a(this,"priority",80);_a(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(r,n,a){switch(n){case"b":case"bb":case"bbb":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(dTe(a),0,0,0),r}}class MFt extends Jl{constructor(){super(...arguments);_a(this,"priority",80);_a(this,"incompatibleTokens",["a","b","t","T"])}parse(r,n,a){switch(n){case"B":case"BB":case"BBB":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(dTe(a),0,0,0),r}}class IFt extends Jl{constructor(){super(...arguments);_a(this,"priority",70);_a(this,"incompatibleTokens",["H","K","k","t","T"])}parse(r,n,a){switch(n){case"h":return hu(dh.hour12h,r);case"ho":return a.ordinalNumber(r,{unit:"hour"});default:return Wu(n.length,r)}}validate(r,n){return n>=1&&n<=12}set(r,n,a){const i=r.getHours()>=12;return i&&a<12?r.setHours(a+12,0,0,0):!i&&a===12?r.setHours(0,0,0,0):r.setHours(a,0,0,0),r}}class PFt extends Jl{constructor(){super(...arguments);_a(this,"priority",70);_a(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(r,n,a){switch(n){case"H":return hu(dh.hour23h,r);case"Ho":return a.ordinalNumber(r,{unit:"hour"});default:return Wu(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,a){return r.setHours(a,0,0,0),r}}class LFt extends Jl{constructor(){super(...arguments);_a(this,"priority",70);_a(this,"incompatibleTokens",["h","H","k","t","T"])}parse(r,n,a){switch(n){case"K":return hu(dh.hour11h,r);case"Ko":return a.ordinalNumber(r,{unit:"hour"});default:return Wu(n.length,r)}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.getHours()>=12&&a<12?r.setHours(a+12,0,0,0):r.setHours(a,0,0,0),r}}class DFt extends Jl{constructor(){super(...arguments);_a(this,"priority",70);_a(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(r,n,a){switch(n){case"k":return hu(dh.hour24h,r);case"ko":return a.ordinalNumber(r,{unit:"hour"});default:return Wu(n.length,r)}}validate(r,n){return n>=1&&n<=24}set(r,n,a){const i=a<=24?a%24:a;return r.setHours(i,0,0,0),r}}class RFt extends Jl{constructor(){super(...arguments);_a(this,"priority",60);_a(this,"incompatibleTokens",["t","T"])}parse(r,n,a){switch(n){case"m":return hu(dh.minute,r);case"mo":return a.ordinalNumber(r,{unit:"minute"});default:return Wu(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,a){return r.setMinutes(a,0,0),r}}class OFt extends Jl{constructor(){super(...arguments);_a(this,"priority",50);_a(this,"incompatibleTokens",["t","T"])}parse(r,n,a){switch(n){case"s":return hu(dh.second,r);case"so":return a.ordinalNumber(r,{unit:"second"});default:return Wu(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,a){return r.setSeconds(a,0),r}}class FFt extends Jl{constructor(){super(...arguments);_a(this,"priority",30);_a(this,"incompatibleTokens",["t","T"])}parse(r,n){const a=i=>Math.trunc(i*Math.pow(10,-n.length+3));return uh(Wu(n.length,r),a)}set(r,n,a){return r.setMilliseconds(a),r}}class zFt extends Jl{constructor(){super(...arguments);_a(this,"priority",10);_a(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return o_(i_.basicOptionalMinutes,r);case"XX":return o_(i_.basic,r);case"XXXX":return o_(i_.basicOptionalSeconds,r);case"XXXXX":return o_(i_.extendedOptionalSeconds,r);case"XXX":default:return o_(i_.extended,r)}}set(r,n,a){return n.timestampIsSet?r:hc(r,r.getTime()-LS(r)-a)}}class BFt extends Jl{constructor(){super(...arguments);_a(this,"priority",10);_a(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return o_(i_.basicOptionalMinutes,r);case"xx":return o_(i_.basic,r);case"xxxx":return o_(i_.basicOptionalSeconds,r);case"xxxxx":return o_(i_.extendedOptionalSeconds,r);case"xxx":default:return o_(i_.extended,r)}}set(r,n,a){return n.timestampIsSet?r:hc(r,r.getTime()-LS(r)-a)}}class $Ft extends Jl{constructor(){super(...arguments);_a(this,"priority",40);_a(this,"incompatibleTokens","*")}parse(r){return gat(r)}set(r,n,a){return[hc(r,a*1e3),{timestampIsSet:!0}]}}class UFt extends Jl{constructor(){super(...arguments);_a(this,"priority",20);_a(this,"incompatibleTokens","*")}parse(r){return gat(r)}set(r,n,a){return[hc(r,a),{timestampIsSet:!0}]}}const qFt={G:new oFt,y:new lFt,Y:new cFt,R:new dFt,u:new uFt,Q:new hFt,q:new mFt,M:new fFt,L:new pFt,w:new gFt,I:new vFt,d:new wFt,D:new jFt,E:new NFt,e:new kFt,c:new SFt,i:new TFt,a:new EFt,b:new AFt,B:new MFt,h:new IFt,H:new PFt,K:new LFt,k:new DFt,m:new RFt,s:new OFt,S:new FFt,X:new zFt,x:new BFt,t:new $Ft,T:new UFt},VFt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,HFt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,GFt=/^'([^]*?)'?$/,WFt=/''/g,KFt=/\S/,YFt=/[a-zA-Z]/;function hTe(s,t,r,n){var _,b,j,N;const a=XOt(),i=a.locale??oge,l=a.firstWeekContainsDate??((b=(_=a.locale)==null?void 0:_.options)==null?void 0:b.firstWeekContainsDate)??1,o=a.weekStartsOn??((N=(j=a.locale)==null?void 0:j.options)==null?void 0:N.weekStartsOn)??0;if(t==="")return s===""?Wa(r):hc(r,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new iFt],u=t.match(HFt).map(C=>{const A=C[0];if(A in XNe){const E=XNe[A];return E(C,i.formatLong)}return C}).join("").match(VFt),m=[];for(let C of u){pat(C)&&QNe(C,t,s),fat(C)&&QNe(C,t,s);const A=C[0],E=qFt[A];if(E){const{incompatibleTokens:D}=E;if(Array.isArray(D)){const F=m.find(O=>D.includes(O.token)||O.token===A);if(F)throw new RangeError(`The format string mustn't contain \`${F.fullToken}\` and \`${C}\` at the same time`)}else if(E.incompatibleTokens==="*"&&m.length>0)throw new RangeError(`The format string mustn't contain \`${C}\` and any other token at the same time`);m.push({token:A,fullToken:C});const R=E.run(s,C,i.match,c);if(!R)return hc(r,NaN);d.push(R.setter),s=R.rest}else{if(A.match(YFt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");if(C==="''"?C="'":A==="'"&&(C=ZFt(C)),s.indexOf(C)===0)s=s.slice(C.length);else return hc(r,NaN)}}if(s.length>0&&KFt.test(s))return hc(r,NaN);const f=d.map(C=>C.priority).sort((C,A)=>A-C).filter((C,A,E)=>E.indexOf(C)===A).map(C=>d.filter(A=>A.priority===C).sort((A,E)=>E.subPriority-A.subPriority)).map(C=>C[0]);let x=Wa(r);if(isNaN(x.getTime()))return hc(r,NaN);const y={};for(const C of f){if(!C.validate(x,c))return hc(r,NaN);const A=C.set(x,y,c);Array.isArray(A)?(x=A[0],Object.assign(y,A[1])):x=A}return hc(r,x)}function ZFt(s){return s.match(GFt)[1].replace(WFt,"'")}function M_(s){return+Wa(s)i-l);return r>=n&&r<=a}function zue(s,t){return Dc(s,-t)}function yx(s,t){const n=r7t(s);let a;if(n.date){const c=n7t(n.date,2);a=a7t(c.restDateString,c.year)}if(!a||isNaN(a.getTime()))return new Date(NaN);const i=a.getTime();let l=0,o;if(n.time&&(l=i7t(n.time),isNaN(l)))return new Date(NaN);if(n.timezone){if(o=o7t(n.timezone),isNaN(o))return new Date(NaN)}else{const c=new Date(i+l),d=new Date(0);return d.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),d.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),d}return new Date(i+l+o)}const uq={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},e7t=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,t7t=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,s7t=/^([+-])(\d{2})(?::?(\d{2}))?$/;function r7t(s){const t={},r=s.split(uq.dateTimeDelimiter);let n;if(r.length>2)return t;if(/:/.test(r[0])?n=r[0]:(t.date=r[0],n=r[1],uq.timeZoneDelimiter.test(t.date)&&(t.date=s.split(uq.timeZoneDelimiter)[0],n=s.substr(t.date.length,s.length))),n){const a=uq.timezone.exec(n);a?(t.time=n.replace(a[1],""),t.timezone=a[1]):t.time=n}return t}function n7t(s,t){const r=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),n=s.match(r);if(!n)return{year:NaN,restDateString:""};const a=n[1]?parseInt(n[1]):null,i=n[2]?parseInt(n[2]):null;return{year:i===null?a:i*100,restDateString:s.slice((n[1]||n[2]).length)}}function a7t(s,t){if(t===null)return new Date(NaN);const r=s.match(e7t);if(!r)return new Date(NaN);const n=!!r[4],a=zR(r[1]),i=zR(r[2])-1,l=zR(r[3]),o=zR(r[4]),c=zR(r[5])-1;if(n)return h7t(t,o,c)?l7t(t,o,c):new Date(NaN);{const d=new Date(0);return!d7t(t,i,l)||!u7t(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function zR(s){return s?parseInt(s):1}function i7t(s){const t=s.match(t7t);if(!t)return NaN;const r=qbe(t[1]),n=qbe(t[2]),a=qbe(t[3]);return m7t(r,n,a)?r*vB+n*age+a*1e3:NaN}function qbe(s){return s&&parseFloat(s.replace(",","."))||0}function o7t(s){if(s==="Z")return 0;const t=s.match(s7t);if(!t)return 0;const r=t[1]==="+"?-1:1,n=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return f7t(n,a)?r*(n*vB+a*age):NaN}function l7t(s,t,r){const n=new Date(0);n.setUTCFullYear(s,0,4);const a=n.getUTCDay()||7,i=(t-1)*7+r+1-a;return n.setUTCDate(n.getUTCDate()+i),n}const c7t=[31,null,31,30,31,30,31,31,30,31,30,31];function bat(s){return s%400===0||s%4===0&&s%100!==0}function d7t(s,t,r){return t>=0&&t<=11&&r>=1&&r<=(c7t[t]||(bat(s)?29:28))}function u7t(s,t){return t>=1&&t<=(bat(s)?366:365)}function h7t(s,t,r){return t>=1&&t<=53&&r>=0&&r<=6}function m7t(s,t,r){return s===24?t===0&&r===0:r>=0&&r<60&&t>=0&&t<60&&s>=0&&s<25}function f7t(s,t){return t>=0&&t<=59}function Vbe(s,t){const r=Wa(s),n=r.getFullYear(),a=r.getDate(),i=hc(s,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);const l=ZOt(i);return r.setMonth(t,Math.min(a,l)),r}function u7(s,t){const r=Wa(s);return r.setHours(t),r}function h7(s,t){const r=Wa(s);return r.setMinutes(t),r}function e7e(s,t){const r=Wa(s);return isNaN(+r)?hc(s,NaN):(r.setFullYear(t),r)}function YT(s,t){return Ex(s,-t)}var t7e;function cn(s,t,r){function n(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 m=0;m{var c,d;return r!=null&&r.Parent&&o instanceof r.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 vP extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class _at extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(t7e=globalThis).__zod_globalConfig??(t7e.__zod_globalConfig={});const mTe=globalThis.__zod_globalConfig;function _A(s){return mTe}function wat(s){const t=Object.values(s).filter(n=>typeof n=="number");return Object.entries(s).filter(([n,a])=>t.indexOf(+n)===-1).map(([n,a])=>a)}function JNe(s,t){return typeof t=="bigint"?t.toString():t}function fTe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function pTe(s){return s==null}function xTe(s){const t=s.startsWith("^")?1:0,r=s.endsWith("$")?s.length-1:s.length;return s.slice(t,r)}function p7t(s,t){const r=s/t,n=Math.round(r),a=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n){};function cme(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const g7t=fTe(()=>{var s;if(mTe.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 E9(s){if(cme(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(cme(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Nat(s){return E9(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const y7t=new Set(["string","number","symbol"]);function uL(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s4(s,t,r){const n=new s._zod.constr(t??s._zod.def);return(!t||r!=null&&r.parent)&&(n._zod.parent=s),n}function Si(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 v7t(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const b7t={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 _7t(s,t){const r=s._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=t4(s._zod.def,{get shape(){const l={};for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(l[o]=r.shape[o])}return XA(this,"shape",l),l},checks:[]});return s4(s,i)}function w7t(s,t){const r=s._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=t4(s._zod.def,{get shape(){const l={...s._zod.def.shape};for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete l[o]}return XA(this,"shape",l),l},checks:[]});return s4(s,i)}function j7t(s,t){if(!E9(t))throw new Error("Invalid input to extend: expected a plain object");const r=s._zod.def.checks;if(r&&r.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=t4(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return XA(this,"shape",i),i}});return s4(s,a)}function N7t(s,t){if(!E9(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=t4(s._zod.def,{get shape(){const n={...s._zod.def.shape,...t};return XA(this,"shape",n),n}});return s4(s,r)}function k7t(s,t){var n;if((n=s._zod.def.checks)!=null&&n.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const r=t4(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return XA(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return s4(s,r)}function S7t(s,t,r){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=t4(t._zod.def,{get shape(){const o=t._zod.def.shape,c={...o};if(r)for(const d in r){if(!(d in o))throw new Error(`Unrecognized key: "${d}"`);r[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 XA(this,"shape",c),c},checks:[]});return s4(t,l)}function C7t(s,t,r){const n=t4(t._zod.def,{get shape(){const a=t._zod.def.shape,i={...a};if(r)for(const l in r){if(!(l in i))throw new Error(`Unrecognized key: "${l}"`);r[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 XA(this,"shape",i),i}});return s4(t,n)}function bI(s,t=0){var r;if(s.aborted===!0)return!0;for(let n=t;n{var n;return(n=r).path??(n.path=[]),r.path.unshift(s),r})}function hq(s){return typeof s=="string"?s:s==null?void 0:s.message}function wA(s,t,r){var c,d,u,m,f,x;const n=s.message?s.message:hq((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??hq((m=t==null?void 0:t.error)==null?void 0:m.call(t,s))??hq((f=r.customError)==null?void 0:f.call(r,s))??hq((x=r.localeError)==null?void 0:x.call(r,s))??"Invalid input",{inst:a,continue:i,input:l,...o}=s;return o.path??(o.path=[]),o.message=n,t!=null&&t.reportInput&&(o.input=l),o}function gTe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function A9(...s){const[t,r,n]=s;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Sat=(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,JNe,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},Cat=cn("$ZodError",Sat),Tat=cn("$ZodError",Sat,{Parent:Error});function E7t(s,t=r=>r.message){const r={},n=[];for(const a of s.issues)a.path.length>0?(r[a.path[0]]=r[a.path[0]]||[],r[a.path[0]].push(t(a))):n.push(t(a));return{formErrors:n,fieldErrors:r}}function A7t(s,t=r=>r.message){const r={_errors:[]},n=(a,i=[])=>{for(const l of a.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(o=>n({issues:o},[...i,...l.path]));else if(l.code==="invalid_key")n({issues:l.issues},[...i,...l.path]);else if(l.code==="invalid_element")n({issues:l.issues},[...i,...l.path]);else{const o=[...i,...l.path];if(o.length===0)r._errors.push(t(l));else{let c=r,d=0;for(;d(t,r,n,a)=>{const i=n?{...n,async:!1}:{async:!1},l=t._zod.run({value:r,issues:[]},i);if(l instanceof Promise)throw new vP;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>wA(c,i,_A())));throw jat(o,a==null?void 0:a.callee),o}return l.value},vTe=s=>async(t,r,n,a)=>{const i=n?{...n,async:!0}:{async:!0};let l=t._zod.run({value:r,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=>wA(c,i,_A())));throw jat(o,a==null?void 0:a.callee),o}return l.value},cge=s=>(t,r,n)=>{const a=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new vP;return i.issues.length?{success:!1,error:new(s??Cat)(i.issues.map(l=>wA(l,a,_A())))}:{success:!0,data:i.value}},M7t=cge(Tat),dge=s=>async(t,r,n)=>{const a=n?{...n,async:!0}:{async:!0};let i=t._zod.run({value:r,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new s(i.issues.map(l=>wA(l,a,_A())))}:{success:!0,data:i.value}},I7t=dge(Tat),P7t=s=>(t,r,n)=>{const a=n?{...n,direction:"backward"}:{direction:"backward"};return yTe(s)(t,r,a)},L7t=s=>(t,r,n)=>yTe(s)(t,r,n),D7t=s=>async(t,r,n)=>{const a=n?{...n,direction:"backward"}:{direction:"backward"};return vTe(s)(t,r,a)},R7t=s=>async(t,r,n)=>vTe(s)(t,r,n),O7t=s=>(t,r,n)=>{const a=n?{...n,direction:"backward"}:{direction:"backward"};return cge(s)(t,r,a)},F7t=s=>(t,r,n)=>cge(s)(t,r,n),z7t=s=>async(t,r,n)=>{const a=n?{...n,direction:"backward"}:{direction:"backward"};return dge(s)(t,r,a)},B7t=s=>async(t,r,n)=>dge(s)(t,r,n),$7t=/^[cC][0-9a-z]{6,}$/,U7t=/^[0-9a-z]+$/,q7t=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,V7t=/^[0-9a-vA-V]{20}$/,H7t=/^[A-Za-z0-9]{27}$/,G7t=/^[a-zA-Z0-9_-]{21}$/,W7t=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,K7t=/^([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})$/,n7e=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)$/,Y7t=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Z7t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function X7t(){return new RegExp(Z7t,"u")}const Q7t=/^(?:(?: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])$/,J7t=/^(([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}|:))$/,e9t=/^((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])$/,t9t=/^(([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])$/,s9t=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Eat=/^[A-Za-z0-9_-]*$/,r9t=/^https?$/,n9t=/^\+[1-9]\d{6,14}$/,Aat="(?:(?:\\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])))",a9t=new RegExp(`^${Aat}$`);function Mat(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 i9t(s){return new RegExp(`^${Mat(s)}$`)}function o9t(s){const t=Mat({precision:s.precision}),r=["Z"];s.local&&r.push(""),s.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Aat}T(?:${n})$`)}const l9t=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}$`)},c9t=/^-?\d+$/,d9t=/^-?\d+(?:\.\d+)?$/,u9t=/^(?:true|false)$/i,h9t=/^[^A-Z]*$/,m9t=/^[^a-z]*$/,Tg=cn("$ZodCheck",(s,t)=>{var r;s._zod??(s._zod={}),s._zod.def=t,(r=s._zod).onattach??(r.onattach=[])}),Iat={number:"number",bigint:"bigint",object:"date"},Pat=cn("$ZodCheckLessThan",(s,t)=>{Tg.init(s,t);const r=Iat[typeof t.value];s._zod.onattach.push(n=>{const a=n._zod.bag,i=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?n.value<=t.value:n.value{Tg.init(s,t);const r=Iat[typeof t.value];s._zod.onattach.push(n=>{const a=n._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=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:s,continue:!t.abort})}}),f9t=cn("$ZodCheckMultipleOf",(s,t)=>{Tg.init(s,t),s._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),s._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):p7t(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:s,continue:!t.abort})}}),p9t=cn("$ZodCheckNumberFormat",(s,t)=>{var l;Tg.init(s,t),t.format=t.format||"float64";const r=(l=t.format)==null?void 0:l.includes("int"),n=r?"int":"number",[a,i]=b7t[t.format];s._zod.onattach.push(o=>{const c=o._zod.bag;c.format=t.format,c.minimum=a,c.maximum=i,r&&(c.pattern=c9t)}),s._zod.check=o=>{const c=o.value;if(r){if(!Number.isInteger(c)){o.issues.push({expected:n,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:n,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:n,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})}}),x9t=cn("$ZodCheckMaxLength",(s,t)=>{var r;Tg.init(s,t),(r=s._zod.def).when??(r.when=n=>{const a=n.value;return!pTe(a)&&a.length!==void 0}),s._zod.onattach.push(n=>{const a=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const a=n.value;if(a.length<=t.maximum)return;const l=gTe(a);n.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),g9t=cn("$ZodCheckMinLength",(s,t)=>{var r;Tg.init(s,t),(r=s._zod.def).when??(r.when=n=>{const a=n.value;return!pTe(a)&&a.length!==void 0}),s._zod.onattach.push(n=>{const a=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(n._zod.bag.minimum=t.minimum)}),s._zod.check=n=>{const a=n.value;if(a.length>=t.minimum)return;const l=gTe(a);n.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),y9t=cn("$ZodCheckLengthEquals",(s,t)=>{var r;Tg.init(s,t),(r=s._zod.def).when??(r.when=n=>{const a=n.value;return!pTe(a)&&a.length!==void 0}),s._zod.onattach.push(n=>{const a=n._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),s._zod.check=n=>{const a=n.value,i=a.length;if(i===t.length)return;const l=gTe(a),o=i>t.length;n.issues.push({origin:l,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:s,continue:!t.abort})}}),uge=cn("$ZodCheckStringFormat",(s,t)=>{var r,n;Tg.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?(r=s._zod).check??(r.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})}):(n=s._zod).check??(n.check=()=>{})}),v9t=cn("$ZodCheckRegex",(s,t)=>{uge.init(s,t),s._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:s,continue:!t.abort})}}),b9t=cn("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=h9t),uge.init(s,t)}),_9t=cn("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=m9t),uge.init(s,t)}),w9t=cn("$ZodCheckIncludes",(s,t)=>{Tg.init(s,t);const r=uL(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,s._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),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})}}),j9t=cn("$ZodCheckStartsWith",(s,t)=>{Tg.init(s,t);const r=new RegExp(`^${uL(t.prefix)}.*`);t.pattern??(t.pattern=r),s._zod.onattach.push(n=>{const a=n._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),s._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:s,continue:!t.abort})}}),N9t=cn("$ZodCheckEndsWith",(s,t)=>{Tg.init(s,t);const r=new RegExp(`.*${uL(t.suffix)}$`);t.pattern??(t.pattern=r),s._zod.onattach.push(n=>{const a=n._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(r)}),s._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:s,continue:!t.abort})}}),k9t=cn("$ZodCheckOverwrite",(s,t)=>{Tg.init(s,t),s._zod.check=r=>{r.value=t.tx(r.value)}});class S9t{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 n=t.split(` `).filter(l=>l),a=Math.min(...n.map(l=>l.length-l.trimStart().length)),i=n.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,r=this==null?void 0:this.args,a=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new t(...r,a.join(` `))}}const C9t={major:4,minor:4,patch:3},Yu=cn("$ZodType",(s,t)=>{var a;var r;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=C9t;const n=[...s._zod.def.checks??[]];s._zod.traits.has("$ZodCheck")&&n.unshift(s);for(const i of n)for(const l of i._zod.onattach)l(s);if(n.length===0)(r=s._zod).deferred??(r.deferred=[]),(a=s._zod.deferred)==null||a.push(()=>{s._zod.run=s._zod.parse});else{const i=(o,c,d)=>{let u=bI(o),m;for(const f of c){if(f._zod.def.when){if(T7t(o)||!f._zod.def.when(o))continue}else if(u)continue;const x=o.issues.length,y=f._zod.check(o);if(y instanceof Promise&&(d==null?void 0:d.async)===!1)throw new vP;if(m||y instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await y,o.issues.length!==x&&(u||(u=bI(o,x)))});else{if(o.issues.length===x)continue;u||(u=bI(o,x))}}return m?m.then(()=>o):o},l=(o,c,d)=>{if(bI(o))return o.aborted=!0,o;const u=i(c,n,d);if(u instanceof Promise){if(d.async===!1)throw new vP;return u.then(m=>s._zod.parse(m,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(m=>l(m,o,c)):l(u,o,c)}const d=s._zod.parse(o,c);if(d instanceof Promise){if(c.async===!1)throw new vP;return d.then(u=>i(u,n,c))}return i(d,n,c)}}Tc(s,"~standard",()=>({validate:i=>{var l;try{const o=M7t(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return I7t(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}))}),bTe=cn("$ZodString",(s,t)=>{var r;Yu.init(s,t),s._zod.pattern=[...((r=s==null?void 0:s._zod.bag)==null?void 0:r.patterns)??[]].pop()??l9t(s._zod.bag),s._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:s}),n}}),Zd=cn("$ZodStringFormat",(s,t)=>{uge.init(s,t),bTe.init(s,t)}),T9t=cn("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=K7t),Zd.init(s,t)}),E9t=cn("$ZodUUID",(s,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=n7e(n))}else t.pattern??(t.pattern=n7e());Zd.init(s,t)}),A9t=cn("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=Y7t),Zd.init(s,t)}),M9t=cn("$ZodURL",(s,t)=>{Zd.init(s,t),s._zod.check=r=>{var n;try{const a=r.value.trim();if(!t.normalize&&((n=t.protocol)==null?void 0:n.source)===r9t.source&&!/^https?:\/\//i.test(a)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:s,continue:!t.abort});return}const i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.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)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:s,continue:!t.abort})),t.normalize?r.value=i.href:r.value=a;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:s,continue:!t.abort})}}}),I9t=cn("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=X7t()),Zd.init(s,t)}),P9t=cn("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=G7t),Zd.init(s,t)}),L9t=cn("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=$7t),Zd.init(s,t)}),D9t=cn("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=U7t),Zd.init(s,t)}),R9t=cn("$ZodULID",(s,t)=>{t.pattern??(t.pattern=q7t),Zd.init(s,t)}),O9t=cn("$ZodXID",(s,t)=>{t.pattern??(t.pattern=V7t),Zd.init(s,t)}),F9t=cn("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=H7t),Zd.init(s,t)}),z9t=cn("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=o9t(t)),Zd.init(s,t)}),B9t=cn("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=a9t),Zd.init(s,t)}),$9t=cn("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=i9t(t)),Zd.init(s,t)}),U9t=cn("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=W7t),Zd.init(s,t)}),q9t=cn("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=Q7t),Zd.init(s,t),s._zod.bag.format="ipv4"}),V9t=cn("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=J7t),Zd.init(s,t),s._zod.bag.format="ipv6",s._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:s,continue:!t.abort})}}}),H9t=cn("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=e9t),Zd.init(s,t)}),G9t=cn("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=t9t),Zd.init(s,t),s._zod.check=r=>{const n=r.value.split("/");try{if(n.length!==2)throw new Error;const[a,i]=n;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{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:s,continue:!t.abort})}}});function Dat(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const W9t=cn("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=s9t),Zd.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=r=>{Dat(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:s,continue:!t.abort})}});function K9t(s){if(!Eat.test(s))return!1;const t=s.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Dat(r)}const Y9t=cn("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=Eat),Zd.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=r=>{K9t(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:s,continue:!t.abort})}}),Z9t=cn("$ZodE164",(s,t)=>{t.pattern??(t.pattern=n9t),Zd.init(s,t)});function X9t(s,t=null){try{const r=s.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const a=JSON.parse(atob(n));return!("typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const Q9t=cn("$ZodJWT",(s,t)=>{Zd.init(s,t),s._zod.check=r=>{X9t(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:s,continue:!t.abort})}}),Rat=cn("$ZodNumber",(s,t)=>{Yu.init(s,t),s._zod.pattern=s._zod.bag.pattern??d9t,s._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const a=r.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return r;const i=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:a,inst:s,...i?{received:i}:{}}),r}}),J9t=cn("$ZodNumberFormat",(s,t)=>{p9t.init(s,t),Rat.init(s,t)}),ezt=cn("$ZodBoolean",(s,t)=>{Yu.init(s,t),s._zod.pattern=u9t,s._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const a=r.value;return typeof a=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:s}),r}}),tzt=cn("$ZodUnknown",(s,t)=>{Yu.init(s,t),s._zod.parse=r=>r}),szt=cn("$ZodNever",(s,t)=>{Yu.init(s,t),s._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:s}),r)});function a7e(s,t,r){s.issues.length&&t.issues.push(...kat(r,s.issues)),t.value[r]=s.value}const rzt=cn("$ZodArray",(s,t)=>{Yu.init(s,t),s._zod.parse=(r,n)=>{const a=r.value;if(!Array.isArray(a))return r.issues.push({expected:"array",code:"invalid_type",input:a,inst:s}),r;r.value=Array(a.length);const i=[];for(let l=0;la7e(d,r,l))):a7e(c,r,l)}return i.length?Promise.all(i).then(()=>r):r}});function dme(s,t,r,n,a,i){const l=r in n;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...kat(r,s.issues))}if(!l&&!a){s.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}s.value===void 0?l&&(t.value[r]=void 0):t.value[r]=s.value}function Oat(s){var n,a,i,l;const t=Object.keys(s.shape);for(const o of t)if(!((l=(i=(a=(n=s.shape)==null?void 0:n[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 r=v7t(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Fat(s,t,r,n,a,i){const l=[],o=a.keySet,c=a.catchall._zod,d=c.def.type,u=c.optin==="optional",m=c.optout==="optional";for(const f in t){if(f==="__proto__"||o.has(f))continue;if(d==="never"){l.push(f);continue}const x=c.run({value:t[f],issues:[]},n);x instanceof Promise?s.push(x.then(y=>dme(y,r,f,t,u,m))):dme(x,r,f,t,u,m)}return l.length&&r.issues.push({code:"unrecognized_keys",keys:l,input:t,inst:i}),s.length?Promise.all(s).then(()=>r):r}const nzt=cn("$ZodObject",(s,t)=>{Yu.init(s,t);const r=Object.getOwnPropertyDescriptor(t,"shape");if(!(r!=null&&r.get)){const o=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...o};return Object.defineProperty(t,"shape",{value:c}),c}})}const n=fTe(()=>Oat(t));Tc(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 m of u.values)c[d].add(m)}}return c});const a=cme,i=t.catchall;let l;s._zod.parse=(o,c)=>{l??(l=n.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=[],m=l.shape;for(const f of l.keys){const x=m[f],y=x._zod.optin==="optional",_=x._zod.optout==="optional",b=x._zod.run({value:d[f],issues:[]},c);b instanceof Promise?u.push(b.then(j=>dme(j,o,f,d,y,_))):dme(b,o,f,d,y,_)}return i?Fat(u,d,o,c,n.value,s):u.length?Promise.all(u).then(()=>o):o}}),azt=cn("$ZodObjectJIT",(s,t)=>{nzt.init(s,t);const r=s._zod.parse,n=fTe(()=>Oat(t)),a=f=>{var C,A;const x=new S9t(["shape","payload","ctx"]),y=n.value,_=E=>{const D=r7e(E);return`shape[${D}]._zod.run({ value: input[${D}], issues: [] }, ctx)`};x.write("const input = payload.value;");const b=Object.create(null);let j=0;for(const E of y.keys)b[E]=`key_${j++}`;x.write("const newResult = {};");for(const E of y.keys){const D=b[E],R=r7e(E),F=f[E],O=((C=F==null?void 0:F._zod)==null?void 0:C.optin)==="optional",B=((A=F==null?void 0:F._zod)==null?void 0:A.optout)==="optional";x.write(`const ${D} = ${_(E)};`),O&&B?x.write(` if (${D}.issues.length) { if (${R} in input) { payload.issues = payload.issues.concat(${D}.issues.map(iss => ({ ...iss, path: iss.path ? [${R}, ...iss.path] : [${R}] }))); } } if (${D}.value === undefined) { if (${R} in input) { newResult[${R}] = undefined; } } else { newResult[${R}] = ${D}.value; } `):O?x.write(` if (${D}.issues.length) { payload.issues = payload.issues.concat(${D}.issues.map(iss => ({ ...iss, path: iss.path ? [${R}, ...iss.path] : [${R}] }))); } if (${D}.value === undefined) { if (${R} in input) { newResult[${R}] = undefined; } } else { newResult[${R}] = ${D}.value; } `):x.write(` const ${D}_present = ${R} in input; if (${D}.issues.length) { payload.issues = payload.issues.concat(${D}.issues.map(iss => ({ ...iss, path: iss.path ? [${R}, ...iss.path] : [${R}] }))); } if (!${D}_present && !${D}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${R}] }); } if (${D}_present) { if (${D}.value === undefined) { newResult[${R}] = undefined; } else { newResult[${R}] = ${D}.value; } } `)}x.write("payload.value = newResult;"),x.write("return payload;");const N=x.compile();return(E,D)=>N(f,E,D)};let i;const l=cme,o=!mTe.jitless,d=o&&g7t.value,u=t.catchall;let m;s._zod.parse=(f,x)=>{m??(m=n.value);const y=f.value;return l(y)?o&&d&&(x==null?void 0:x.async)===!1&&x.jitless!==!0?(i||(i=a(t.shape)),f=i(f,x),u?Fat([],y,f,x,m,s):f):r(f,x):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:s}),f)}});function i7e(s,t,r,n){for(const i of s)if(i.issues.length===0)return t.value=i.value,t;const a=s.filter(i=>!bI(i));return a.length===1?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:s.map(i=>i.issues.map(l=>wA(l,n,_A())))}),t)}const izt=cn("$ZodUnion",(s,t)=>{Yu.init(s,t),Tc(s._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Tc(s._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Tc(s._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),Tc(s._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${n.map(a=>xTe(a.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;s._zod.parse=(n,a)=>{if(r)return r(n,a);let i=!1;const l=[];for(const o of t.options){const c=o._zod.run({value:n.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=>i7e(o,n,s,a)):i7e(l,n,s,a)}}),ozt=cn("$ZodIntersection",(s,t)=>{Yu.init(s,t),s._zod.parse=(r,n)=>{const a=r.value,i=t.left._zod.run({value:a,issues:[]},n),l=t.right._zod.run({value:a,issues:[]},n);return i instanceof Promise||l instanceof Promise?Promise.all([i,l]).then(([c,d])=>o7e(r,c,d)):o7e(r,i,l)}});function eke(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(E9(s)&&E9(t)){const r=Object.keys(t),n=Object.keys(s).filter(i=>r.indexOf(i)!==-1),a={...s,...t};for(const i of n){const l=eke(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 r=[];for(let n=0;no.l&&o.r).map(([o])=>o);if(i.length&&a&&s.issues.push({...a,keys:i}),bI(s))return s;const l=eke(t.value,r.value);if(!l.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`);return s.value=l.data,s}const lzt=cn("$ZodEnum",(s,t)=>{Yu.init(s,t);const r=wat(t.entries),n=new Set(r);s._zod.values=n,s._zod.pattern=new RegExp(`^(${r.filter(a=>y7t.has(typeof a)).map(a=>typeof a=="string"?uL(a):a.toString()).join("|")})$`),s._zod.parse=(a,i)=>{const l=a.value;return n.has(l)||a.issues.push({code:"invalid_value",values:r,input:l,inst:s}),a}}),czt=cn("$ZodLiteral",(s,t)=>{if(Yu.init(s,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);s._zod.values=r,s._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?uL(n):n?uL(n.toString()):String(n)).join("|")})$`),s._zod.parse=(n,a)=>{const i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:s}),n}}),dzt=cn("$ZodTransform",(s,t)=>{Yu.init(s,t),s._zod.optin="optional",s._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _at(s.constructor.name);const a=t.transform(r.value,r);if(n.async)return(a instanceof Promise?a:Promise.resolve(a)).then(l=>(r.value=l,r.fallback=!0,r));if(a instanceof Promise)throw new vP;return r.value=a,r.fallback=!0,r}});function l7e(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const zat=cn("$ZodOptional",(s,t)=>{Yu.init(s,t),s._zod.optin="optional",s._zod.optout="optional",Tc(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Tc(s._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${xTe(r.source)})?$`):void 0}),s._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const a=r.value,i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(l=>l7e(l,a)):l7e(i,a)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),uzt=cn("$ZodExactOptional",(s,t)=>{zat.init(s,t),Tc(s._zod,"values",()=>t.innerType._zod.values),Tc(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),hzt=cn("$ZodNullable",(s,t)=>{Yu.init(s,t),Tc(s._zod,"optin",()=>t.innerType._zod.optin),Tc(s._zod,"optout",()=>t.innerType._zod.optout),Tc(s._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${xTe(r.source)}|null)$`):void 0}),Tc(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),s._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),mzt=cn("$ZodDefault",(s,t)=>{Yu.init(s,t),s._zod.optin="optional",Tc(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(i=>c7e(i,t)):c7e(a,t)}});function c7e(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const fzt=cn("$ZodPrefault",(s,t)=>{Yu.init(s,t),s._zod.optin="optional",Tc(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),pzt=cn("$ZodNonOptional",(s,t)=>{Yu.init(s,t),Tc(s._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),s._zod.parse=(r,n)=>{const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(i=>d7e(i,s)):d7e(a,s)}});function d7e(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 xzt=cn("$ZodCatch",(s,t)=>{Yu.init(s,t),s._zod.optin="optional",Tc(s._zod,"optout",()=>t.innerType._zod.optout),Tc(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(l=>wA(l,n,_A()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=a.value,a.issues.length&&(r.value=t.catchValue({...r,error:{issues:a.issues.map(i=>wA(i,n,_A()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),gzt=cn("$ZodPipe",(s,t)=>{Yu.init(s,t),Tc(s._zod,"values",()=>t.in._zod.values),Tc(s._zod,"optin",()=>t.in._zod.optin),Tc(s._zod,"optout",()=>t.out._zod.optout),Tc(s._zod,"propValues",()=>t.in._zod.propValues),s._zod.parse=(r,n)=>{if(n.direction==="backward"){const i=t.out._zod.run(r,n);return i instanceof Promise?i.then(l=>mq(l,t.in,n)):mq(i,t.in,n)}const a=t.in._zod.run(r,n);return a instanceof Promise?a.then(i=>mq(i,t.out,n)):mq(a,t.out,n)}});function mq(s,t,r){return s.issues.length?(s.aborted=!0,s):t._zod.run({value:s.value,issues:s.issues,fallback:s.fallback},r)}const yzt=cn("$ZodReadonly",(s,t)=>{Yu.init(s,t),Tc(s._zod,"propValues",()=>t.innerType._zod.propValues),Tc(s._zod,"values",()=>t.innerType._zod.values),Tc(s._zod,"optin",()=>{var r,n;return(n=(r=t.innerType)==null?void 0:r._zod)==null?void 0:n.optin}),Tc(s._zod,"optout",()=>{var r,n;return(n=(r=t.innerType)==null?void 0:r._zod)==null?void 0:n.optout}),s._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const a=t.innerType._zod.run(r,n);return a instanceof Promise?a.then(u7e):u7e(a)}});function u7e(s){return s.value=Object.freeze(s.value),s}const vzt=cn("$ZodCustom",(s,t)=>{Tg.init(s,t),Yu.init(s,t),s._zod.parse=(r,n)=>r,s._zod.check=r=>{const n=r.value,a=t.fn(n);if(a instanceof Promise)return a.then(i=>h7e(i,r,n,s));h7e(a,r,n,s)}});function h7e(s,t,r,n){if(!s){const a={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(a.params=n._zod.def.params),t.issues.push(A9(a))}}var m7e;class bzt{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){const n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};delete n.id;const a={...n,...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 _zt(){return new bzt}(m7e=globalThis).__zod_globalRegistry??(m7e.__zod_globalRegistry=_zt());const MO=globalThis.__zod_globalRegistry;function wzt(s,t){return new s({type:"string",...Si(t)})}function jzt(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Si(t)})}function f7e(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Si(t)})}function Nzt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Si(t)})}function kzt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Si(t)})}function Szt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Si(t)})}function Czt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Si(t)})}function Tzt(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Si(t)})}function Ezt(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Si(t)})}function Azt(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Si(t)})}function Mzt(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Si(t)})}function Izt(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Si(t)})}function Pzt(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Si(t)})}function Lzt(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Si(t)})}function Dzt(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Si(t)})}function Rzt(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Si(t)})}function Ozt(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Si(t)})}function Fzt(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Si(t)})}function zzt(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Si(t)})}function Bzt(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Si(t)})}function $zt(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Si(t)})}function Uzt(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Si(t)})}function qzt(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Si(t)})}function Vzt(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Si(t)})}function Hzt(s,t){return new s({type:"string",format:"date",check:"string_format",...Si(t)})}function Gzt(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Si(t)})}function Wzt(s,t){return new s({type:"string",format:"duration",check:"string_format",...Si(t)})}function Kzt(s,t){return new s({type:"number",checks:[],...Si(t)})}function Yzt(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Si(t)})}function Zzt(s,t){return new s({type:"boolean",...Si(t)})}function Xzt(s){return new s({type:"unknown"})}function Qzt(s,t){return new s({type:"never",...Si(t)})}function p7e(s,t){return new Pat({check:"less_than",...Si(t),value:s,inclusive:!1})}function Hbe(s,t){return new Pat({check:"less_than",...Si(t),value:s,inclusive:!0})}function x7e(s,t){return new Lat({check:"greater_than",...Si(t),value:s,inclusive:!1})}function Gbe(s,t){return new Lat({check:"greater_than",...Si(t),value:s,inclusive:!0})}function g7e(s,t){return new f9t({check:"multiple_of",...Si(t),value:s})}function Bat(s,t){return new x9t({check:"max_length",...Si(t),maximum:s})}function ume(s,t){return new g9t({check:"min_length",...Si(t),minimum:s})}function $at(s,t){return new y9t({check:"length_equals",...Si(t),length:s})}function Jzt(s,t){return new v9t({check:"string_format",format:"regex",...Si(t),pattern:s})}function eBt(s){return new b9t({check:"string_format",format:"lowercase",...Si(s)})}function tBt(s){return new _9t({check:"string_format",format:"uppercase",...Si(s)})}function sBt(s,t){return new w9t({check:"string_format",format:"includes",...Si(t),includes:s})}function rBt(s,t){return new j9t({check:"string_format",format:"starts_with",...Si(t),prefix:s})}function nBt(s,t){return new N9t({check:"string_format",format:"ends_with",...Si(t),suffix:s})}function S8(s){return new k9t({check:"overwrite",tx:s})}function aBt(s){return S8(t=>t.normalize(s))}function iBt(){return S8(s=>s.trim())}function oBt(){return S8(s=>s.toLowerCase())}function lBt(){return S8(s=>s.toUpperCase())}function cBt(){return S8(s=>x7t(s))}function dBt(s,t,r){return new s({type:"array",element:t,...Si(r)})}function uBt(s,t,r){return new s({type:"custom",check:"custom",fn:t,...Si(r)})}function hBt(s,t){const r=mBt(n=>(n.addIssue=a=>{if(typeof a=="string")n.issues.push(A9(a,n.value,r._zod.def));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(A9(i))}},s(n.value,n)),t);return r}function mBt(s,t){const r=new Tg({check:"custom",...Si(t)});return r._zod.check=s,r}function Uat(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)??MO,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 ep(s,t,r={path:[],schemaPath:[]}){var u,m;var n;const a=s._zod.def,i=t.seen.get(s);if(i)return i.count++,r.schemaPath.includes(s)&&(i.cycle=r.path),i.schema;const l={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(s,l);const o=(m=(u=s._zod).toJSONSchema)==null?void 0:m.call(u);if(o)l.schema=o;else{const f={...r,schemaPath:[...r.schemaPath,s],path:r.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,f);else{const y=l.schema,_=t.processors[a.type];if(!_)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);_(s,t,y,f)}const x=s._zod.parent;x&&(l.ref||(l.ref=x),ep(x,t,f),t.seen.get(x).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(l.schema,c),t.io==="input"&&cx(s)&&(delete l.schema.examples,delete l.schema.default),t.io==="input"&&"_prefault"in l.schema&&((n=l.schema).default??(n.default=l.schema._prefault)),delete l.schema._prefault,t.seen.get(s).schema}function qat(s,t){var l,o,c,d;const r=s.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const u of s.seen.entries()){const m=(l=s.metadataRegistry.get(u[0]))==null?void 0:l.id;if(m){const f=n.get(m);if(f&&f!==u[0])throw new Error(`Duplicate schema id "${m}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(m,u[0])}}const a=u=>{var _;const m=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const b=(_=s.external.registry.get(u[0]))==null?void 0:_.id,j=s.external.uri??(C=>C);if(b)return{ref:j(b)};const N=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=N,{defId:N,ref:`${j("__shared")}#/${m}/${N}`}}if(u[1]===r)return{ref:"#"};const x=`#/${m}/`,y=u[1].schema.id??`__schema${s.counter++}`;return{defId:y,ref:x+y}},i=u=>{if(u[1].schema.$ref)return;const m=u[1],{ref:f,defId:x}=a(u);m.def={...m.schema},x&&(m.defId=x);const y=m.schema;for(const _ in y)delete y[_];y.$ref=f};if(s.cycles==="throw")for(const u of s.seen.entries()){const m=u[1];if(m.cycle)throw new Error(`Cycle detected: #/${(o=m.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 m=u[1];if(t===u[0]){i(u);continue}if(s.external){const x=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&x){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(m.cycle){i(u);continue}if(m.count>1&&s.reused==="ref"){i(u);continue}}}function Vat(s,t){var o,c,d,u;const r=s.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=m=>{const f=s.seen.get(m);if(f.ref===null)return;const x=f.def??f.schema,y={...x},_=f.ref;if(f.ref=null,_){n(_);const j=s.seen.get(_),N=j.schema;if(N.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(x.allOf=x.allOf??[],x.allOf.push(N)):Object.assign(x,N),Object.assign(x,y),m._zod.parent===_)for(const A in x)A==="$ref"||A==="allOf"||A in y||delete x[A];if(N.$ref&&j.def)for(const A in x)A==="$ref"||A==="allOf"||A in j.def&&JSON.stringify(x[A])===JSON.stringify(j.def[A])&&delete x[A]}const b=m._zod.parent;if(b&&b!==_){n(b);const j=s.seen.get(b);if(j!=null&&j.schema.$ref&&(x.$ref=j.schema.$ref,j.def))for(const N in x)N==="$ref"||N==="allOf"||N in j.def&&JSON.stringify(x[N])===JSON.stringify(j.def[N])&&delete x[N]}s.override({zodSchema:m,jsonSchema:x,path:f.path??[]})};for(const m of[...s.seen.entries()].reverse())n(m[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 m=(c=s.external.registry.get(t))==null?void 0:c.id;if(!m)throw new Error("Schema is missing an `id` property");a.$id=s.external.uri(m)}Object.assign(a,r.def??r.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 m of s.seen.entries()){const f=m[1];f.def&&f.defId&&(f.def.id===f.defId&&delete f.def.id,l[f.defId]=f.def)}s.external||Object.keys(l).length>0&&(s.target==="draft-2020-12"?a.$defs=l:a.definitions=l);try{const m=JSON.parse(JSON.stringify(a));return Object.defineProperty(m,"~standard",{value:{...t["~standard"],jsonSchema:{input:hme(t,"input",s.processors),output:hme(t,"output",s.processors)}},enumerable:!1,writable:!1}),m}catch{throw new Error("Error converting schema to JSON.")}}function cx(s,t){const r=t??{seen:new Set};if(r.seen.has(s))return!1;r.seen.add(s);const n=s._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return cx(n.element,r);if(n.type==="set")return cx(n.valueType,r);if(n.type==="lazy")return cx(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return cx(n.innerType,r);if(n.type==="intersection")return cx(n.left,r)||cx(n.right,r);if(n.type==="record"||n.type==="map")return cx(n.keyType,r)||cx(n.valueType,r);if(n.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:cx(n.in,r)||cx(n.out,r);if(n.type==="object"){for(const a in n.shape)if(cx(n.shape[a],r))return!0;return!1}if(n.type==="union"){for(const a of n.options)if(cx(a,r))return!0;return!1}if(n.type==="tuple"){for(const a of n.items)if(cx(a,r))return!0;return!!(n.rest&&cx(n.rest,r))}return!1}const fBt=(s,t={})=>r=>{const n=Uat({...r,processors:t});return ep(s,n),qat(n,s),Vat(n,s)},hme=(s,t,r={})=>n=>{const{libraryOptions:a,target:i}=n??{},l=Uat({...a??{},target:i,io:t,processors:r});return ep(s,l),qat(l,s),Vat(l,s)},pBt={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},xBt=(s,t,r,n)=>{const a=r;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=pBt[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(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},gBt=(s,t,r,n)=>{const a=r,{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 m=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof d=="number"&&d<=(l??Number.POSITIVE_INFINITY),x=t.target==="draft-04"||t.target==="openapi-3.0";m?x?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),f?x?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},yBt=(s,t,r,n)=>{r.type="boolean"},vBt=(s,t,r,n)=>{r.not={}},bBt=(s,t,r,n)=>{},_Bt=(s,t,r,n)=>{const a=s._zod.def,i=wat(a.entries);i.every(l=>typeof l=="number")&&(r.type="number"),i.every(l=>typeof l=="string")&&(r.type="string"),r.enum=i},wBt=(s,t,r,n)=>{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];r.type=l===null?"null":typeof l,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[l]:r.const=l}else i.every(l=>typeof l=="number")&&(r.type="number"),i.every(l=>typeof l=="string")&&(r.type="string"),i.every(l=>typeof l=="boolean")&&(r.type="boolean"),i.every(l=>l===null)&&(r.type="null"),r.enum=i},jBt=(s,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},NBt=(s,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},kBt=(s,t,r,n)=>{const a=r,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=ep(i.element,t,{...n,path:[...n.path,"items"]})},SBt=(s,t,r,n)=>{var d;const a=r,i=s._zod.def;a.type="object",a.properties={};const l=i.shape;for(const u in l)a.properties[u]=ep(l[u],t,{...n,path:[...n.path,"properties",u]});const o=new Set(Object.keys(l)),c=new Set([...o].filter(u=>{const m=i.shape[u]._zod;return t.io==="input"?m.optin===void 0:m.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=ep(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},CBt=(s,t,r,n)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>ep(o,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=l:r.anyOf=l},TBt=(s,t,r,n)=>{const a=s._zod.def,i=ep(a.left,t,{...n,path:[...n.path,"allOf",0]}),l=ep(a.right,t,{...n,path:[...n.path,"allOf",1]}),o=d=>"allOf"in d&&Object.keys(d).length===1,c=[...o(i)?i.allOf:[i],...o(l)?l.allOf:[l]];r.allOf=c},EBt=(s,t,r,n)=>{const a=s._zod.def,i=ep(a.innerType,t,n),l=t.seen.get(s);t.target==="openapi-3.0"?(l.ref=a.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},ABt=(s,t,r,n)=>{const a=s._zod.def;ep(a.innerType,t,n);const i=t.seen.get(s);i.ref=a.innerType},MBt=(s,t,r,n)=>{const a=s._zod.def;ep(a.innerType,t,n);const i=t.seen.get(s);i.ref=a.innerType,r.default=JSON.parse(JSON.stringify(a.defaultValue))},IBt=(s,t,r,n)=>{const a=s._zod.def;ep(a.innerType,t,n);const i=t.seen.get(s);i.ref=a.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},PBt=(s,t,r,n)=>{const a=s._zod.def;ep(a.innerType,t,n);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")}r.default=l},LBt=(s,t,r,n)=>{const a=s._zod.def,i=a.in._zod.traits.has("$ZodTransform"),l=t.io==="input"?i?a.out:a.in:a.out;ep(l,t,n);const o=t.seen.get(s);o.ref=l},DBt=(s,t,r,n)=>{const a=s._zod.def;ep(a.innerType,t,n);const i=t.seen.get(s);i.ref=a.innerType,r.readOnly=!0},Hat=(s,t,r,n)=>{const a=s._zod.def;ep(a.innerType,t,n);const i=t.seen.get(s);i.ref=a.innerType},RBt=cn("ZodISODateTime",(s,t)=>{z9t.init(s,t),_u.init(s,t)});function OBt(s){return Vzt(RBt,s)}const FBt=cn("ZodISODate",(s,t)=>{B9t.init(s,t),_u.init(s,t)});function zBt(s){return Hzt(FBt,s)}const BBt=cn("ZodISOTime",(s,t)=>{$9t.init(s,t),_u.init(s,t)});function $Bt(s){return Gzt(BBt,s)}const UBt=cn("ZodISODuration",(s,t)=>{U9t.init(s,t),_u.init(s,t)});function qBt(s){return Wzt(UBt,s)}const Gat=(s,t)=>{Cat.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:r=>A7t(s,r)},flatten:{value:r=>E7t(s,r)},addIssue:{value:r=>{s.issues.push(r),s.message=JSON.stringify(s.issues,JNe,2)}},addIssues:{value:r=>{s.issues.push(...r),s.message=JSON.stringify(s.issues,JNe,2)}},isEmpty:{get(){return s.issues.length===0}}})},VBt=cn("ZodError",Gat),hv=cn("ZodError",Gat,{Parent:Error}),HBt=yTe(hv),GBt=vTe(hv),WBt=cge(hv),KBt=dge(hv),YBt=P7t(hv),ZBt=L7t(hv),XBt=D7t(hv),QBt=R7t(hv),JBt=O7t(hv),e$t=F7t(hv),t$t=z7t(hv),s$t=B7t(hv),y7e=new WeakMap;function bB(s,t,r){const n=Object.getPrototypeOf(s);let a=y7e.get(n);if(a||(a=new Set,y7e.set(n,a)),!a.has(t)){a.add(t);for(const i in r){const l=r[i];Object.defineProperty(n,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 Zu=cn("ZodType",(s,t)=>(Yu.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:hme(s,"input"),output:hme(s,"output")}}),s.toJSONSchema=fBt(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(r,n)=>HBt(s,r,n,{callee:s.parse}),s.safeParse=(r,n)=>WBt(s,r,n),s.parseAsync=async(r,n)=>GBt(s,r,n,{callee:s.parseAsync}),s.safeParseAsync=async(r,n)=>KBt(s,r,n),s.spa=s.safeParseAsync,s.encode=(r,n)=>YBt(s,r,n),s.decode=(r,n)=>ZBt(s,r,n),s.encodeAsync=async(r,n)=>XBt(s,r,n),s.decodeAsync=async(r,n)=>QBt(s,r,n),s.safeEncode=(r,n)=>JBt(s,r,n),s.safeDecode=(r,n)=>e$t(s,r,n),s.safeEncodeAsync=async(r,n)=>t$t(s,r,n),s.safeDecodeAsync=async(r,n)=>s$t(s,r,n),bB(s,"ZodType",{check(...r){const n=this.def;return this.clone(t4(n,{checks:[...n.checks??[],...r.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return s4(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(X$t(r,n))},superRefine(r,n){return this.check(Q$t(r,n))},overwrite(r){return this.check(S8(r))},optional(){return w7e(this)},exactOptional(){return F$t(this)},nullable(){return j7e(this)},nullish(){return w7e(j7e(this))},nonoptional(r){return V$t(this,r)},array(){return T$t(this)},or(r){return M$t([this,r])},and(r){return P$t(this,r)},transform(r){return N7e(this,R$t(r))},default(r){return $$t(this,r)},prefault(r){return q$t(this,r)},catch(r){return G$t(this,r)},pipe(r){return N7e(this,r)},readonly(){return Y$t(this)},describe(r){const n=this.clone();return MO.add(n,{description:r}),n},meta(...r){if(r.length===0)return MO.get(this);const n=this.clone();return MO.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(s,"description",{get(){var r;return(r=MO.get(s))==null?void 0:r.description},configurable:!0}),s)),Wat=cn("_ZodString",(s,t)=>{bTe.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(n,a,i)=>xBt(s,n,a);const r=s._zod.bag;s.format=r.format??null,s.minLength=r.minimum??null,s.maxLength=r.maximum??null,bB(s,"_ZodString",{regex(...n){return this.check(Jzt(...n))},includes(...n){return this.check(sBt(...n))},startsWith(...n){return this.check(rBt(...n))},endsWith(...n){return this.check(nBt(...n))},min(...n){return this.check(ume(...n))},max(...n){return this.check(Bat(...n))},length(...n){return this.check($at(...n))},nonempty(...n){return this.check(ume(1,...n))},lowercase(n){return this.check(eBt(n))},uppercase(n){return this.check(tBt(n))},trim(){return this.check(iBt())},normalize(...n){return this.check(aBt(...n))},toLowerCase(){return this.check(oBt())},toUpperCase(){return this.check(lBt())},slugify(){return this.check(cBt())}})}),r$t=cn("ZodString",(s,t)=>{bTe.init(s,t),Wat.init(s,t),s.email=r=>s.check(jzt(n$t,r)),s.url=r=>s.check(Tzt(a$t,r)),s.jwt=r=>s.check(qzt(b$t,r)),s.emoji=r=>s.check(Ezt(i$t,r)),s.guid=r=>s.check(f7e(v7e,r)),s.uuid=r=>s.check(Nzt(fq,r)),s.uuidv4=r=>s.check(kzt(fq,r)),s.uuidv6=r=>s.check(Szt(fq,r)),s.uuidv7=r=>s.check(Czt(fq,r)),s.nanoid=r=>s.check(Azt(o$t,r)),s.guid=r=>s.check(f7e(v7e,r)),s.cuid=r=>s.check(Mzt(l$t,r)),s.cuid2=r=>s.check(Izt(c$t,r)),s.ulid=r=>s.check(Pzt(d$t,r)),s.base64=r=>s.check(Bzt(g$t,r)),s.base64url=r=>s.check($zt(y$t,r)),s.xid=r=>s.check(Lzt(u$t,r)),s.ksuid=r=>s.check(Dzt(h$t,r)),s.ipv4=r=>s.check(Rzt(m$t,r)),s.ipv6=r=>s.check(Ozt(f$t,r)),s.cidrv4=r=>s.check(Fzt(p$t,r)),s.cidrv6=r=>s.check(zzt(x$t,r)),s.e164=r=>s.check(Uzt(v$t,r)),s.datetime=r=>s.check(OBt(r)),s.date=r=>s.check(zBt(r)),s.time=r=>s.check($Bt(r)),s.duration=r=>s.check(qBt(r))});function ho(s){return wzt(r$t,s)}const _u=cn("ZodStringFormat",(s,t)=>{Zd.init(s,t),Wat.init(s,t)}),n$t=cn("ZodEmail",(s,t)=>{A9t.init(s,t),_u.init(s,t)}),v7e=cn("ZodGUID",(s,t)=>{T9t.init(s,t),_u.init(s,t)}),fq=cn("ZodUUID",(s,t)=>{E9t.init(s,t),_u.init(s,t)}),a$t=cn("ZodURL",(s,t)=>{M9t.init(s,t),_u.init(s,t)}),i$t=cn("ZodEmoji",(s,t)=>{I9t.init(s,t),_u.init(s,t)}),o$t=cn("ZodNanoID",(s,t)=>{P9t.init(s,t),_u.init(s,t)}),l$t=cn("ZodCUID",(s,t)=>{L9t.init(s,t),_u.init(s,t)}),c$t=cn("ZodCUID2",(s,t)=>{D9t.init(s,t),_u.init(s,t)}),d$t=cn("ZodULID",(s,t)=>{R9t.init(s,t),_u.init(s,t)}),u$t=cn("ZodXID",(s,t)=>{O9t.init(s,t),_u.init(s,t)}),h$t=cn("ZodKSUID",(s,t)=>{F9t.init(s,t),_u.init(s,t)}),m$t=cn("ZodIPv4",(s,t)=>{q9t.init(s,t),_u.init(s,t)}),f$t=cn("ZodIPv6",(s,t)=>{V9t.init(s,t),_u.init(s,t)}),p$t=cn("ZodCIDRv4",(s,t)=>{H9t.init(s,t),_u.init(s,t)}),x$t=cn("ZodCIDRv6",(s,t)=>{G9t.init(s,t),_u.init(s,t)}),g$t=cn("ZodBase64",(s,t)=>{W9t.init(s,t),_u.init(s,t)}),y$t=cn("ZodBase64URL",(s,t)=>{Y9t.init(s,t),_u.init(s,t)}),v$t=cn("ZodE164",(s,t)=>{Z9t.init(s,t),_u.init(s,t)}),b$t=cn("ZodJWT",(s,t)=>{Q9t.init(s,t),_u.init(s,t)}),Kat=cn("ZodNumber",(s,t)=>{Rat.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(n,a,i)=>gBt(s,n,a),bB(s,"ZodNumber",{gt(n,a){return this.check(x7e(n,a))},gte(n,a){return this.check(Gbe(n,a))},min(n,a){return this.check(Gbe(n,a))},lt(n,a){return this.check(p7e(n,a))},lte(n,a){return this.check(Hbe(n,a))},max(n,a){return this.check(Hbe(n,a))},int(n){return this.check(b7e(n))},safe(n){return this.check(b7e(n))},positive(n){return this.check(x7e(0,n))},nonnegative(n){return this.check(Gbe(0,n))},negative(n){return this.check(p7e(0,n))},nonpositive(n){return this.check(Hbe(0,n))},multipleOf(n,a){return this.check(g7e(n,a))},step(n,a){return this.check(g7e(n,a))},finite(){return this}});const r=s._zod.bag;s.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,s.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,s.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),s.isFinite=!0,s.format=r.format??null});function m7(s){return Kzt(Kat,s)}const _$t=cn("ZodNumberFormat",(s,t)=>{J9t.init(s,t),Kat.init(s,t)});function b7e(s){return Yzt(_$t,s)}const w$t=cn("ZodBoolean",(s,t)=>{ezt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>yBt(s,r,n)});function j$t(s){return Zzt(w$t,s)}const N$t=cn("ZodUnknown",(s,t)=>{tzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>bBt()});function _7e(){return Xzt(N$t)}const k$t=cn("ZodNever",(s,t)=>{szt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>vBt(s,r,n)});function S$t(s){return Qzt(k$t,s)}const C$t=cn("ZodArray",(s,t)=>{rzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>kBt(s,r,n,a),s.element=t.element,bB(s,"ZodArray",{min(r,n){return this.check(ume(r,n))},nonempty(r){return this.check(ume(1,r))},max(r,n){return this.check(Bat(r,n))},length(r,n){return this.check($at(r,n))},unwrap(){return this.element}})});function T$t(s,t){return dBt(C$t,s,t)}const E$t=cn("ZodObject",(s,t)=>{azt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>SBt(s,r,n,a),Tc(s,"shape",()=>t.shape),bB(s,"ZodObject",{keyof(){return _Te(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:_7e()})},loose(){return this.clone({...this._zod.def,catchall:_7e()})},strict(){return this.clone({...this._zod.def,catchall:S$t()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return j7t(this,r)},safeExtend(r){return N7t(this,r)},merge(r){return k7t(this,r)},pick(r){return _7t(this,r)},omit(r){return w7t(this,r)},partial(...r){return S7t(Yat,this,r[0])},required(...r){return C7t(Zat,this,r[0])}})});function tw(s,t){const r={type:"object",shape:s??{},...Si(t)};return new E$t(r)}const A$t=cn("ZodUnion",(s,t)=>{izt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>CBt(s,r,n,a),s.options=t.options});function M$t(s,t){return new A$t({type:"union",options:s,...Si(t)})}const I$t=cn("ZodIntersection",(s,t)=>{ozt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>TBt(s,r,n,a)});function P$t(s,t){return new I$t({type:"intersection",left:s,right:t})}const tke=cn("ZodEnum",(s,t)=>{lzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(n,a,i)=>_Bt(s,n,a),s.enum=t.entries,s.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));s.extract=(n,a)=>{const i={};for(const l of n)if(r.has(l))i[l]=t.entries[l];else throw new Error(`Key ${l} not found in enum`);return new tke({...t,checks:[],...Si(a),entries:i})},s.exclude=(n,a)=>{const i={...t.entries};for(const l of n)if(r.has(l))delete i[l];else throw new Error(`Key ${l} not found in enum`);return new tke({...t,checks:[],...Si(a),entries:i})}});function _Te(s,t){const r=Array.isArray(s)?Object.fromEntries(s.map(n=>[n,n])):s;return new tke({type:"enum",entries:r,...Si(t)})}const L$t=cn("ZodLiteral",(s,t)=>{czt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>wBt(s,r,n),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 tf(s,t){return new L$t({type:"literal",values:Array.isArray(s)?s:[s],...Si(t)})}const D$t=cn("ZodTransform",(s,t)=>{dzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>NBt(s,r),s._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _at(s.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(A9(i,r.value,t));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=r.value),l.inst??(l.inst=s),r.issues.push(A9(l))}};const a=t.transform(r.value,r);return a instanceof Promise?a.then(i=>(r.value=i,r.fallback=!0,r)):(r.value=a,r.fallback=!0,r)}});function R$t(s){return new D$t({type:"transform",transform:s})}const Yat=cn("ZodOptional",(s,t)=>{zat.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>Hat(s,r,n,a),s.unwrap=()=>s._zod.def.innerType});function w7e(s){return new Yat({type:"optional",innerType:s})}const O$t=cn("ZodExactOptional",(s,t)=>{uzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>Hat(s,r,n,a),s.unwrap=()=>s._zod.def.innerType});function F$t(s){return new O$t({type:"optional",innerType:s})}const z$t=cn("ZodNullable",(s,t)=>{hzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>EBt(s,r,n,a),s.unwrap=()=>s._zod.def.innerType});function j7e(s){return new z$t({type:"nullable",innerType:s})}const B$t=cn("ZodDefault",(s,t)=>{mzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>MBt(s,r,n,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function $$t(s,t){return new B$t({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():Nat(t)}})}const U$t=cn("ZodPrefault",(s,t)=>{fzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>IBt(s,r,n,a),s.unwrap=()=>s._zod.def.innerType});function q$t(s,t){return new U$t({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():Nat(t)}})}const Zat=cn("ZodNonOptional",(s,t)=>{pzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>ABt(s,r,n,a),s.unwrap=()=>s._zod.def.innerType});function V$t(s,t){return new Zat({type:"nonoptional",innerType:s,...Si(t)})}const H$t=cn("ZodCatch",(s,t)=>{xzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>PBt(s,r,n,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function G$t(s,t){return new H$t({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const W$t=cn("ZodPipe",(s,t)=>{gzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>LBt(s,r,n,a),s.in=t.in,s.out=t.out});function N7e(s,t){return new W$t({type:"pipe",in:s,out:t})}const K$t=cn("ZodReadonly",(s,t)=>{yzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>DBt(s,r,n,a),s.unwrap=()=>s._zod.def.innerType});function Y$t(s){return new K$t({type:"readonly",innerType:s})}const Z$t=cn("ZodCustom",(s,t)=>{vzt.init(s,t),Zu.init(s,t),s._zod.processJSONSchema=(r,n,a)=>jBt(s,r)});function X$t(s,t={}){return uBt(Z$t,s,t)}function Q$t(s,t){return hBt(s,t)}const J$t=["Excellent","Good","Neutral","Bad","Very Bad"],eUt=[5,4,3,2,1];function tUt({questions:s,visitorId:t,onComplete:r,onSkip:n}){const a=_Rt(),[i,l]=k.useState({}),o=s.filter(f=>f.question_type==="rating"),c=s.filter(f=>f.question_type!=="rating"),d=(f,x)=>{l(y=>({...y,[f]:{rating_value:x}}))},u=(f,x)=>{l(y=>({...y,[f]:{text_value:x}}))},m=async()=>{const f=Object.entries(i).filter(([,x])=>x.rating_value!=null||x.text_value&&x.text_value.trim()).map(([x,y])=>{var _;return{visitor_id:t,question_id:x,rating_value:y.rating_value??null,text_value:((_=y.text_value)==null?void 0:_.trim())||null}});if(f.length>0)try{await a.mutateAsync(f)}catch{}r()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),e.jsx("button",{onClick:n,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),e.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"flex-1"}),J$t.map(f=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:f})},f))]}),o.map(f=>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:f.question_text}),eUt.map(x=>{var y;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(f.id,x),className:`w-6 h-6 rounded-full border-2 transition-all ${((y=i[f.id])==null?void 0:y.rating_value)===x?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},x)})]},f.id))]}),c.map(f=>{var x;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:f.question_text}),e.jsx(pr,{value:((x=i[f.id])==null?void 0:x.text_value)||"",onChange:y=>u(f.id,y.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},f.id)}),e.jsx(q,{onClick:m,disabled:a.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:a.isPending?e.jsx(ls,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var hge="Checkbox",[sUt,Fnr]=bu(hge),[rUt,wTe]=sUt(hge);function nUt(s){const{__scopeCheckbox:t,checked:r,children:n,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:m}=s,[f,x]=df({prop:r,defaultProp:a??!1,onChange:c,caller:hge}),[y,_]=k.useState(null),[b,j]=k.useState(null),N=k.useRef(!1),C=y?!!l||!!y.closest("form"):!0,A={checked:f,disabled:i,setChecked:x,control:y,setControl:_,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:N,required:d,defaultChecked:yS(a)?!1:a,isFormControl:C,bubbleInput:b,setBubbleInput:j};return e.jsx(rUt,{scope:t,...A,children:aUt(m)?m(A):n})}var Xat="CheckboxTrigger",Qat=k.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:r,...n},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:u,setChecked:m,hasConsumerStoppedPropagationRef:f,isFormControl:x,bubbleInput:y}=wTe(Xat,s),_=_i(a,u),b=k.useRef(c);return k.useEffect(()=>{const j=i==null?void 0:i.form;if(j){const N=()=>m(b.current);return j.addEventListener("reset",N),()=>j.removeEventListener("reset",N)}},[i,m]),e.jsx(Yn.button,{type:"button",role:"checkbox","aria-checked":yS(c)?"mixed":c,"aria-required":d,"data-state":rit(c),"data-disabled":o?"":void 0,disabled:o,value:l,...n,ref:_,onKeyDown:dn(t,j=>{j.key==="Enter"&&j.preventDefault()}),onClick:dn(r,j=>{m(N=>yS(N)?!0:!N),y&&x&&(f.current=j.isPropagationStopped(),f.current||j.stopPropagation())})})});Qat.displayName=Xat;var jTe=k.forwardRef((s,t)=>{const{__scopeCheckbox:r,name:n,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:u,...m}=s;return e.jsx(nUt,{__scopeCheckbox:r,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:n,form:u,value:c,internal_do_not_use_render:({isFormControl:f})=>e.jsxs(e.Fragment,{children:[e.jsx(Qat,{...m,ref:t,__scopeCheckbox:r}),f&&e.jsx(sit,{__scopeCheckbox:r})]})})});jTe.displayName=hge;var Jat="CheckboxIndicator",eit=k.forwardRef((s,t)=>{const{__scopeCheckbox:r,forceMount:n,...a}=s,i=wTe(Jat,r);return e.jsx(yh,{present:n||yS(i.checked)||i.checked===!0,children:e.jsx(Yn.span,{"data-state":rit(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});eit.displayName=Jat;var tit="CheckboxBubbleInput",sit=k.forwardRef(({__scopeCheckbox:s,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:u,form:m,bubbleInput:f,setBubbleInput:x}=wTe(tit,s),y=_i(r,x),_=yB(i),b=rB(n);k.useEffect(()=>{const N=f;if(!N)return;const C=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(C,"checked").set,D=!a.current;if(_!==i&&E){const R=new Event("click",{bubbles:D});N.indeterminate=yS(i),E.call(N,yS(i)?!1:i),N.dispatchEvent(R)}},[f,_,i,a]);const j=k.useRef(yS(i)?!1:i);return e.jsx(Yn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??j.current,required:o,disabled:c,name:d,value:u,form:m,...t,tabIndex:-1,ref:y,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});sit.displayName=tit;function aUt(s){return typeof s=="function"}function yS(s){return s==="indeterminate"}function rit(s){return yS(s)?"indeterminate":s?"checked":"unchecked"}const Ri=k.forwardRef(({className:s,...t},r)=>e.jsx(jTe,{ref:r,className:zt("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(eit,{className:zt("flex items-center justify-center text-current"),children:e.jsx(la,{className:"h-4 w-4"})})}));Ri.displayName=jTe.displayName;const sw=Gxe,mge=K5e,iUt=Wxe,nit=k.forwardRef(({className:s,...t},r)=>e.jsx(w8,{className:zt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...t,ref:r}));nit.displayName=w8.displayName;const oUt=WA("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"}}),U1=k.forwardRef(({side:s="right",className:t,children:r,...n},a)=>e.jsxs(iUt,{children:[e.jsx(nit,{}),e.jsxs(j8,{ref:a,className:zt(oUt({side:s}),t),...n,children:[r,e.jsxs(xB,{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($r,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));U1.displayName=j8.displayName;const rw=({className:s,...t})=>e.jsx("div",{className:zt("flex flex-col space-y-2 text-center sm:text-left",s),...t});rw.displayName="SheetHeader";const ait=({className:s,...t})=>e.jsx("div",{className:zt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});ait.displayName="SheetFooter";const nw=k.forwardRef(({className:s,...t},r)=>e.jsx(fB,{ref:r,className:zt("text-lg font-semibold text-foreground",s),...t}));nw.displayName=fB.displayName;const fge=k.forwardRef(({className:s,...t},r)=>e.jsx(pB,{ref:r,className:zt("text-sm text-muted-foreground",s),...t}));fge.displayName=pB.displayName;function ske(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function lUt({rooms:s}){var m;const[t,r]=k.useState(((m=s[0])==null?void 0:m.id)||""),[n,a]=k.useState(null),i=s.find(f=>f.id===t)||s[0],l=n!==null?i==null?void 0:i.media[n]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(f=>f===null||o===0?f:(f-1+o)%o),u=()=>a(f=>f===null||o===0?f:(f+1)%o);return k.useEffect(()=>{if(n===null)return;const f=x=>{x.key==="Escape"?c():x.key==="ArrowLeft"?d():x.key==="ArrowRight"&&u()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(f=>e.jsxs("button",{onClick:()=>r(f.id),className:zt("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===f.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[f.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:f.media.length})]},f.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((f,x)=>e.jsx("button",{onClick:()=>a(x),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:f.kind==="video"?e.jsxs(e.Fragment,{children:[ske(f.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:f.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(bn,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:f.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},f.id))})]}),l&&i&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:c,children:[e.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[i.name," — ",(n??0)+1," / ",o]}),e.jsx("button",{onClick:f=>{f.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:f=>{f.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(jl,{className:"h-6 w-6"})}),l.kind==="video"?ske(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:f=>f.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:f=>f.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:f=>f.stopPropagation()}),o>1&&e.jsx("button",{onClick:f=>{f.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(Ia,{className:"h-6 w-6"})})]})]}):null}function cUt({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 r=k.useRef(null),[n,a]=k.useState(0);k.useEffect(()=>{const c=r.current;if(!c)return;let d=0;const u=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const m=Math.round(c.scrollLeft/c.clientWidth);a(m)})};return c.addEventListener("scroll",u,{passive:!0}),()=>{c.removeEventListener("scroll",u),cancelAnimationFrame(d)}},[]);const i=c=>{const d=r.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[n])==null?void 0:o.roomId;return e.jsxs("div",{className:"md:hidden -mx-5",children:[e.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(c=>{const d=t.findIndex(m=>m.roomId===c.id),u=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:zt("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:r,className:"flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar",style:{scrollSnapType:"x mandatory"},children:t.map((c,d)=>e.jsx("div",{className:"shrink-0 w-screen snap-center",children:e.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[c.type==="cover"?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center p-8 text-center bg-gradient-to-br from-slate-800 to-slate-950",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),e.jsx("h3",{className:"text-3xl font-bold",children:c.roomName}),c.description&&e.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:c.description}),e.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[c.mediaCount," ",c.mediaCount===1?"item":"items"," — swipe to view →"]})]}):c.kind==="video"?ske(c.url)?e.jsx("iframe",{src:c.url,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"}):e.jsx("video",{src:c.url,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):e.jsx("img",{src:c.url,alt:c.roomName,className:"w-full h-full object-cover"}),c.type==="media"&&e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-center justify-between pointer-events-none",children:[e.jsx("div",{className:"px-3 py-1 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-medium",children:c.roomName}),e.jsxs("div",{className:"px-2.5 py-1 rounded-full bg-black/50 backdrop-blur-sm text-[10px] text-white/80",children:[c.index+1," / ",c.total]})]})]})},d))}),e.jsxs("div",{className:"flex items-center justify-between px-5 mt-3",children:[e.jsxs("button",{onClick:()=>i(Math.max(0,n-1)),disabled:n===0,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:[e.jsx(jl,{className:"h-4 w-4"})," Prev"]}),e.jsxs("span",{className:"text-xs text-white/50",children:[n+1," / ",t.length]}),e.jsxs("button",{onClick:()=>i(Math.min(t.length-1,n+1)),disabled:n===t.length-1,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:["Next ",e.jsx(Ia,{className:"h-4 w-4"})]})]})]})}const Wbe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Ui},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:vn},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:En},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:Xl}},dUt=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function uUt(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 hUt({openHouse:s,visitorId:t,visitorName:r,visitorEmail:n,visitorPhone:a,previewMode:i=!1}){var $e;const l=s.profiles,o=(($e=l==null?void 0:l.name)==null?void 0:$e.split(" ").map(ve=>ve[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=k.useState(null),[m,f]=k.useState(""),[x,y]=k.useState(n||""),[_,b]=k.useState(a||""),[j,N]=k.useState(!1),[C,A]=k.useState(null),[E,D]=k.useState(""),[R,F]=k.useState(""),[O,B]=k.useState(""),[K,Z]=k.useState([]),[Q,W]=k.useState(""),[te,ne]=k.useState(""),[ae,ue]=k.useState(""),[me,de]=k.useState(""),fe=uUt(s.price),je=s.tour_mode==="rooms",{data:xe=[]}=MRt(je?s.id:void 0),Ee=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),Me=ve=>{u(ve),f(""),D(""),F(""),B(""),Z([]),W(""),ne(""),ue(""),de("")},Oe=()=>{u(null)},Ie=ve=>{Z(Qe=>Qe.includes(ve)?Qe.filter(we=>we!==ve):[...Qe,ve])},ze=ve=>ve==="showing"?{preferred_date:E||null,preferred_time:R||null,alternate_date:O||null}:ve==="disclosure"?{requested_documents:K}:ve==="offer"?{offer_amount:Q||null,financing:te||null,timeline:ae||null,pre_approved:me||null}:{},Ve=d?d==="showing"?!!E:d==="question"?m.trim().length>0:!0:!1,Le=async()=>{if(d){if(i){Dn({title:"Preview mode",description:"Lead not sent — this is just a preview."}),A(d),setTimeout(()=>{u(null),A(null)},1500);return}N(!0);try{const ve=ze(d),{error:Qe}=await U.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:m.trim()||null,email:x.trim()||null,phone:_.trim()||null,visitor_name:r,...ve}});if(Qe)throw Qe;U.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:m.trim()||null,visitor_name:r,visitor_email:x.trim()||null,visitor_phone:_.trim()||null,extras:ve}}).catch(()=>{}),A(d),Dn({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Oe(),A(null)},1400)}catch(ve){Dn({title:"Something went wrong",description:ve.message,variant:"destructive"})}finally{N(!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(Ma,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),fe&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:fe}),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(k0,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(of,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(C0,{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(Wn,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(Xa,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(Kn,{className:"bg-white/10 text-white",children:o})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-semibold text-white truncate",children:l.name}),l.title&&e.jsx("p",{className:"text-xs text-white/60 truncate",children:l.title})]}),(l.phone||l.email)&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l.phone&&e.jsx("a",{href:`tel:${l.phone}`,"aria-label":`Call ${l.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:c?{backgroundColor:`${c}33`,color:"white"}:void 0,children:e.jsx(Mn,{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(Ks,{className:"h-4 w-4"})})]})]}),je&&xe.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(lUt,{rooms:xe}),e.jsx(cUt,{rooms:xe})]}),Ee.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:Ee.map(ve=>{const Qe=Wbe[ve],we=Qe.icon;return e.jsxs("button",{onClick:()=>Me(ve),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(we,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Qe.label})]},ve)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(sw,{open:!!d,onOpenChange:ve=>!ve&&Oe(),children:e.jsx(U1,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(rw,{className:"text-left",children:[e.jsx(nw,{children:Wbe[d].title}),e.jsxs(fge,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),C===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(qn,{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(ce,{className:"text-xs",children:"Email"}),e.jsx(Ne,{type:"email",value:x,onChange:ve=>y(ve.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Phone"}),e.jsx(Ne,{type:"tel",value:_,onChange:ve=>b(ve.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(ce,{className:"text-xs",children:"Preferred date *"}),e.jsx(Ne,{type:"date",value:E,onChange:ve=>D(ve.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Preferred time"}),e.jsx(Ne,{type:"time",value:R,onChange:ve=>F(ve.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(Ne,{type:"date",value:O,onChange:ve=>B(ve.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:dUt.map(ve=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Ri,{checked:K.includes(ve),onCheckedChange:()=>Ie(ve)}),e.jsx("span",{children:ve})]},ve))})]}),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(ce,{className:"text-xs",children:"Estimated offer"}),e.jsx(Ne,{value:Q,onChange:ve=>W(ve.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Financing"}),e.jsxs(Ds,{value:te,onValueChange:ne,children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Fs,{placeholder:"Select..."})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"Cash",children:"Cash"}),e.jsx(lt,{value:"Conventional",children:"Conventional"}),e.jsx(lt,{value:"FHA",children:"FHA"}),e.jsx(lt,{value:"VA",children:"VA"}),e.jsx(lt,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Timeline"}),e.jsxs(Ds,{value:ae,onValueChange:ue,children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Fs,{placeholder:"Select..."})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"ASAP",children:"ASAP"}),e.jsx(lt,{value:"30 days",children:"30 days"}),e.jsx(lt,{value:"60 days",children:"60 days"}),e.jsx(lt,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(Ds,{value:me,onValueChange:de,children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Fs,{placeholder:"Select..."})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"Yes",children:"Yes"}),e.jsx(lt,{value:"No",children:"No"}),e.jsx(lt,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ce,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(pr,{value:m,onChange:ve=>f(ve.target.value),placeholder:Wbe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(q,{onClick:Le,disabled:j||!Ve,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:j?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const mUt=tw({first_name:ho().trim().min(1,"First name is required").max(50),last_name:ho().trim().max(50).optional(),email:ho().trim().email("Please enter a valid email").max(255).optional().or(tf("")),phone:ho().trim().max(20).optional().or(tf(""))}),fUt=[{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 iit({slug:s}={}){var Ge;const t=xo(),r=s||t.slug,[n]=ic(),a=n.get("kiosk")==="1"||n.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=yRt(r),d=CRt(),u=TRt(),m=ERt(),f=k.useRef(!1),[x,y]=k.useState("welcome"),[_,b]=k.useState(null),[j,N]=k.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[C,A]=k.useState(""),[E,D]=k.useState(!1),[R,F]=k.useState(!1),[O,B]=k.useState(""),[K,Z]=k.useState(""),[Q,W]=k.useState(i),te=k.useCallback(()=>{b(null),N({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),A(""),D(!1),F(!1),B(""),Z(""),W(i),y(a?"info":"welcome")},[a]);k.useEffect(()=>{if(!a||x!=="done")return;W(i);const We=setInterval(()=>{W(Ce=>Ce<=1?(clearInterval(We),te(),0):Ce-1)},1e3);return()=>clearInterval(We)},[a,x,te]),k.useEffect(()=>{if(!a)return;y(Ce=>Ce==="welcome"?"info":Ce);let We=null;return(async()=>{var Ce,qe;try{We=await((qe=(Ce=navigator.wakeLock)==null?void 0:Ce.request)==null?void 0:qe.call(Ce,"screen"))}catch{}})(),()=>{var Ce;try{(Ce=We==null?void 0:We.release)==null||Ce.call(We)}catch{}}},[a]);const ne=k.useCallback(()=>{var Ce;const We=document.documentElement;document.fullscreenElement||(Ce=We.requestFullscreen||We.webkitRequestFullscreen)==null||Ce.call(We).catch(()=>{})},[]),{data:ae,isLoading:ue}=bRt(l==null?void 0:l.id),me=!!(l!=null&&l.enable_survey),de=(l==null?void 0:l.ask_visitor_intent)!==!1,fe=(l==null?void 0:l.ask_visitor_address)===!0;k.useEffect(()=>{if(!r||!(l!=null&&l.id)||f.current)return;const We=`oh_scan_${l.id}`;if(sessionStorage.getItem(We)){f.current=!0;return}f.current=!0,sessionStorage.setItem(We,"1"),m.mutate(r)},[r,l==null?void 0:l.id]),k.useEffect(()=>{x==="pending_survey"&&(ue||y(me&&((ae==null?void 0:ae.length)??0)>0?"survey":"done"))},[x,ue,me,ae]);const je=We=>{if(!We)return"";const[Ce,qe]=We.split(":"),et=parseInt(Ce),Ze=et>=12?"PM":"AM";return`${et>12?et-12:et||12}:${qe} ${Ze}`},xe=async()=>{Z("");const We=mUt.safeParse(j);if(!We.success){Z(We.error.issues[0].message);return}if(!j.email&&!j.phone){Z("Please provide either an email or phone number");return}const Ce=(l==null?void 0:l.kind)==="virtual";if(!_&&(l!=null&&l.id))try{const qe=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:fe&&j.visitor_address.trim()?j.visitor_address.trim():void 0,wants_market_updates:E,has_agent:R,working_with_agent_name:R&&O.trim()?O.trim():void 0,partial_signin:Ce?!1:de});b(qe.id)}catch{if(Ce){Z("We could not start the virtual tour. Please try again.");return}}if(Ce){y(de?"intent":"done");return}if(!de){me?!ue&&ae&&ae.length>0?y("survey"):y("pending_survey"):y("done");return}y("intent")},Ee=async We=>{A(We);try{let Ce=_;if(Ce?await u.mutateAsync({visitor_id:Ce,visitor_intent:We,wants_market_updates:E,has_agent:R,working_with_agent_name:R&&O.trim()?O.trim():null,partial_signin:!1}):(Ce=(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:fe&&j.visitor_address.trim()?j.visitor_address.trim():void 0,visitor_intent:We,wants_market_updates:E,has_agent:R,working_with_agent_name:R&&O.trim()?O.trim():void 0,partial_signin:!1})).id,b(Ce)),(l==null?void 0:l.kind)==="virtual"){y("done");return}me?!ue&&ae&&ae.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(Pn,{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 Me=l.profiles,Oe=((Ge=Me==null?void 0:Me.name)==null?void 0:Ge.split(" ").map(We=>We[0]).join("").slice(0,2))||"?",Ie=l.event_type==="community",ze=l.kind==="virtual",Ve=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(ze&&(Ve||x==="done"))return!Ve&&!_?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(Yo,{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"})]}),Ve&&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(hUt,{openHouse:l,visitorId:Ve?"preview":_,visitorName:Ve?"Preview Visitor":`${j.first_name} ${j.last_name}`.trim(),visitorEmail:Ve?"":j.email,visitorPhone:Ve?"":j.phone,previewMode:Ve})]});const $e=`${ze?"Virtual Open House":Ie?"Community Event":"Open House"} — ${l.property_address}`,Qe=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?As(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,Me!=null&&Me.name?`Hosted by ${Me.name}`:null].filter(Boolean).join(" · "),we=l.photo_url||"",nt=we&&we.includes("/storage/v1/object/public/")?we.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":we||"https://dashboard.relevelup.com/og-image.png",Se=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:$e}),e.jsx("meta",{name:"description",content:Qe||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:$e}),e.jsx("meta",{property:"og:description",content:Qe||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:nt}),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:Se}),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:$e}),e.jsx("meta",{name:"twitter:description",content:Qe||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:nt}),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(Wn,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(Xa,{src:(Me==null?void 0:Me.avatar_url)||"",alt:(Me==null?void 0:Me.name)||""}),e.jsx(Kn,{className:"bg-white/10 text-white text-lg",children:Oe})]}),e.jsx("p",{className:"text-white/60 text-sm",children:Me==null?void 0:Me.name}),(Me==null?void 0:Me.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:Me.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(Ma,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!ze&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vn,{className:"h-3 w-3"}),As(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(jn,{className:"h-3 w-3"}),je(l.start_time),l.end_time?` – ${je(l.end_time)}`:""]})]})]})]})]}),!l.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:Ie?e.jsx(Ga,{className:"h-5 w-5 text-white"}):e.jsx(Pn,{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(Ma,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!ze&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vn,{className:"h-3 w-3"}),As(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(jn,{className:"h-3 w-3"}),je(l.start_time),l.end_time?` – ${je(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[x==="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(q,{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(ci,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),x==="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(Aa,{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(ce,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(Ne,{value:j.first_name,onChange:We=>N(Ce=>({...Ce,first_name:We.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(Ne,{value:j.last_name,onChange:We=>N(Ce=>({...Ce,last_name:We.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(Ne,{type:"email",value:j.email,onChange:We=>N(Ce=>({...Ce,email:We.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(Ne,{type:"tel",value:j.phone,onChange:We=>N(Ce=>({...Ce,phone:We.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),fe&&e.jsxs("div",{children:[e.jsx(ce,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(Ne,{value:j.visitor_address,onChange:We=>N(Ce=>({...Ce,visitor_address:We.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:We=>D(We.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:R?"Yes":"No"}),e.jsx(Rr,{checked:R,onCheckedChange:F})]})]}),R&&e.jsx(Ne,{value:O,onChange:We=>B(We.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),K&&e.jsx("p",{className:"text-destructive text-sm",children:K}),e.jsxs(q,{onClick:xe,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(ci,{className:"h-5 w-5 ml-2"})]})]}),x==="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(Aa,{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:fUt.map(We=>e.jsxs("button",{onClick:()=>Ee(We.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:We.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:We.label})]},We.value))}),K&&e.jsx("p",{className:"text-destructive text-sm text-center",children:K})]}),x==="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..."})]}),x==="survey"&&_&&ae&&e.jsx(tUt,{questions:ae,visitorId:_,onComplete:()=>y("done"),onSkip:()=>y("done")}),x==="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(qn,{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,". ",Ie?"Enjoy the event!":"Enjoy the open house!"]})]}),(l==null?void 0:l.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(l.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx(En,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(Me==null?void 0:Me.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:Me.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(q,{onClick:te,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 ",Q,"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(lP,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:ne,className:"inline-flex items-center gap-1 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10 hover:bg-white/20",title:"Enter full screen",children:e.jsx(LF,{className:"h-3 w-3"})})]})]})})]})}function znr(s){const{user:t}=Cs();return pt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:r,error:n}=await U.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return r},enabled:!!t&&!!s})}function Bnr(){const s=is(),{user:t}=Cs();return Mt({mutationFn:async({openHouseId:r,label:n})=>{const{data:a,error:i}=await U.from("open_house_cohost_tokens").insert({open_house_id:r,label:n||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function $nr(){const s=is();return Mt({mutationFn:async({id:t,openHouseId:r})=>{const{error:n}=await U.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function pUt(s){return pt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:r}=await U.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(r)throw r;if(t.expires_at&&new Date(t.expires_at)t[r][n]??r,s)}var NTe="ScrollArea",[oit,Unr]=bu(NTe),[gUt,mv]=oit(NTe),lit=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,type:n="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=k.useState(null),[d,u]=k.useState(null),[m,f]=k.useState(null),[x,y]=k.useState(null),[_,b]=k.useState(null),[j,N]=k.useState(0),[C,A]=k.useState(0),[E,D]=k.useState(!1),[R,F]=k.useState(!1),O=_i(t,K=>c(K)),B=ZS(a);return e.jsx(gUt,{scope:r,type:n,dir:B,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:m,onContentChange:f,scrollbarX:x,onScrollbarXChange:y,scrollbarXEnabled:E,onScrollbarXEnabledChange:D,scrollbarY:_,onScrollbarYChange:b,scrollbarYEnabled:R,onScrollbarYEnabledChange:F,onCornerWidthChange:N,onCornerHeightChange:A,children:e.jsx(Yn.div,{dir:B,...l,ref:O,style:{position:"relative","--radix-scroll-area-corner-width":j+"px","--radix-scroll-area-corner-height":C+"px",...s.style}})})});lit.displayName=NTe;var cit="ScrollAreaViewport",dit=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,children:n,nonce:a,...i}=s,l=mv(cit,r),o=k.useRef(null),c=_i(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(Yn.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:l.scrollbarXEnabled?"scroll":"hidden",overflowY:l.scrollbarYEnabled?"scroll":"hidden",...s.style},children:e.jsx("div",{ref:l.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});dit.displayName=cit;var aw="ScrollAreaScrollbar",kTe=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=mv(aw,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return k.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(yUt,{...n,ref:t,forceMount:r}):a.type==="scroll"?e.jsx(vUt,{...n,ref:t,forceMount:r}):a.type==="auto"?e.jsx(uit,{...n,ref:t,forceMount:r}):a.type==="always"?e.jsx(STe,{...n,ref:t}):null});kTe.displayName=aw;var yUt=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=mv(aw,s.__scopeScrollArea),[i,l]=k.useState(!1);return k.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},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(yh,{present:r||i,children:e.jsx(uit,{"data-state":i?"visible":"hidden",...n,ref:t})})}),vUt=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=mv(aw,s.__scopeScrollArea),i=s.orientation==="horizontal",l=xge(()=>c("SCROLL_END"),100),[o,c]=xUt("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return k.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),k.useEffect(()=>{const d=a.viewport,u=i?"scrollLeft":"scrollTop";if(d){let m=d[u];const f=()=>{const x=d[u];m!==x&&(c("SCROLL"),l()),m=x};return d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[a.viewport,i,c,l]),e.jsx(yh,{present:r||o!=="hidden",children:e.jsx(STe,{"data-state":o==="hidden"?"hidden":"visible",...n,ref:t,onPointerEnter:dn(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:dn(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),uit=k.forwardRef((s,t)=>{const r=mv(aw,s.__scopeScrollArea),{forceMount:n,...a}=s,[i,l]=k.useState(!1),o=s.orientation==="horizontal",c=xge(()=>{if(r.viewport){const d=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=s,a=mv(aw,s.__scopeScrollArea),i=k.useRef(null),l=k.useRef(0),[o,c]=k.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=xit(o.viewport,o.content),u={...n,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:f=>l.current=f};function m(f,x){return kUt(f,l.current,o,x)}return r==="horizontal"?e.jsx(bUt,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const f=a.viewport.scrollLeft,x=k7e(f,o,a.dir);i.current.style.transform=`translate3d(${x}px, 0, 0)`}},onWheelScroll:f=>{a.viewport&&(a.viewport.scrollLeft=f)},onDragScroll:f=>{a.viewport&&(a.viewport.scrollLeft=m(f,a.dir))}}):r==="vertical"?e.jsx(_Ut,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const f=a.viewport.scrollTop,x=k7e(f,o);i.current.style.transform=`translate3d(0, ${x}px, 0)`}},onWheelScroll:f=>{a.viewport&&(a.viewport.scrollTop=f)},onDragScroll:f=>{a.viewport&&(a.viewport.scrollTop=m(f))}}):null}),bUt=k.forwardRef((s,t)=>{const{sizes:r,onSizesChange:n,...a}=s,i=mv(aw,s.__scopeScrollArea),[l,o]=k.useState(),c=k.useRef(null),d=_i(t,c,i.onScrollbarXChange);return k.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(mit,{"data-orientation":"horizontal",...a,ref:d,sizes:r,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":pge(r)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.x),onDragScroll:u=>s.onDragScroll(u.x),onWheelScroll:(u,m)=>{if(i.viewport){const f=i.viewport.scrollLeft+u.deltaX;s.onWheelScroll(f),yit(f,m)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&n({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:fme(l.paddingLeft),paddingEnd:fme(l.paddingRight)}})}})}),_Ut=k.forwardRef((s,t)=>{const{sizes:r,onSizesChange:n,...a}=s,i=mv(aw,s.__scopeScrollArea),[l,o]=k.useState(),c=k.useRef(null),d=_i(t,c,i.onScrollbarYChange);return k.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(mit,{"data-orientation":"vertical",...a,ref:d,sizes:r,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":pge(r)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.y),onDragScroll:u=>s.onDragScroll(u.y),onWheelScroll:(u,m)=>{if(i.viewport){const f=i.viewport.scrollTop+u.deltaY;s.onWheelScroll(f),yit(f,m)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&n({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:fme(l.paddingTop),paddingEnd:fme(l.paddingBottom)}})}})}),[wUt,hit]=oit(aw),mit=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:u,onResize:m,...f}=s,x=mv(aw,r),[y,_]=k.useState(null),b=_i(t,O=>_(O)),j=k.useRef(null),N=k.useRef(""),C=x.viewport,A=n.content-n.viewport,E=$u(u),D=$u(c),R=xge(m,10);function F(O){if(j.current){const B=O.clientX-j.current.left,K=O.clientY-j.current.top;d({x:B,y:K})}}return k.useEffect(()=>{const O=B=>{const K=B.target;(y==null?void 0:y.contains(K))&&E(B,A)};return document.addEventListener("wheel",O,{passive:!1}),()=>document.removeEventListener("wheel",O,{passive:!1})},[C,y,A,E]),k.useEffect(D,[n,D]),hL(y,R),hL(x.content,R),e.jsx(wUt,{scope:r,scrollbar:y,hasThumb:a,onThumbChange:$u(i),onThumbPointerUp:$u(l),onThumbPositionChange:D,onThumbPointerDown:$u(o),children:e.jsx(Yn.div,{...f,ref:b,style:{position:"absolute",...f.style},onPointerDown:dn(s.onPointerDown,O=>{O.button===0&&(O.target.setPointerCapture(O.pointerId),j.current=y.getBoundingClientRect(),N.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",x.viewport&&(x.viewport.style.scrollBehavior="auto"),F(O))}),onPointerMove:dn(s.onPointerMove,F),onPointerUp:dn(s.onPointerUp,O=>{const B=O.target;B.hasPointerCapture(O.pointerId)&&B.releasePointerCapture(O.pointerId),document.body.style.webkitUserSelect=N.current,x.viewport&&(x.viewport.style.scrollBehavior=""),j.current=null})})})}),mme="ScrollAreaThumb",fit=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=hit(mme,s.__scopeScrollArea);return e.jsx(yh,{present:r||a.hasThumb,children:e.jsx(jUt,{ref:t,...n})})}),jUt=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,style:n,...a}=s,i=mv(mme,r),l=hit(mme,r),{onThumbPositionChange:o}=l,c=_i(t,m=>l.onThumbChange(m)),d=k.useRef(void 0),u=xge(()=>{d.current&&(d.current(),d.current=void 0)},100);return k.useEffect(()=>{const m=i.viewport;if(m){const f=()=>{if(u(),!d.current){const x=SUt(m,o);d.current=x,o()}};return o(),m.addEventListener("scroll",f),()=>m.removeEventListener("scroll",f)}},[i.viewport,u,o]),e.jsx(Yn.div,{"data-state":l.hasThumb?"visible":"hidden",...a,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:dn(s.onPointerDownCapture,m=>{const x=m.target.getBoundingClientRect(),y=m.clientX-x.left,_=m.clientY-x.top;l.onThumbPointerDown({x:y,y:_})}),onPointerUp:dn(s.onPointerUp,l.onThumbPointerUp)})});fit.displayName=mme;var CTe="ScrollAreaCorner",pit=k.forwardRef((s,t)=>{const r=mv(CTe,s.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?e.jsx(NUt,{...s,ref:t}):null});pit.displayName=CTe;var NUt=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,...n}=s,a=mv(CTe,r),[i,l]=k.useState(0),[o,c]=k.useState(0),d=!!(i&&o);return hL(a.scrollbarX,()=>{var m;const u=((m=a.scrollbarX)==null?void 0:m.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),hL(a.scrollbarY,()=>{var m;const u=((m=a.scrollbarY)==null?void 0:m.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(Yn.div,{...n,ref:t,style:{width:i,height:o,position:"absolute",right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:0,...s.style}}):null});function fme(s){return s?parseInt(s,10):0}function xit(s,t){const r=s/t;return isNaN(r)?0:r}function pge(s){const t=xit(s.viewport,s.content),r=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,n=(s.scrollbar.size-r)*t;return Math.max(n,18)}function kUt(s,t,r,n="ltr"){const a=pge(r),i=a/2,l=t||i,o=a-l,c=r.scrollbar.paddingStart+l,d=r.scrollbar.size-r.scrollbar.paddingEnd-o,u=r.content-r.viewport,m=n==="ltr"?[0,u]:[u*-1,0];return git([c,d],m)(s)}function k7e(s,t,r="ltr"){const n=pge(t),a=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-a,l=t.content-t.viewport,o=i-n,c=r==="ltr"?[0,l]:[l*-1,0],d=T9(s,c);return git([0,l],[0,o])(d)}function git(s,t){return r=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const n=(t[1]-t[0])/(s[1]-s[0]);return t[0]+n*(r-s[0])}}function yit(s,t){return s>0&&s{})=>{let r={left:s.scrollLeft,top:s.scrollTop},n=0;return function a(){const i={left:s.scrollLeft,top:s.scrollTop},l=r.left!==i.left,o=r.top!==i.top;(l||o)&&t(),r=i,n=window.requestAnimationFrame(a)}(),()=>window.cancelAnimationFrame(n)};function xge(s,t){const r=$u(s),n=k.useRef(0);return k.useEffect(()=>()=>window.clearTimeout(n.current),[]),k.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,t)},[r,t])}function hL(s,t){const r=$u(t);Gu(()=>{let n=0;if(s){const a=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(r)});return a.observe(s),()=>{window.cancelAnimationFrame(n),a.unobserve(s)}}},[s,r])}var vit=lit,CUt=dit,TUt=pit;const ui=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(vit,{ref:n,className:zt("relative overflow-hidden",s),...r,children:[e.jsx(CUt,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(gge,{}),e.jsx(TUt,{})]}));ui.displayName=vit.displayName;const gge=k.forwardRef(({className:s,orientation:t="vertical",...r},n)=>e.jsx(kTe,{ref:n,orientation:t,className:zt("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...r,children:e.jsx(fit,{className:"relative flex-1 rounded-full bg-border"})}));gge.displayName=kTe.displayName;const TTe=k.createContext({});function ETe(s){const t=k.useRef(null);return t.current===null&&(t.current=s()),t.current}const EUt=typeof window<"u",bit=EUt?k.useLayoutEffect:k.useEffect,yge=k.createContext(null);function ATe(s,t){s.indexOf(t)===-1&&s.push(t)}function pme(s,t){const r=s.indexOf(t);r>-1&&s.splice(r,1)}const $_=(s,t,r)=>r>t?t:r{},mL=()=>{};const DS={},_it=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function wit(s){return typeof s=="object"&&s!==null}const jit=s=>/^0[^.\s]+$/u.test(s);function Nit(s){let t;return()=>(t===void 0&&(t=s()),t)}const sv=s=>s,AUt=(s,t)=>r=>t(s(r)),_B=(...s)=>s.reduce(AUt),M9=(s,t,r)=>{const n=t-s;return n===0?1:(r-s)/n};class MTe{constructor(){this.subscriptions=[]}add(t){return ATe(this.subscriptions,t),()=>pme(this.subscriptions,t)}notify(t,r,n){const a=this.subscriptions.length;if(a)if(a===1)this.subscriptions[0](t,r,n);else for(let i=0;is*1e3,Gy=s=>s/1e3;function kit(s,t){return t?s*(1e3/t):0}const Sit=(s,t,r)=>(((1-3*r+3*t)*s+(3*r-6*t))*s+3*t)*s,MUt=1e-7,IUt=12;function PUt(s,t,r,n,a){let i,l,o=0;do l=t+(r-t)/2,i=Sit(l,n,a)-s,i>0?r=l:t=l;while(Math.abs(i)>MUt&&++oPUt(i,0,1,s,r);return i=>i===0||i===1?i:Sit(a(i),t,n)}const Cit=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,Tit=s=>t=>1-s(1-t),Eit=wB(.33,1.53,.69,.99),ITe=Tit(Eit),Ait=Cit(ITe),Mit=s=>s>=1?1:(s*=2)<1?.5*ITe(s):.5*(2-Math.pow(2,-10*(s-1))),PTe=s=>1-Math.sin(Math.acos(s)),Iit=Tit(PTe),Pit=Cit(PTe),LUt=wB(.42,0,1,1),DUt=wB(0,0,.58,1),Lit=wB(.42,0,.58,1),RUt=s=>Array.isArray(s)&&typeof s[0]!="number",Dit=s=>Array.isArray(s)&&typeof s[0]=="number",S7e={linear:sv,easeIn:LUt,easeInOut:Lit,easeOut:DUt,circIn:PTe,circInOut:Pit,circOut:Iit,backIn:ITe,backInOut:Ait,backOut:Eit,anticipate:Mit},OUt=s=>typeof s=="string",C7e=s=>{if(Dit(s)){mL(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,r,n,a]=s;return wB(t,r,n,a)}else if(OUt(s))return mL(S7e[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),S7e[s];return s},pq=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],T7e={value:null,addProjectionMetrics:null};function FUt(s,t){let r=new Set,n=new Set,a=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1},c=0;function d(m){l.has(m)&&(u.schedule(m),s()),c++,m(o)}const u={schedule:(m,f=!1,x=!1)=>{const _=x&&a?r:n;return f&&l.add(m),_.add(m),m},cancel:m=>{n.delete(m),l.delete(m)},process:m=>{if(o=m,a){i=!0;return}a=!0;const f=r;r=n,n=f,r.forEach(d),t&&T7e.value&&T7e.value.frameloop[t].push(c),c=0,r.clear(),a=!1,i&&(i=!1,u.process(m))}};return u}const zUt=40;function Rit(s,t){let r=!1,n=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>r=!0,l=pq.reduce((C,A)=>(C[A]=FUt(i,t?A:void 0),C),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:m,preRender:f,render:x,postRender:y}=l,_=()=>{const C=DS.useManualTiming,A=C?a.timestamp:performance.now();r=!1,C||(a.delta=n?1e3/60:Math.max(Math.min(A-a.timestamp,zUt),1)),a.timestamp=A,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),m.process(a),f.process(a),x.process(a),y.process(a),a.isProcessing=!1,r&&t&&(n=!1,s(_))},b=()=>{r=!0,n=!0,a.isProcessing||s(_)};return{schedule:pq.reduce((C,A)=>{const E=l[A];return C[A]=(D,R=!1,F=!1)=>(r||b(),E.schedule(D,R,F)),C},{}),cancel:C=>{for(let A=0;A(Bue===void 0&&bx.set(Df.isProcessing||DS.useManualTiming?Df.timestamp:performance.now()),Bue),set:s=>{Bue=s,queueMicrotask(BUt)}},Oit=s=>t=>typeof t=="string"&&t.startsWith(s),Fit=Oit("--"),$Ut=Oit("var(--"),LTe=s=>$Ut(s)?UUt.test(s.split("/*")[0].trim()):!1,UUt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function E7e(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const C8={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},I9={...C8,transform:s=>$_(0,1,s)},xq={...C8,default:1},f7=s=>Math.round(s*1e5)/1e5,DTe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function qUt(s){return s==null}const VUt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,RTe=(s,t)=>r=>!!(typeof r=="string"&&VUt.test(r)&&r.startsWith(s)||t&&!qUt(r)&&Object.prototype.hasOwnProperty.call(r,t)),zit=(s,t,r)=>n=>{if(typeof n!="string")return n;const[a,i,l,o]=n.match(DTe);return{[s]:parseFloat(a),[t]:parseFloat(i),[r]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},HUt=s=>$_(0,255,s),Ybe={...C8,transform:s=>Math.round(HUt(s))},ZT={test:RTe("rgb","red"),parse:zit("red","green","blue"),transform:({red:s,green:t,blue:r,alpha:n=1})=>"rgba("+Ybe.transform(s)+", "+Ybe.transform(t)+", "+Ybe.transform(r)+", "+f7(I9.transform(n))+")"};function GUt(s){let t="",r="",n="",a="";return s.length>5?(t=s.substring(1,3),r=s.substring(3,5),n=s.substring(5,7),a=s.substring(7,9)):(t=s.substring(1,2),r=s.substring(2,3),n=s.substring(3,4),a=s.substring(4,5),t+=t,r+=r,n+=n,a+=a),{red:parseInt(t,16),green:parseInt(r,16),blue:parseInt(n,16),alpha:a?parseInt(a,16)/255:1}}const rke={test:RTe("#"),parse:GUt,transform:ZT.transform},jB=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),YN=jB("deg"),I_=jB("%"),ai=jB("px"),WUt=jB("vh"),KUt=jB("vw"),A7e={...I_,parse:s=>I_.parse(s)/100,transform:s=>I_.transform(s*100)},_I={test:RTe("hsl","hue"),parse:zit("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:r,alpha:n=1})=>"hsla("+Math.round(s)+", "+I_.transform(f7(t))+", "+I_.transform(f7(r))+", "+f7(I9.transform(n))+")"},Ah={test:s=>ZT.test(s)||rke.test(s)||_I.test(s),parse:s=>ZT.test(s)?ZT.parse(s):_I.test(s)?_I.parse(s):rke.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?ZT.transform(s):_I.transform(s),getAnimatableNone:s=>{const t=Ah.parse(s);return t.alpha=0,Ah.transform(t)}},YUt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ZUt(s){var t,r;return isNaN(s)&&typeof s=="string"&&(((t=s.match(DTe))==null?void 0:t.length)||0)+(((r=s.match(YUt))==null?void 0:r.length)||0)>0}const Bit="number",$it="color",XUt="var",QUt="var(",M7e="${}",JUt=/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 fL(s){const t=s.toString(),r=[],n={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(JUt,c=>(Ah.test(c)?(n.color.push(i),a.push($it),r.push(Ah.parse(c))):c.startsWith(QUt)?(n.var.push(i),a.push(XUt),r.push(c)):(n.number.push(i),a.push(Bit),r.push(parseFloat(c))),++i,M7e)).split(M7e);return{values:r,split:o,indexes:n,types:a}}function eqt(s){return fL(s).values}function Uit({split:s,types:t}){const r=s.length;return n=>{let a="";for(let i=0;itypeof s=="number"?0:Ah.test(s)?Ah.getAnimatableNone(s):s,rqt=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:sqt(s);function nqt(s){const t=fL(s);return Uit(t)(t.values.map((n,a)=>rqt(n,t.split[a])))}const I1={test:ZUt,parse:eqt,createTransformer:tqt,getAnimatableNone:nqt};function Zbe(s,t,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?s+(t-s)*6*r:r<1/2?t:r<2/3?s+(t-s)*(2/3-r)*6:s}function aqt({hue:s,saturation:t,lightness:r,alpha:n}){s/=360,t/=100,r/=100;let a=0,i=0,l=0;if(!t)a=i=l=r;else{const o=r<.5?r*(1+t):r+t-r*t,c=2*r-o;a=Zbe(c,o,s+1/3),i=Zbe(c,o,s),l=Zbe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:n}}function xme(s,t){return r=>r>0?t:s}const Nd=(s,t,r)=>s+(t-s)*r,Xbe=(s,t,r)=>{const n=s*s,a=r*(t*t-n)+n;return a<0?0:Math.sqrt(a)},iqt=[rke,ZT,_I],oqt=s=>iqt.find(t=>t.test(s));function I7e(s){const t=oqt(s);if(vge(!!t,`'${s}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let r=t.parse(s);return t===_I&&(r=aqt(r)),r}const P7e=(s,t)=>{const r=I7e(s),n=I7e(t);if(!r||!n)return xme(s,t);const a={...r};return i=>(a.red=Xbe(r.red,n.red,i),a.green=Xbe(r.green,n.green,i),a.blue=Xbe(r.blue,n.blue,i),a.alpha=Nd(r.alpha,n.alpha,i),ZT.transform(a))},nke=new Set(["none","hidden"]);function lqt(s,t){return nke.has(s)?r=>r<=0?s:t:r=>r>=1?t:s}function cqt(s,t){return r=>Nd(s,t,r)}function OTe(s){return typeof s=="number"?cqt:typeof s=="string"?LTe(s)?xme:Ah.test(s)?P7e:hqt:Array.isArray(s)?qit:typeof s=="object"?Ah.test(s)?P7e:dqt:xme}function qit(s,t){const r=[...s],n=r.length,a=s.map((i,l)=>OTe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in n)r[i]=n[i](a);return r}}function uqt(s,t){const r=[],n={color:0,var:0,number:0};for(let a=0;a{const r=I1.createTransformer(t),n=fL(s),a=fL(t);return n.indexes.var.length===a.indexes.var.length&&n.indexes.color.length===a.indexes.color.length&&n.indexes.number.length>=a.indexes.number.length?nke.has(s)&&!a.values.length||nke.has(t)&&!n.values.length?lqt(s,t):_B(qit(uqt(n,a),a.values),r):(vge(!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"),xme(s,t))};function Vit(s,t,r){return typeof s=="number"&&typeof t=="number"&&typeof r=="number"?Nd(s,t,r):OTe(s)(s,t)}const mqt=s=>{const t=({timestamp:r})=>s(r);return{start:(r=!0)=>qc.update(t,r),stop:()=>RS(t),now:()=>Df.isProcessing?Df.timestamp:bx.now()}},Hit=(s,t,r=10)=>{let n="";const a=Math.max(Math.round(t/r),2);for(let i=0;i=gme?1/0:t}function fqt(s,t=100,r){const n=r({...s,keyframes:[0,t]}),a=Math.min(FTe(n),gme);return{type:"keyframes",ease:i=>n.next(a*i).value/t,duration:Gy(a)}}const ou={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 ake(s,t){return s*Math.sqrt(1-t*t)}const pqt=12;function xqt(s,t,r){let n=r;for(let a=1;a{const u=d*l,m=u*s,f=u-r,x=ake(d,l),y=Math.exp(-m);return Qbe-f/x*y},i=d=>{const m=d*l*s,f=m*r+r,x=Math.pow(l,2)*Math.pow(d,2)*s,y=Math.exp(-m),_=ake(Math.pow(d,2),l);return(-a(d)+Qbe>0?-1:1)*((f-x)*y)/_}):(a=d=>{const u=Math.exp(-d*s),m=(d-r)*s+1;return-Qbe+u*m},i=d=>{const u=Math.exp(-d*s),m=(r-d)*(s*s);return u*m});const o=5/s,c=xqt(a,i,o);if(s=vg(s),isNaN(c))return{stiffness:ou.stiffness,damping:ou.damping,duration:s};{const d=Math.pow(c,2)*n;return{stiffness:d,damping:l*2*Math.sqrt(n*d),duration:s}}}const yqt=["duration","bounce"],vqt=["stiffness","damping","mass"];function L7e(s,t){return t.some(r=>s[r]!==void 0)}function bqt(s){let t={velocity:ou.velocity,stiffness:ou.stiffness,damping:ou.damping,mass:ou.mass,isResolvedFromDuration:!1,...s};if(!L7e(s,vqt)&&L7e(s,yqt))if(t.velocity=0,s.visualDuration){const r=s.visualDuration,n=2*Math.PI/(r*1.2),a=n*n,i=2*$_(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:ou.mass,stiffness:a,damping:i}}else{const r=gqt({...s,velocity:0});t={...t,...r,mass:ou.mass},t.isResolvedFromDuration=!0}return t}function yme(s=ou.visualDuration,t=ou.bounce){const r=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:n,restDelta:a}=r;const i=r.keyframes[0],l=r.keyframes[r.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:m,velocity:f,isResolvedFromDuration:x}=bqt({...r,velocity:-Gy(r.velocity||0)}),y=f||0,_=d/(2*Math.sqrt(c*u)),b=l-i,j=Gy(Math.sqrt(c/u)),N=Math.abs(b)<5;n||(n=N?ou.restSpeed.granular:ou.restSpeed.default),a||(a=N?ou.restDelta.granular:ou.restDelta.default);let C,A,E,D,R,F;if(_<1)E=ake(j,_),D=(y+_*j*b)/E,C=B=>{const K=Math.exp(-_*j*B);return l-K*(D*Math.sin(E*B)+b*Math.cos(E*B))},R=_*j*D+b*E,F=_*j*b-D*E,A=B=>Math.exp(-_*j*B)*(R*Math.sin(E*B)+F*Math.cos(E*B));else if(_===1){C=K=>l-Math.exp(-j*K)*(b+(y+j*b)*K);const B=y+j*b;A=K=>Math.exp(-j*K)*(j*B*K-y)}else{const B=j*Math.sqrt(_*_-1);C=W=>{const te=Math.exp(-_*j*W),ne=Math.min(B*W,300);return l-te*((y+_*j*b)*Math.sinh(ne)+B*b*Math.cosh(ne))/B};const K=(y+_*j*b)/B,Z=_*j*K-b*B,Q=_*j*b-K*B;A=W=>{const te=Math.exp(-_*j*W),ne=Math.min(B*W,300);return te*(Z*Math.sinh(ne)+Q*Math.cosh(ne))}}const O={calculatedDuration:x&&m||null,velocity:B=>vg(A(B)),next:B=>{if(!x&&_<1){const Z=Math.exp(-_*j*B),Q=Math.sin(E*B),W=Math.cos(E*B),te=l-Z*(D*Q+b*W),ne=vg(Z*(R*Q+F*W));return o.done=Math.abs(ne)<=n&&Math.abs(l-te)<=a,o.value=o.done?l:te,o}const K=C(B);if(x)o.done=B>=m;else{const Z=vg(A(B));o.done=Math.abs(Z)<=n&&Math.abs(l-K)<=a}return o.value=o.done?l:K,o},toString:()=>{const B=Math.min(FTe(O),gme),K=Hit(Z=>O.next(B*Z).value,B,30);return B+"ms "+K},toTransition:()=>{}};return O}yme.applyToOptions=s=>{const t=fqt(s,100,yme);return s.ease=t.ease,s.duration=vg(t.duration),s.type="keyframes",s};const _qt=5;function Git(s,t,r){const n=Math.max(t-_qt,0);return kit(r-s(n),t-n)}function ike({keyframes:s,velocity:t=0,power:r=.8,timeConstant:n=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const m=s[0],f={done:!1,value:m},x=F=>o!==void 0&&Fc,y=F=>o===void 0?c:c===void 0||Math.abs(o-F)-_*Math.exp(-F/n),C=F=>j+N(F),A=F=>{const O=N(F),B=C(F);f.done=Math.abs(O)<=d,f.value=f.done?j:B};let E,D;const R=F=>{x(f.value)&&(E=F,D=yme({keyframes:[f.value,y(f.value)],velocity:Git(C,F,f.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return R(0),{calculatedDuration:null,next:F=>{let O=!1;return!D&&E===void 0&&(O=!0,A(F),R(F)),E!==void 0&&F>=E?D.next(F-E):(!O&&A(F),f)}}}function wqt(s,t,r){const n=[],a=r||DS.mix||Vit,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=wqt(t,n,a),c=o.length,d=u=>{if(l&&u1)for(;md($_(s[0],s[i-1],u)):d}function Nqt(s,t){const r=s[s.length-1];for(let n=1;n<=t;n++){const a=M9(0,t,n);s.push(Nd(r,1,a))}}function kqt(s){const t=[0];return Nqt(t,s.length-1),t}function Sqt(s,t){return s.map(r=>r*t)}function Cqt(s,t){return s.map(()=>t||Lit).splice(0,s.length-1)}function p7({duration:s=300,keyframes:t,times:r,ease:n="easeInOut"}){const a=RUt(n)?n.map(C7e):C7e(n),i={done:!1,value:t[0]},l=Sqt(r&&r.length===t.length?r:kqt(t),s),o=jqt(l,t,{ease:Array.isArray(a)?a:Cqt(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const Tqt=s=>s!==null;function bge(s,{repeat:t,repeatType:r="loop"},n,a=1){const i=s.filter(Tqt),o=a<0||t&&r!=="loop"&&t%2===1?0:i.length-1;return!o||n===void 0?i[o]:n}const Eqt={decay:ike,inertia:ike,tween:p7,keyframes:p7,spring:yme};function Wit(s){typeof s.type=="string"&&(s.type=Eqt[s.type])}class zTe{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,r){return this.finished.then(t,r)}}const Aqt=s=>s/100;class vme extends zTe{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{var n,a;const{motionValue:r}=this.options;r&&r.updatedAt!==bx.now()&&this.tick(bx.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(a=(n=this.options).onStop)==null||a.call(n))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;Wit(t);const{type:r=p7,repeat:n=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=r||p7;c!==p7&&typeof o[0]!="number"&&(this.mixKeyframes=_B(Aqt,Vit(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=FTe(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(n+1)-a,this.generator=d}updateTime(t){const r=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=r}tick(t,r=!1){const{generator:n,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return n.next(0);const{delay:d=0,keyframes:u,repeat:m,repeatType:f,repeatDelay:x,type:y,onUpdate:_,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),r?this.currentTime=t:this.updateTime(t);const j=this.currentTime-d*(this.playbackSpeed>=0?1:-1),N=this.playbackSpeed>=0?j<0:j>a;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let C=this.currentTime,A=n;if(m){const F=Math.min(this.currentTime,a)/o;let O=Math.floor(F),B=F%1;!B&&F>=1&&(B=1),B===1&&O--,O=Math.min(O,m+1),!!(O%2)&&(f==="reverse"?(B=1-B,x&&(B-=x/o)):f==="mirror"&&(A=l)),C=$_(0,1,B)*o}let E;N?(this.delayState.value=u[0],E=this.delayState):E=A.next(C),i&&!N&&(E.value=i(E.value));let{done:D}=E;!N&&c!==null&&(D=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const R=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return R&&y!==ike&&(E.value=bge(u,this.options,b,this.speed)),_&&_(E.value),R&&this.finish(),E}then(t,r){return this.finished.then(t,r)}get duration(){return Gy(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Gy(t)}get time(){return Gy(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 r=this.generator.next(t).value;return Git(n=>this.generator.next(n).value,t,r)}get speed(){return this.playbackSpeed}set speed(t){const r=this.playbackSpeed!==t;r&&this.driver&&this.updateTime(bx.now()),this.playbackSpeed=t,r&&this.driver&&(this.time=Gy(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=mqt,startTime:r}=this.options;this.driver||(this.driver=t(l=>this.tick(l))),(i=(a=this.options).onPlay)==null||i.call(a);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=r??n),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(bx.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,r;this.notifyFinished(),this.teardown(),this.state="finished",(r=(t=this.options).onComplete)==null||r.call(t)}cancel(){var t,r;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(r=(t=this.options).onCancel)==null||r.call(t)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){var r;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(r=this.driver)==null||r.stop(),t.observe(this)}}function Mqt(s){for(let t=1;ts*180/Math.PI,oke=s=>{const t=XT(Math.atan2(s[1],s[0]));return lke(t)},Iqt={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:oke,rotateZ:oke,skewX:s=>XT(Math.atan(s[1])),skewY:s=>XT(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},lke=s=>(s=s%360,s<0&&(s+=360),s),D7e=oke,R7e=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),O7e=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),Pqt={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:R7e,scaleY:O7e,scale:s=>(R7e(s)+O7e(s))/2,rotateX:s=>lke(XT(Math.atan2(s[6],s[5]))),rotateY:s=>lke(XT(Math.atan2(-s[2],s[0]))),rotateZ:D7e,rotate:D7e,skewX:s=>XT(Math.atan(s[4])),skewY:s=>XT(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function cke(s){return s.includes("scale")?1:0}function dke(s,t){if(!s||s==="none")return cke(t);const r=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,a;if(r)n=Pqt,a=r;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Iqt,a=o}if(!a)return cke(t);const i=n[t],l=a[1].split(",").map(Dqt);return typeof i=="function"?i(l):l[i]}const Lqt=(s,t)=>{const{transform:r="none"}=getComputedStyle(s);return dke(r,t)};function Dqt(s){return parseFloat(s.trim())}const T8=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],E8=new Set(T8),F7e=s=>s===C8||s===ai,Rqt=new Set(["x","y","z"]),Oqt=T8.filter(s=>!Rqt.has(s));function Fqt(s){const t=[];return Oqt.forEach(r=>{const n=s.getValue(r);n!==void 0&&(t.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),t}const Ok={width:({x:s},{paddingLeft:t="0",paddingRight:r="0",boxSizing:n})=>{const a=s.max-s.min;return n==="border-box"?a:a-parseFloat(t)-parseFloat(r)},height:({y:s},{paddingTop:t="0",paddingBottom:r="0",boxSizing:n})=>{const a=s.max-s.min;return n==="border-box"?a:a-parseFloat(t)-parseFloat(r)},top:(s,{top:t})=>parseFloat(t),left:(s,{left:t})=>parseFloat(t),bottom:({y:s},{top:t})=>parseFloat(t)+(s.max-s.min),right:({x:s},{left:t})=>parseFloat(t)+(s.max-s.min),x:(s,{transform:t})=>dke(t,"x"),y:(s,{transform:t})=>dke(t,"y")};Ok.translateX=Ok.x;Ok.translateY=Ok.y;const KE=new Set;let uke=!1,hke=!1,mke=!1;function Kit(){if(hke){const s=Array.from(KE).filter(n=>n.needsMeasurement),t=new Set(s.map(n=>n.element)),r=new Map;t.forEach(n=>{const a=Fqt(n);a.length&&(r.set(n,a),n.render())}),s.forEach(n=>n.measureInitialState()),t.forEach(n=>{n.render();const a=r.get(n);a&&a.forEach(([i,l])=>{var o;(o=n.getValue(i))==null||o.set(l)})}),s.forEach(n=>n.measureEndState()),s.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}hke=!1,uke=!1,KE.forEach(s=>s.complete(mke)),KE.clear()}function Yit(){KE.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(hke=!0)})}function zqt(){mke=!0,Yit(),Kit(),mke=!1}class BTe{constructor(t,r,n,a,i,l=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=r,this.name=n,this.motionValue=a,this.element=i,this.isAsync=l}scheduleResolve(){this.state="scheduled",this.isAsync?(KE.add(this),uke||(uke=!0,qc.read(Yit),qc.resolveKeyframes(Kit))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:r,element:n,motionValue:a}=this;if(t[0]===null){const i=a==null?void 0:a.get(),l=t[t.length-1];if(i!==void 0)t[0]=i;else if(n&&r){const o=n.readValue(r,l);o!=null&&(t[0]=o)}t[0]===void 0&&(t[0]=l),a&&i===void 0&&a.set(t[0])}Mqt(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),KE.delete(this)}cancel(){this.state==="scheduled"&&(KE.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Bqt=s=>s.startsWith("--");function Zit(s,t,r){Bqt(t)?s.style.setProperty(t,r):s.style[t]=r}const $qt={};function Xit(s,t){const r=Nit(s);return()=>$qt[t]??r()}const Uqt=Xit(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),Qit=Xit(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),IO=([s,t,r,n])=>`cubic-bezier(${s}, ${t}, ${r}, ${n})`,z7e={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:IO([0,.65,.55,1]),circOut:IO([.55,0,1,.45]),backIn:IO([.31,.01,.66,-.59]),backOut:IO([.33,1.53,.69,.99])};function Jit(s,t){if(s)return typeof s=="function"?Qit()?Hit(s,t):"ease-out":Dit(s)?IO(s):Array.isArray(s)?s.map(r=>Jit(r,t)||z7e.easeOut):z7e[s]}function qqt(s,t,r,{delay:n=0,duration:a=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const u={[t]:r};c&&(u.offset=c);const m=Jit(o,a);Array.isArray(m)&&(u.easing=m);const f={delay:n,duration:a,easing:Array.isArray(m)?"linear":m,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(f.pseudoElement=d),s.animate(u,f)}function eot(s){return typeof s=="function"&&"applyToOptions"in s}function Vqt({type:s,...t}){return eot(s)&&Qit()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class tot extends zTe{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:r,name:n,keyframes:a,pseudoElement:i,allowFlatten:l=!1,finalKeyframe:o,onComplete:c}=t;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=t,mL(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=Vqt(t);this.animation=qqt(r,n,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=bge(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),Zit(r,n,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,r;(r=(t=this.animation).finish)==null||r.call(t)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var r,n,a;const t=(r=this.options)==null?void 0:r.element;!this.isPseudoElement&&(t!=null&&t.isConnected)&&((a=(n=this.animation).commitStyles)==null||a.call(n))}get duration(){var r,n;const t=((n=(r=this.animation.effect)==null?void 0:r.getComputedTiming)==null?void 0:n.call(r).duration)||0;return Gy(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Gy(t)}get time(){return Gy(Number(this.animation.currentTime)||0)}set time(t){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=vg(t),r&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(t){this.manualStartTime=this.animation.startTime=t}attachTimeline({timeline:t,rangeStart:r,rangeEnd:n,observe:a}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&Uqt()?(this.animation.timeline=t,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),sv):a(this)}}const sot={anticipate:Mit,backInOut:Ait,circInOut:Pit};function Hqt(s){return s in sot}function Gqt(s){typeof s.ease=="string"&&Hqt(s.ease)&&(s.ease=sot[s.ease])}const Jbe=10;class Wqt extends tot{constructor(t){Gqt(t),Wit(t),super(t),t.startTime!==void 0&&t.autoplay!==!1&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:r,onUpdate:n,onComplete:a,element:i,...l}=this.options;if(!r)return;if(t!==void 0){r.set(t);return}const o=new vme({...l,autoplay:!1}),c=Math.max(Jbe,bx.now()-this.startTime),d=$_(0,Jbe,c-Jbe),u=o.sample(c).value,{name:m}=this.options;i&&m&&Zit(i,m,u),r.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const B7e=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(I1.test(s)||s==="0")&&!s.startsWith("url("));function Kqt(s){const t=s[0];if(s.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function eVt(s){var m;const{motionValue:t,name:r,repeatDelay:n,repeatType:a,damping:i,type:l,keyframes:o}=s;if(!(((m=t==null?void 0:t.owner)==null?void 0:m.current)instanceof HTMLElement))return!1;const{onUpdate:d,transformTemplate:u}=t.owner.getProps();return Jqt()&&r&&(rot.has(r)||Qqt.has(r)&&Xqt(o))&&(r!=="transform"||!u)&&!d&&!n&&a!=="mirror"&&i!==0&&l!=="inertia"}const tVt=40;class sVt extends zTe{constructor({autoplay:t=!0,delay:r=0,type:n="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...m}){var y;super(),this.stop=()=>{var _,b;this._animation&&(this._animation.stop(),(_=this.stopTimeline)==null||_.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=bx.now();const f={autoplay:t,delay:r,type:n,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...m},x=(u==null?void 0:u.KeyframeResolver)||BTe;this.keyframeResolver=new x(o,(_,b,j)=>this.onKeyframesResolved(_,b,f,!j),c,d,u),(y=this.keyframeResolver)==null||y.scheduleResolve()}onKeyframesResolved(t,r,n,a){var j,N;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=n;this.resolvedAt=bx.now();let m=!0;Yqt(t,i,l,o)||(m=!1,(DS.instantAnimations||!c)&&(u==null||u(bge(t,n,r))),t[0]=t[t.length-1],fke(n),n.repeat=0);const x={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>tVt?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:t},y=m&&!d&&eVt(x),_=(N=(j=x.motionValue)==null?void 0:j.owner)==null?void 0:N.current;let b;if(y)try{b=new Wqt({...x,element:_})}catch{b=new vme(x)}else b=new vme(x);b.finished.then(()=>{this.notifyFinished()}).catch(sv),this.pendingTimeline&&(this.stopTimeline=b.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=b}get finished(){return this._animation?this.animation.finished:this._finished}then(t,r){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),zqt()),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 not(s,t,r,n=0,a=1){const i=Array.from(s).sort((d,u)=>d.sortNodePosition(u)).indexOf(t),l=s.size,o=(l-1)*n;return typeof r=="function"?r(i,l):a===1?i*n:o-i*n}const rVt=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function nVt(s){const t=rVt.exec(s);if(!t)return[,];const[,r,n,a]=t;return[`--${r??n}`,a]}const aVt=4;function aot(s,t,r=1){mL(r<=aVt,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[n,a]=nVt(s);if(!n)return;const i=window.getComputedStyle(t).getPropertyValue(n);if(i){const l=i.trim();return _it(l)?parseFloat(l):l}return LTe(a)?aot(a,t,r+1):a}const iVt={type:"spring",stiffness:500,damping:25,restSpeed:10},oVt=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),lVt={type:"keyframes",duration:.8},cVt={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},dVt=(s,{keyframes:t})=>t.length>2?lVt:E8.has(s)?s.startsWith("scale")?oVt(t[1]):iVt:cVt;function iot(s,t){if(s!=null&&s.inherit&&t){const{inherit:r,...n}=s;return{...t,...n}}return s}function $Te(s,t){const r=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return r!==s?iot(r,s):r}const uVt=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function hVt(s){for(const t in s)if(!uVt.has(t))return!0;return!1}const UTe=(s,t,r,n={},a,i)=>l=>{const o=$Te(n,s)||{},c=o.delay||n.delay||0;let{elapsed:d=0}=n;d=d-vg(c);const u={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:f=>{t.set(f),o.onUpdate&&o.onUpdate(f)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};hVt(o)||Object.assign(u,dVt(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 m=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(fke(u),u.delay===0&&(m=!0)),(DS.instantAnimations||DS.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(m=!0,fke(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,m&&!i&&t.get()!==void 0){const f=bge(u.keyframes,o);if(f!==void 0){qc.update(()=>{u.onUpdate(f),u.onComplete()});return}}return o.isSync?new vme(u):new sVt(u)};function $7e(s){const t=[{},{}];return s==null||s.values.forEach((r,n)=>{t[0][n]=r.get(),t[1][n]=r.getVelocity()}),t}function qTe(s,t,r,n){if(typeof t=="function"){const[a,i]=$7e(n);t=t(r!==void 0?r:s.custom,a,i)}if(typeof t=="string"&&(t=s.variants&&s.variants[t]),typeof t=="function"){const[a,i]=$7e(n);t=t(r!==void 0?r:s.custom,a,i)}return t}function YE(s,t,r){const n=s.getProps();return qTe(n,t,r!==void 0?r:n.custom,s)}const oot=new Set(["width","height","top","left","right","bottom",...T8]),U7e=30,mVt=s=>!isNaN(parseFloat(s));class fVt{constructor(t,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var i;const a=bx.now();if(this.updatedAt!==a&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),this.current!==this.prev&&((i=this.events.change)==null||i.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=r.owner}setCurrent(t){this.current=t,this.updatedAt=bx.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=mVt(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,r){this.events[t]||(this.events[t]=new MTe);const n=this.events[t].add(r);return t==="change"?()=>{n(),qc.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,r){this.passiveEffect=t,this.stopPassiveEffect=r}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,r,n){this.set(r),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,r=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,r&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var t;(t=this.events.change)==null||t.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=bx.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>U7e)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,U7e);return kit(parseFloat(this.current)-parseFloat(this.prevFrameValue),r)}start(t){return this.stop(),new Promise(r=>{this.hasAnimated=!0,this.animation=t(r),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var t,r;(t=this.dependents)==null||t.clear(),(r=this.events.destroy)==null||r.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function pL(s,t){return new fVt(s,t)}const pke=s=>Array.isArray(s);function pVt(s,t,r){s.hasValue(t)?s.getValue(t).set(r):s.addValue(t,pL(r))}function xVt(s){return pke(s)?s[s.length-1]||0:s}function gVt(s,t){const r=YE(s,t);let{transitionEnd:n={},transition:a={},...i}=r||{};i={...i,...n};for(const l in i){const o=xVt(i[l]);pVt(s,l,o)}}const qf=s=>!!(s&&s.getVelocity);function yVt(s){return!!(qf(s)&&s.add)}function xke(s,t){const r=s.getValue("willChange");if(yVt(r))return r.add(t);if(!r&&DS.WillChange){const n=new DS.WillChange("auto");s.addValue("willChange",n),n.add(t)}}function VTe(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const vVt="framerAppearId",lot="data-"+VTe(vVt);function cot(s){return s.props[lot]}function bVt({protectedKeys:s,needsAnimating:t},r){const n=s.hasOwnProperty(r)&&t[r]!==!0;return t[r]=!1,n}function dot(s,t,{delay:r=0,transitionOverride:n,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?iot(i,c):c;const d=i==null?void 0:i.reduceMotion;n&&(i=n);const u=[],m=a&&s.animationState&&s.animationState.getState()[a];for(const f in o){const x=s.getValue(f,s.latestValues[f]??null),y=o[f];if(y===void 0||m&&bVt(m,f))continue;const _={delay:r,...$Te(i||{},f)},b=x.get();if(b!==void 0&&!x.isAnimating()&&!Array.isArray(y)&&y===b&&!_.velocity){qc.update(()=>x.set(y));continue}let j=!1;if(window.MotionHandoffAnimation){const A=cot(s);if(A){const E=window.MotionHandoffAnimation(A,f,qc);E!==null&&(_.startTime=E,j=!0)}}xke(s,f);const N=d??s.shouldReduceMotion;x.start(UTe(f,x,y,N&&oot.has(f)?{type:!1}:_,s,j));const C=x.animation;C&&u.push(C)}if(l){const f=()=>qc.update(()=>{l&&gVt(s,l)});u.length?Promise.all(u).then(f):f()}return u}function gke(s,t,r={}){var c;const n=YE(s,t,r.type==="exit"?(c=s.presenceContext)==null?void 0:c.custom:void 0);let{transition:a=s.getDefaultTransition()||{}}=n||{};r.transitionOverride&&(a=r.transitionOverride);const i=n?()=>Promise.all(dot(s,n,r)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:m,staggerDirection:f}=a;return _Vt(s,t,d,u,m,f,r)}:()=>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(r.delay)])}function _Vt(s,t,r=0,n=0,a=0,i=1,l){const o=[];for(const c of s.variantChildren)c.notify("AnimationStart",t),o.push(gke(c,t,{...l,delay:r+(typeof n=="function"?0:n)+not(s.variantChildren,c,n,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function wVt(s,t,r={}){s.notify("AnimationStart",t);let n;if(Array.isArray(t)){const a=t.map(i=>gke(s,i,r));n=Promise.all(a)}else if(typeof t=="string")n=gke(s,t,r);else{const a=typeof t=="function"?YE(s,t,r.custom):t;n=Promise.all(dot(s,a,r))}return n.then(()=>{s.notify("AnimationComplete",t)})}const jVt={test:s=>s==="auto",parse:s=>s},uot=s=>t=>t.test(s),hot=[C8,ai,I_,YN,KUt,WUt,jVt],q7e=s=>hot.find(uot(s));function NVt(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||jit(s):!0}const kVt=new Set(["brightness","contrast","saturate","opacity"]);function SVt(s){const[t,r]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[n]=r.match(DTe)||[];if(!n)return s;const a=r.replace(n,"");let i=kVt.has(t)?1:0;return n!==r&&(i*=100),t+"("+i+a+")"}const CVt=/\b([a-z-]*)\(.*?\)/gu,yke={...I1,getAnimatableNone:s=>{const t=s.match(CVt);return t?t.map(SVt).join(" "):s}},vke={...I1,getAnimatableNone:s=>{const t=I1.parse(s);return I1.createTransformer(s)(t.map(n=>typeof n=="number"?0:typeof n=="object"?{...n,alpha:1}:n))}},V7e={...C8,transform:Math.round},TVt={rotate:YN,rotateX:YN,rotateY:YN,rotateZ:YN,scale:xq,scaleX:xq,scaleY:xq,scaleZ:xq,skew:YN,skewX:YN,skewY:YN,distance:ai,translateX:ai,translateY:ai,translateZ:ai,x:ai,y:ai,z:ai,perspective:ai,transformPerspective:ai,opacity:I9,originX:A7e,originY:A7e,originZ:ai},HTe={borderWidth:ai,borderTopWidth:ai,borderRightWidth:ai,borderBottomWidth:ai,borderLeftWidth:ai,borderRadius:ai,borderTopLeftRadius:ai,borderTopRightRadius:ai,borderBottomRightRadius:ai,borderBottomLeftRadius:ai,width:ai,maxWidth:ai,height:ai,maxHeight:ai,top:ai,right:ai,bottom:ai,left:ai,inset:ai,insetBlock:ai,insetBlockStart:ai,insetBlockEnd:ai,insetInline:ai,insetInlineStart:ai,insetInlineEnd:ai,padding:ai,paddingTop:ai,paddingRight:ai,paddingBottom:ai,paddingLeft:ai,paddingBlock:ai,paddingBlockStart:ai,paddingBlockEnd:ai,paddingInline:ai,paddingInlineStart:ai,paddingInlineEnd:ai,margin:ai,marginTop:ai,marginRight:ai,marginBottom:ai,marginLeft:ai,marginBlock:ai,marginBlockStart:ai,marginBlockEnd:ai,marginInline:ai,marginInlineStart:ai,marginInlineEnd:ai,fontSize:ai,backgroundPositionX:ai,backgroundPositionY:ai,...TVt,zIndex:V7e,fillOpacity:I9,strokeOpacity:I9,numOctaves:V7e},EVt={...HTe,color:Ah,backgroundColor:Ah,outlineColor:Ah,fill:Ah,stroke:Ah,borderColor:Ah,borderTopColor:Ah,borderRightColor:Ah,borderBottomColor:Ah,borderLeftColor:Ah,filter:yke,WebkitFilter:yke,mask:vke,WebkitMask:vke},mot=s=>EVt[s],AVt=new Set([yke,vke]);function fot(s,t){let r=mot(s);return AVt.has(r)||(r=I1),r.getAnimatableNone?r.getAnimatableNone(t):void 0}const MVt=new Set(["auto","none","0"]);function IVt(s,t,r){let n=0,a;for(;n{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function GTe(s,t,r){if(s==null)return[];if(s instanceof EventTarget)return[s];if(typeof s=="string"){const a=document.querySelectorAll(s);return a?Array.from(a):[]}return Array.from(s).filter(n=>n!=null)}const pot=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function $ue(s){return wit(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:WTe,cancel:qnr}=Rit(queueMicrotask,!1),r1={x:!1,y:!1};function xot(){return r1.x||r1.y}function LVt(s){return s==="x"||s==="y"?r1[s]?null:(r1[s]=!0,()=>{r1[s]=!1}):r1.x||r1.y?null:(r1.x=r1.y=!0,()=>{r1.x=r1.y=!1})}function got(s,t){const r=GTe(s),n=new AbortController,a={passive:!0,...t,signal:n.signal};return[r,a,()=>n.abort()]}function DVt(s){return!(s.pointerType==="touch"||xot())}function RVt(s,t,r={}){const[n,a,i]=got(s,r);return n.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",y)},m=b=>{d&&(d(b),d=void 0),u()},f=b=>{o=!1,window.removeEventListener("pointerup",f),window.removeEventListener("pointercancel",f),c&&(c=!1,m(b))},x=()=>{o=!0,window.addEventListener("pointerup",f,a),window.addEventListener("pointercancel",f,a)},y=b=>{if(b.pointerType!=="touch"){if(o){c=!0;return}m(b)}},_=b=>{if(!DVt(b))return;c=!1;const j=t(l,b);typeof j=="function"&&(d=j,l.addEventListener("pointerleave",y,a))};l.addEventListener("pointerenter",_,a),l.addEventListener("pointerdown",x,a)}),i}const yot=(s,t)=>t?s===t?!0:yot(s,t.parentElement):!1,KTe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,OVt=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function FVt(s){return OVt.has(s.tagName)||s.isContentEditable===!0}const zVt=new Set(["INPUT","SELECT","TEXTAREA"]);function BVt(s){return zVt.has(s.tagName)||s.isContentEditable===!0}const Uue=new WeakSet;function H7e(s){return t=>{t.key==="Enter"&&s(t)}}function e_e(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const $Vt=(s,t)=>{const r=s.currentTarget;if(!r)return;const n=H7e(()=>{if(Uue.has(r))return;e_e(r,"down");const a=H7e(()=>{e_e(r,"up")}),i=()=>e_e(r,"cancel");r.addEventListener("keyup",a,t),r.addEventListener("blur",i,t)});r.addEventListener("keydown",n,t),r.addEventListener("blur",()=>r.removeEventListener("keydown",n),t)};function G7e(s){return KTe(s)&&!xot()}const W7e=new WeakSet;function UVt(s,t,r={}){const[n,a,i]=got(s,r),l=o=>{const c=o.currentTarget;if(!G7e(o)||W7e.has(o))return;Uue.add(c),r.stopPropagation&&W7e.add(o);const d=t(c,o),u=(x,y)=>{window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",f),Uue.has(c)&&Uue.delete(c),G7e(x)&&typeof d=="function"&&d(x,{success:y})},m=x=>{u(x,c===window||c===document||r.useGlobalTarget||yot(c,x.target))},f=x=>{u(x,!1)};window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",f,a)};return n.forEach(o=>{(r.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),$ue(o)&&(o.addEventListener("focus",d=>$Vt(d,a)),!FVt(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function YTe(s){return wit(s)&&"ownerSVGElement"in s}const que=new WeakMap;let ZN;const vot=(s,t,r)=>(n,a)=>a&&a[0]?a[0][s+"Size"]:YTe(n)&&"getBBox"in n?n.getBBox()[t]:n[r],qVt=vot("inline","width","offsetWidth"),VVt=vot("block","height","offsetHeight");function HVt({target:s,borderBoxSize:t}){var r;(r=que.get(s))==null||r.forEach(n=>{n(s,{get width(){return qVt(s,t)},get height(){return VVt(s,t)}})})}function GVt(s){s.forEach(HVt)}function WVt(){typeof ResizeObserver>"u"||(ZN=new ResizeObserver(GVt))}function KVt(s,t){ZN||WVt();const r=GTe(s);return r.forEach(n=>{let a=que.get(n);a||(a=new Set,que.set(n,a)),a.add(t),ZN==null||ZN.observe(n)}),()=>{r.forEach(n=>{const a=que.get(n);a==null||a.delete(t),a!=null&&a.size||ZN==null||ZN.unobserve(n)})}}const Vue=new Set;let wI;function YVt(){wI=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};Vue.forEach(t=>t(s))},window.addEventListener("resize",wI)}function ZVt(s){return Vue.add(s),wI||YVt(),()=>{Vue.delete(s),!Vue.size&&typeof wI=="function"&&(window.removeEventListener("resize",wI),wI=void 0)}}function K7e(s,t){return typeof s=="function"?ZVt(s):KVt(s,t)}function XVt(s){return YTe(s)&&s.tagName==="svg"}const QVt=[...hot,Ah,I1],JVt=s=>QVt.find(uot(s)),Y7e=()=>({translate:0,scale:1,origin:0,originPoint:0}),jI=()=>({x:Y7e(),y:Y7e()}),Z7e=()=>({min:0,max:0}),nm=()=>({x:Z7e(),y:Z7e()}),eHt=new WeakMap;function _ge(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function P9(s){return typeof s=="string"||Array.isArray(s)}const ZTe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],XTe=["initial",...ZTe];function wge(s){return _ge(s.animate)||XTe.some(t=>P9(s[t]))}function bot(s){return!!(wge(s)||s.variants)}function tHt(s,t,r){for(const n in t){const a=t[n],i=r[n];if(qf(a))s.addValue(n,a);else if(qf(i))s.addValue(n,pL(a,{owner:s}));else if(i!==a)if(s.hasValue(n)){const l=s.getValue(n);l.liveStyle===!0?l.jump(a):l.hasAnimated||l.set(a)}else{const l=s.getStaticValue(n);s.addValue(n,pL(l!==void 0?l:a,{owner:s}))}}for(const n in r)t[n]===void 0&&s.removeValue(n);return t}const bke={current:null},_ot={current:!1},sHt=typeof window<"u";function rHt(){if(_ot.current=!0,!!sHt)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>bke.current=s.matches;s.addEventListener("change",t),t()}else bke.current=!1}const X7e=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let bme={};function wot(s){bme=s}function nHt(){return bme}class aHt{scrapeMotionValuesFromProps(t,r,n){return{}}constructor({parent:t,props:r,presenceContext:n,reducedMotionConfig:a,skipAnimations:i,blockInitialAnimation:l,visualState:o},c={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=BTe,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 x=bx.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(_ot.current||rHt(),this.shouldReduceMotion=bke.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(n=this.parent)==null||n.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var t;this.projection&&this.projection.unmount(),RS(this.notifyUpdate),RS(this.render),this.valueSubscriptions.forEach(r=>r()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const r in this.events)this.events[r].clear();for(const r in this.features){const n=this.features[r];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,r){if(this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)(),r.accelerate&&rot.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=r.accelerate,m=new tot({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:vg(u)}),f=l(m);this.valueSubscriptions.set(t,()=>{f(),m.cancel()});return}const n=E8.has(t);n&&this.onBindTransform&&this.onBindTransform();const a=r.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&qc.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,r)),this.valueSubscriptions.set(t,()=>{a(),i&&i(),r.owner&&r.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in bme){const r=bme[t];if(!r)continue;const{isEnabled:n,Feature:a}=r;if(!this.features[t]&&a&&n(this.props)&&(this.features[t]=new a(this)),this.features[t]){const i=this.features[t];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):nm()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,r){this.latestValues[t]=r}update(t,r){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=r;for(let n=0;nr.variantChildren.delete(t)}addValue(t,r){const n=this.values.get(t);r!==n&&(n&&this.removeValue(t),this.bindToMotionValue(t,r),this.values.set(t,r),this.latestValues[t]=r.get())}removeValue(t){this.values.delete(t);const r=this.valueSubscriptions.get(t);r&&(r(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,r){if(this.props.values&&this.props.values[t])return this.props.values[t];let n=this.values.get(t);return n===void 0&&r!==void 0&&(n=pL(r===null?void 0:r,{owner:this}),this.addValue(t,n)),n}readValue(t,r){let n=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return n!=null&&(typeof n=="string"&&(_it(n)||jit(n))?n=parseFloat(n):!JVt(n)&&I1.test(r)&&(n=fot(t,r)),this.setBaseTarget(t,qf(n)?n.get():n)),qf(n)?n.get():n}setBaseTarget(t,r){this.baseTarget[t]=r}getBaseTarget(t){var i;const{initial:r}=this.props;let n;if(typeof r=="string"||typeof r=="object"){const l=qTe(this.props,r,(i=this.presenceContext)==null?void 0:i.custom);l&&(n=l[t])}if(r&&n!==void 0)return n;const a=this.getBaseTargetFromProps(this.props,t);return a!==void 0&&!qf(a)?a:this.initialValues[t]!==void 0&&n===void 0?void 0:this.baseTarget[t]}on(t,r){return this.events[t]||(this.events[t]=new MTe),this.events[t].add(r)}notify(t,...r){this.events[t]&&this.events[t].notify(...r)}scheduleRenderMicrotask(){WTe.render(this.render)}}class jot extends aHt{constructor(){super(...arguments),this.KeyframeResolver=PVt}sortInstanceNodePosition(t,r){return t.compareDocumentPosition(r)&2?1:-1}getBaseTargetFromProps(t,r){const n=t.style;return n?n[r]:void 0}removeValueFromRenderState(t,{vars:r,style:n}){delete r[t],delete n[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;qf(t)&&(this.childSubscription=t.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class r4{constructor(t){this.isMounted=!1,this.node=t}update(){}}function Not({top:s,left:t,right:r,bottom:n}){return{x:{min:t,max:r},y:{min:s,max:n}}}function iHt({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function oHt(s,t){if(!t)return s;const r=t({x:s.left,y:s.top}),n=t({x:s.right,y:s.bottom});return{top:r.y,left:r.x,bottom:n.y,right:n.x}}function t_e(s){return s===void 0||s===1}function _ke({scale:s,scaleX:t,scaleY:r}){return!t_e(s)||!t_e(t)||!t_e(r)}function DT(s){return _ke(s)||kot(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function kot(s){return Q7e(s.x)||Q7e(s.y)}function Q7e(s){return s&&s!=="0%"}function _me(s,t,r){const n=s-r,a=t*n;return r+a}function J7e(s,t,r,n,a){return a!==void 0&&(s=_me(s,a,n)),_me(s,r,n)+t}function wke(s,t=0,r=1,n,a){s.min=J7e(s.min,t,r,n,a),s.max=J7e(s.max,t,r,n,a)}function Sot(s,{x:t,y:r}){wke(s.x,t.translate,t.scale,t.originPoint),wke(s.y,r.translate,r.scale,r.originPoint)}const e9e=.999999999999,t9e=1.0000000000001;function lHt(s,t,r,n=!1){var o;const a=r.length;if(!a)return;t.x=t.y=1;let i,l;for(let c=0;ce9e&&(t.x=1),t.ye9e&&(t.y=1)}function s_(s,t){s.min+=t,s.max+=t}function s9e(s,t,r,n,a=.5){const i=Nd(s.min,s.max,a);wke(s,t,r,i,n)}function r9e(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function Hue(s,t,r){const n=r??s;s9e(s.x,r9e(t.x,n.x),t.scaleX,t.scale,t.originX),s9e(s.y,r9e(t.y,n.y),t.scaleY,t.scale,t.originY)}function Cot(s,t){return Not(oHt(s.getBoundingClientRect(),t))}function cHt(s,t,r){const n=Cot(s,r),{scroll:a}=t;return a&&(s_(n.x,a.offset.x),s_(n.y,a.offset.y)),n}const dHt={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},uHt=T8.length;function hHt(s,t,r){let n="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(ai.test(s))s=parseFloat(s);else return s;const r=n9e(s,t.target.x),n=n9e(s,t.target.y);return`${r}% ${n}%`}},mHt={correct:(s,{treeScale:t,projectionDelta:r})=>{const n=s,a=I1.parse(s);if(a.length>5)return n;const i=I1.createTransformer(s),l=typeof a[0]!="number"?1:0,o=r.x.scale*t.x,c=r.y.scale*t.y;a[0+l]/=o,a[1+l]/=c;const d=Nd(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},jke={borderRadius:{...BR,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:BR,borderTopRightRadius:BR,borderBottomLeftRadius:BR,borderBottomRightRadius:BR,boxShadow:mHt};function Eot(s,{layout:t,layoutId:r}){return E8.has(s)||s.startsWith("origin")||(t||r!==void 0)&&(!!jke[s]||s==="opacity")}function JTe(s,t,r){var l;const n=s.style,a=t==null?void 0:t.style,i={};if(!n)return i;for(const o in n)(qf(n[o])||a&&qf(a[o])||Eot(o,s)||((l=r==null?void 0:r.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=n[o]);return i}function fHt(s){return window.getComputedStyle(s)}class pHt extends jot{constructor(){super(...arguments),this.type="html",this.renderInstance=Tot}readValueFromInstance(t,r){var n;if(E8.has(r))return(n=this.projection)!=null&&n.isProjecting?cke(r):Lqt(t,r);{const a=fHt(t),i=(Fit(r)?a.getPropertyValue(r):a[r])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:r}){return Cot(t,r)}build(t,r,n){QTe(t,r,n.transformTemplate)}scrapeMotionValuesFromProps(t,r,n){return JTe(t,r,n)}}const xHt={offset:"stroke-dashoffset",array:"stroke-dasharray"},gHt={offset:"strokeDashoffset",array:"strokeDasharray"};function yHt(s,t,r=1,n=0,a=!0){s.pathLength=1;const i=a?xHt:gHt;s[i.offset]=`${-n}`,s[i.array]=`${t} ${r}`}const vHt=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Aot(s,{attrX:t,attrY:r,attrScale:n,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(QTe(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:m,style:f}=s;m.transform&&(f.transform=m.transform,delete m.transform),(f.transform||m.transformOrigin)&&(f.transformOrigin=m.transformOrigin??"50% 50%",delete m.transformOrigin),f.transform&&(f.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete m.transformBox);for(const x of vHt)m[x]!==void 0&&(f[x]=m[x],delete m[x]);t!==void 0&&(m.x=t),r!==void 0&&(m.y=r),n!==void 0&&(m.scale=n),a!==void 0&&yHt(m,a,i,l,!1)}const Mot=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"]),Iot=s=>typeof s=="string"&&s.toLowerCase()==="svg";function bHt(s,t,r,n){Tot(s,t,void 0,n);for(const a in t.attrs)s.setAttribute(Mot.has(a)?a:VTe(a),t.attrs[a])}function Pot(s,t,r){const n=JTe(s,t,r);for(const a in s)if(qf(s[a])||qf(t[a])){const i=T8.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;n[i]=s[a]}return n}class _Ht extends jot{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=nm}getBaseTargetFromProps(t,r){return t[r]}readValueFromInstance(t,r){if(E8.has(r)){const n=mot(r);return n&&n.default||0}return r=Mot.has(r)?r:VTe(r),t.getAttribute(r)}scrapeMotionValuesFromProps(t,r,n){return Pot(t,r,n)}build(t,r,n){Aot(t,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(t,r,n,a){bHt(t,r,n,a)}mount(t){this.isSVGTag=Iot(t.tagName),super.mount(t)}}const wHt=XTe.length;function Lot(s){if(!s)return;if(!s.isControllingVariants){const r=s.parent?Lot(s.parent)||{}:{};return s.props.initial!==void 0&&(r.initial=s.props.initial),r}const t={};for(let r=0;rPromise.all(t.map(({animation:r,options:n})=>wVt(s,r,n)))}function SHt(s){let t=kHt(s),r=a9e(),n=!0,a=!1;const i=d=>(u,m)=>{var x;const f=YE(s,m,d==="exit"?(x=s.presenceContext)==null?void 0:x.custom:void 0);if(f){const{transition:y,transitionEnd:_,...b}=f;u={...u,...b,..._}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,m=Lot(s.parent)||{},f=[],x=new Set;let y={},_=1/0;for(let j=0;j_&&E,B=!1;const K=Array.isArray(A)?A:[A];let Z=K.reduce(i(N),{});D===!1&&(Z={});const{prevResolvedValues:Q={}}=C,W={...Q,...Z},te=ue=>{O=!0,x.has(ue)&&(B=!0,x.delete(ue)),C.needsAnimating[ue]=!0;const me=s.getValue(ue);me&&(me.liveStyle=!1)};for(const ue in W){const me=Z[ue],de=Q[ue];if(y.hasOwnProperty(ue))continue;let fe=!1;pke(me)&&pke(de)?fe=!Dot(me,de):fe=me!==de,fe?me!=null?te(ue):x.add(ue):me!==void 0&&x.has(ue)?te(ue):C.protectedKeys[ue]=!0}C.prevProp=A,C.prevResolvedValues=Z,C.isActive&&(y={...y,...Z}),(n||a)&&s.blockInitialAnimation&&(O=!1);const ne=R&&F;O&&(!ne||B)&&f.push(...K.map(ue=>{const me={type:N};if(typeof ue=="string"&&(n||a)&&!ne&&s.manuallyAnimateOnMount&&s.parent){const{parent:de}=s,fe=YE(de,ue);if(de.enteringChildren&&fe){const{delayChildren:je}=fe.transition||{};me.delay=not(de.enteringChildren,s,je)}}return{animation:ue,options:me}}))}if(x.size){const j={};if(typeof u.initial!="boolean"){const N=YE(s,Array.isArray(u.initial)?u.initial[0]:u.initial);N&&N.transition&&(j.transition=N.transition)}x.forEach(N=>{const C=s.getBaseTarget(N),A=s.getValue(N);A&&(A.liveStyle=!0),j[N]=C??null}),f.push({animation:j})}let b=!!f.length;return n&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(b=!1),n=!1,a=!1,b?t(f):Promise.resolve()}function c(d,u){var f;if(r[d].isActive===u)return Promise.resolve();(f=s.variantChildren)==null||f.forEach(x=>{var y;return(y=x.animationState)==null?void 0:y.setActive(d,u)}),r[d].isActive=u;const m=o(d);for(const x in r)r[x].protectedKeys={};return m}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>r,reset:()=>{r=a9e(),a=!0}}}function CHt(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!Dot(t,s):!1}function mC(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function a9e(){return{animate:mC(!0),whileInView:mC(),whileHover:mC(),whileTap:mC(),whileDrag:mC(),whileFocus:mC(),exit:mC()}}function Nke(s,t){s.min=t.min,s.max=t.max}function Qv(s,t){Nke(s.x,t.x),Nke(s.y,t.y)}function i9e(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const Rot=1e-4,THt=1-Rot,EHt=1+Rot,Oot=.01,AHt=0-Oot,MHt=0+Oot;function _x(s){return s.max-s.min}function IHt(s,t,r){return Math.abs(s-t)<=r}function o9e(s,t,r,n=.5){s.origin=n,s.originPoint=Nd(t.min,t.max,s.origin),s.scale=_x(r)/_x(t),s.translate=Nd(r.min,r.max,s.origin)-s.originPoint,(s.scale>=THt&&s.scale<=EHt||isNaN(s.scale))&&(s.scale=1),(s.translate>=AHt&&s.translate<=MHt||isNaN(s.translate))&&(s.translate=0)}function x7(s,t,r,n){o9e(s.x,t.x,r.x,n?n.originX:void 0),o9e(s.y,t.y,r.y,n?n.originY:void 0)}function l9e(s,t,r,n=0){const a=n?Nd(r.min,r.max,n):r.min;s.min=a+t.min,s.max=s.min+_x(t)}function PHt(s,t,r,n){l9e(s.x,t.x,r.x,n==null?void 0:n.x),l9e(s.y,t.y,r.y,n==null?void 0:n.y)}function c9e(s,t,r,n=0){const a=n?Nd(r.min,r.max,n):r.min;s.min=t.min-a,s.max=s.min+_x(t)}function wme(s,t,r,n){c9e(s.x,t.x,r.x,n==null?void 0:n.x),c9e(s.y,t.y,r.y,n==null?void 0:n.y)}function d9e(s,t,r,n,a){return s-=t,s=_me(s,1/r,n),a!==void 0&&(s=_me(s,1/a,n)),s}function LHt(s,t=0,r=1,n=.5,a,i=s,l=s){if(I_.test(t)&&(t=parseFloat(t),t=Nd(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=Nd(i.min,i.max,n);s===i&&(o-=t),s.min=d9e(s.min,t,r,o,a),s.max=d9e(s.max,t,r,o,a)}function u9e(s,t,[r,n,a],i,l){LHt(s,t[r],t[n],t[a],t.scale,i,l)}const DHt=["x","scaleX","originX"],RHt=["y","scaleY","originY"];function h9e(s,t,r,n){u9e(s.x,t,DHt,r?r.x:void 0,n?n.x:void 0),u9e(s.y,t,RHt,r?r.y:void 0,n?n.y:void 0)}function m9e(s){return s.translate===0&&s.scale===1}function Fot(s){return m9e(s.x)&&m9e(s.y)}function f9e(s,t){return s.min===t.min&&s.max===t.max}function OHt(s,t){return f9e(s.x,t.x)&&f9e(s.y,t.y)}function p9e(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function zot(s,t){return p9e(s.x,t.x)&&p9e(s.y,t.y)}function x9e(s){return _x(s.x)/_x(s.y)}function g9e(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function Hb(s){return[s("x"),s("y")]}function FHt(s,t,r){let n="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(r==null?void 0:r.z)||0;if((a||i||l)&&(n=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(n+=`scale(${1/t.x}, ${1/t.y}) `),r){const{transformPerspective:d,rotate:u,rotateX:m,rotateY:f,skewX:x,skewY:y}=r;d&&(n=`perspective(${d}px) ${n}`),u&&(n+=`rotate(${u}deg) `),m&&(n+=`rotateX(${m}deg) `),f&&(n+=`rotateY(${f}deg) `),x&&(n+=`skewX(${x}deg) `),y&&(n+=`skewY(${y}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(n+=`scale(${o}, ${c})`),n||"none"}const Bot=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],zHt=Bot.length,y9e=s=>typeof s=="string"?parseFloat(s):s,v9e=s=>typeof s=="number"||ai.test(s);function BHt(s,t,r,n,a,i){a?(s.opacity=Nd(0,r.opacity??1,$Ht(n)),s.opacityExit=Nd(t.opacity??1,0,UHt(n))):i&&(s.opacity=Nd(t.opacity??1,r.opacity??1,n));for(let l=0;lnt?1:r(M9(s,t,n))}function qHt(s,t,r){const n=qf(s)?s:pL(s);return n.start(UTe("",n,t,r)),n.animation}function L9(s,t,r,n={passive:!0}){return s.addEventListener(t,r,n),()=>s.removeEventListener(t,r)}const VHt=(s,t)=>s.depth-t.depth;class HHt{constructor(){this.children=[],this.isDirty=!1}add(t){ATe(this.children,t),this.isDirty=!0}remove(t){pme(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(VHt),this.isDirty=!1,this.children.forEach(t)}}function GHt(s,t){const r=bx.now(),n=({timestamp:a})=>{const i=a-r;i>=t&&(RS(n),s(i-t))};return qc.setup(n,!0),()=>RS(n)}function Gue(s){return qf(s)?s.get():s}class WHt{constructor(){this.members=[]}add(t){ATe(this.members,t);for(let r=this.members.length-1;r>=0;r--){const n=this.members[r];if(n===t||n===this.lead||n===this.prevLead)continue;const a=n.instance;(!a||a.isConnected===!1)&&!n.snapshot&&(pme(this.members,n),n.unmount())}t.scheduleRender()}remove(t){if(pme(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const r=this.members[this.members.length-1];r&&this.promote(r)}}relegate(t){var r;for(let n=this.members.indexOf(t)-1;n>=0;n--){const a=this.members[n];if(a.isPresent!==!1&&((r=a.instance)==null?void 0:r.isConnected)!==!1)return this.promote(a),!0}return!1}promote(t,r){var a;const n=this.lead;if(t!==n&&(this.prevLead=n,this.lead=t,t.show(),n)){n.updateSnapshot(),t.scheduleRender();const{layoutDependency:i}=n.options,{layoutDependency:l}=t.options;(i===void 0||i!==l)&&(t.resumeFrom=n,r&&(n.preserveOpacity=!0),n.snapshot&&(t.snapshot=n.snapshot,t.snapshot.latestValues=n.animationValues||n.latestValues),(a=t.root)!=null&&a.isUpdating&&(t.isLayoutDirty=!0)),t.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(t=>{var r,n,a,i,l;(n=(r=t.options).onExitComplete)==null||n.call(r),(l=(a=t.resumingFrom)==null?void 0:(i=a.options).onExitComplete)==null||l.call(i)})}scheduleRender(){this.members.forEach(t=>t.instance&&t.scheduleRender(!1))}removeLeadSnapshot(){var t;(t=this.lead)!=null&&t.snapshot&&(this.lead.snapshot=void 0)}}const Wue={hasAnimatedSinceResize:!0,hasEverUpdated:!1},s_e=["","X","Y","Z"],KHt=1e3;let YHt=0;function r_e(s,t,r,n){const{latestValues:a}=t;a[s]&&(r[s]=a[s],t.setStaticValue(s,0),n&&(n[s]=0))}function Uot(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const r=cot(t);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(r,"transform",qc,!(a||i))}const{parent:n}=s;n&&!n.hasCheckedOptimisedAppear&&Uot(n)}function qot({attachResizeListener:s,defaultParent:t,measureScroll:r,checkIsScrollRoot:n,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=YHt++,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(QHt),this.nodes.forEach(nGt),this.nodes.forEach(aGt),this.nodes.forEach(JHt)},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;qc.read(()=>{m=window.innerWidth}),s(l,()=>{const x=window.innerWidth;x!==m&&(m=x,this.root.updateBlockedByResize=!0,u&&u(),u=GHt(f,250),Wue.hasAnimatedSinceResize&&(Wue.hasAnimatedSinceResize=!1,this.nodes.forEach(j9e)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:m,hasRelativeLayoutChanged:f,layout:x})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||d.getDefaultTransition()||dGt,{onLayoutAnimationStart:_,onLayoutAnimationComplete:b}=d.getProps(),j=!this.targetLayout||!zot(this.targetLayout,x),N=!m&&f;if(this.options.layoutRoot||this.resumeFrom||N||m&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const C={...$Te(y,"layout"),onPlay:_,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(C.delay=0,C.type=!1),this.startAnimation(C),this.setAnimationOrigin(u,N)}else m||j9e(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=x})}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(),RS(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(iGt),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&&Uot(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&&!_x(this.snapshot.measuredBox.x)&&!_x(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;N9e(m.x,l.x,E),N9e(m.y,l.y,E),this.setTargetDelta(m),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(wme(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),lGt(this.relativeTarget,this.relativeTargetOrigin,f,E),C&&OHt(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=nm()),Qv(C,this.relativeTarget)),_&&(this.animationValues=u,BHt(u,d,this.latestValues,E,N,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&&(RS(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=qc.update(()=>{Wue.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=pL(0)),this.motionValue.jump(0,!1),this.currentAnimation=qHt(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(KHt),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&&Vot(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||nm();const m=_x(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+m;const f=_x(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+f}Qv(o,c),Hue(o,u),x7(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new WHt),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&&r_e("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(_9e),this.root.sharedNodes.clear()}}}function ZHt(s){s.updateLayout()}function XHt(s){var r;const t=((r=s.resumeFrom)==null?void 0:r.snapshot)||s.snapshot;if(s.isLead()&&s.layout&&t&&s.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:a}=s.layout,{animationType:i}=s.options,l=t.source!==s.layout.source;if(i==="size")Hb(m=>{const f=l?t.measuredBox[m]:t.layoutBox[m],x=_x(f);f.min=n[m].min,f.max=f.min+x});else if(i==="x"||i==="y"){const m=i==="x"?"y":"x";Nke(l?t.measuredBox[m]:t.layoutBox[m],n[m])}else Vot(i,t.layoutBox,n)&&Hb(m=>{const f=l?t.measuredBox[m]:t.layoutBox[m],x=_x(n[m]);f.max=f.min+x,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[m].max=s.relativeTarget[m].min+x)});const o=jI();x7(o,n,t.layoutBox);const c=jI();l?x7(c,s.applyTransform(a,!0),t.measuredBox):x7(c,n,t.layoutBox);const d=!Fot(o);let u=!1;if(!s.resumeFrom){const m=s.getClosestProjectingParent();if(m&&!m.resumeFrom){const{snapshot:f,layout:x}=m;if(f&&x){const y=s.options.layoutAnchor||void 0,_=nm();wme(_,t.layoutBox,f.layoutBox,y);const b=nm();wme(b,n,x.layoutBox,y),zot(_,b)||(u=!0),m.options.layoutRoot&&(s.relativeTarget=b,s.relativeTargetOrigin=_,s.relativeParent=m)}}}s.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:u})}else if(s.isLead()){const{onExitComplete:n}=s.options;n&&n()}s.options.transition=void 0}function QHt(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 JHt(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function eGt(s){s.clearSnapshot()}function _9e(s){s.clearMeasurements()}function tGt(s){s.isLayoutDirty=!0,s.updateLayout()}function w9e(s){s.isLayoutDirty=!1}function sGt(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function rGt(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function j9e(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function nGt(s){s.resolveTargetDelta()}function aGt(s){s.calcProjection()}function iGt(s){s.resetSkewAndRotation()}function oGt(s){s.removeLeadSnapshot()}function N9e(s,t,r){s.translate=Nd(t.translate,0,r),s.scale=Nd(t.scale,1,r),s.origin=t.origin,s.originPoint=t.originPoint}function k9e(s,t,r,n){s.min=Nd(t.min,r.min,n),s.max=Nd(t.max,r.max,n)}function lGt(s,t,r,n){k9e(s.x,t.x,r.x,n),k9e(s.y,t.y,r.y,n)}function cGt(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const dGt={duration:.45,ease:[.4,0,.1,1]},S9e=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),C9e=S9e("applewebkit/")&&!S9e("chrome/")?Math.round:sv;function T9e(s){s.min=C9e(s.min),s.max=C9e(s.max)}function uGt(s){T9e(s.x),T9e(s.y)}function Vot(s,t,r){return s==="position"||s==="preserve-aspect"&&!IHt(x9e(t),x9e(r),.2)}function hGt(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const mGt=qot({attachResizeListener:(s,t)=>L9(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}),n_e={current:void 0},Hot=qot({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!n_e.current){const s=new mGt({});s.mount(window),s.setOptions({layoutScroll:!0}),n_e.current=s}return n_e.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),eEe=k.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function E9e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function fGt(...s){return t=>{let r=!1;const n=s.map(a=>{const i=E9e(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a{const{width:x,height:y,top:_,left:b,right:j,bottom:N}=c.current;if(t||i===!1||!o.current||!x||!y)return;const C=r==="left"?`left: ${b}`:`right: ${j}`,A=n==="bottom"?`bottom: ${N}`:`top: ${_}`;o.current.dataset.motionPopId=l;const E=document.createElement("style");d&&(E.nonce=d);const D=a??document.head;return D.appendChild(E),E.sheet&&E.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${x}px !important; height: ${y}px !important; ${C}px !important; ${A}px !important; } `),()=>{var R;(R=o.current)==null||R.removeAttribute("data-motion-pop-id"),D.contains(E)&&D.removeChild(E)}},[t]),e.jsx(xGt,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:k.cloneElement(s,{ref:m})})}const yGt=({children:s,initial:t,isPresent:r,onExitComplete:n,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=ETe(vGt),m=k.useId();let f=!0,x=k.useMemo(()=>(f=!1,{id:m,initial:t,isPresent:r,custom:a,onExitComplete:y=>{u.set(y,!0);for(const _ of u.values())if(!_)return;n&&n()},register:y=>(u.set(y,!1),()=>u.delete(y))}),[r,u,n]);return i&&f&&(x={...x}),k.useMemo(()=>{u.forEach((y,_)=>u.set(_,!1))},[r]),k.useEffect(()=>{!r&&!u.size&&n&&n()},[r]),s=e.jsx(gGt,{pop:l==="popLayout",isPresent:r,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(yge.Provider,{value:x,children:s})};function vGt(){return new Map}function Got(s=!0){const t=k.useContext(yge);if(t===null)return[!0,null];const{isPresent:r,onExitComplete:n,register:a}=t,i=k.useId();k.useEffect(()=>{if(s)return a(i)},[s]);const l=k.useCallback(()=>s&&n&&n(i),[i,n,s]);return!r&&n?[!1,l]:[!0]}const gq=s=>s.key||"";function A9e(s){const t=[];return k.Children.forEach(s,r=>{k.isValidElement(r)&&t.push(r)}),t}const tEe=({children:s,custom:t,initial:r=!0,onExitComplete:n,presenceAffectsLayout:a=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",anchorY:c="top",root:d})=>{const[u,m]=Got(l),f=k.useMemo(()=>A9e(s),[s]),x=l&&!u?[]:f.map(gq),y=k.useRef(!0),_=k.useRef(f),b=ETe(()=>new Map),j=k.useRef(new Set),[N,C]=k.useState(f),[A,E]=k.useState(f);bit(()=>{y.current=!1,_.current=f;for(let F=0;F{const O=gq(F),B=l&&!u?!1:f===A||x.includes(O),K=()=>{if(j.current.has(O))return;if(b.has(O))j.current.add(O),b.set(O,!0);else return;let Z=!0;b.forEach(Q=>{Q||(Z=!1)}),Z&&(R==null||R(),E(_.current),l&&(m==null||m()),n&&n())};return e.jsx(yGt,{isPresent:B,initial:!y.current||r?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:B?void 0:K,anchorX:o,anchorY:c,children:F},O)})})},Wot=k.createContext({strict:!1}),M9e={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 I9e=!1;function bGt(){if(I9e)return;const s={};for(const t in M9e)s[t]={isEnabled:r=>M9e[t].some(n=>!!r[n])};wot(s),I9e=!0}function Kot(){return bGt(),nHt()}function _Gt(s){const t=Kot();for(const r in s)t[r]={...t[r],...s[r]};wot(t)}const wGt=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 jme(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||wGt.has(s)}let Yot=s=>!jme(s);function jGt(s){typeof s=="function"&&(Yot=t=>t.startsWith("on")?!jme(t):s(t))}try{jGt(require("@emotion/is-prop-valid").default)}catch{}function NGt(s,t,r){const n={};for(const a in s)a==="values"&&typeof s.values=="object"||qf(s[a])||(Yot(a)||r===!0&&jme(a)||!t&&!jme(a)||s.draggable&&a.startsWith("onDrag"))&&(n[a]=s[a]);return n}const jge=k.createContext({});function kGt(s,t){if(wge(s)){const{initial:r,animate:n}=s;return{initial:r===!1||P9(r)?r:void 0,animate:P9(n)?n:void 0}}return s.inherit!==!1?t:{}}function SGt(s){const{initial:t,animate:r}=kGt(s,k.useContext(jge));return k.useMemo(()=>({initial:t,animate:r}),[P9e(t),P9e(r)])}function P9e(s){return Array.isArray(s)?s.join(" "):s}const sEe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Zot(s,t,r){for(const n in t)!qf(t[n])&&!Eot(n,r)&&(s[n]=t[n])}function CGt({transformTemplate:s},t){return k.useMemo(()=>{const r=sEe();return QTe(r,t,s),Object.assign({},r.vars,r.style)},[t])}function TGt(s,t){const r=s.style||{},n={};return Zot(n,r,s),Object.assign(n,CGt(s,t)),n}function EGt(s,t){const r={},n=TGt(s,t);return s.drag&&s.dragListener!==!1&&(r.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=s.drag===!0?"none":`pan-${s.drag==="x"?"y":"x"}`),s.tabIndex===void 0&&(s.onTap||s.onTapStart||s.whileTap)&&(r.tabIndex=0),r.style=n,r}const Xot=()=>({...sEe(),attrs:{}});function AGt(s,t,r,n){const a=k.useMemo(()=>{const i=Xot();return Aot(i,t,Iot(n),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};Zot(i,s.style,s),a.style={...i,...a.style}}return a}const MGt=["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 rEe(s){return typeof s!="string"||s.includes("-")?!1:!!(MGt.indexOf(s)>-1||/[A-Z]/u.test(s))}function IGt(s,t,r,{latestValues:n},a,i=!1,l){const c=(l??rEe(s)?AGt:EGt)(t,n,a,s),d=NGt(t,typeof s=="string",i),u=s!==k.Fragment?{...d,...c,ref:r}:{},{children:m}=t,f=k.useMemo(()=>qf(m)?m.get():m,[m]);return k.createElement(s,{...u,children:f})}function PGt({scrapeMotionValuesFromProps:s,createRenderState:t},r,n,a){return{latestValues:LGt(r,n,a,s),renderState:t()}}function LGt(s,t,r,n){const a={},i=n(s,{});for(const f in i)a[f]=Gue(i[f]);let{initial:l,animate:o}=s;const c=wge(s),d=bot(s);t&&d&&!c&&s.inherit!==!1&&(l===void 0&&(l=t.initial),o===void 0&&(o=t.animate));let u=r?r.initial===!1:!1;u=u||l===!1;const m=u?o:l;if(m&&typeof m!="boolean"&&!_ge(m)){const f=Array.isArray(m)?m:[m];for(let x=0;x(t,r)=>{const n=k.useContext(jge),a=k.useContext(yge),i=()=>PGt(s,t,n,a);return r?i():ETe(i)},DGt=Qot({scrapeMotionValuesFromProps:JTe,createRenderState:sEe}),RGt=Qot({scrapeMotionValuesFromProps:Pot,createRenderState:Xot}),OGt=Symbol.for("motionComponentSymbol");function FGt(s,t,r){const n=k.useRef(r);k.useInsertionEffect(()=>{n.current=r});const a=k.useRef(null);return k.useCallback(i=>{var o;i&&((o=s.onMount)==null||o.call(s,i));const l=n.current;if(typeof l=="function")if(i){const c=l(i);typeof c=="function"&&(a.current=c)}else a.current?(a.current(),a.current=null):l(i);else l&&(l.current=i);t&&(i?t.mount(i):t.unmount())},[t])}const Jot=k.createContext({});function Q6(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function zGt(s,t,r,n,a,i){var C,A;const{visualElement:l}=k.useContext(jge),o=k.useContext(Wot),c=k.useContext(yge),d=k.useContext(eEe),u=d.reducedMotion,m=d.skipAnimations,f=k.useRef(null),x=k.useRef(!1);n=n||o.renderer,!f.current&&n&&(f.current=n(s,{visualState:t,parent:l,props:r,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:m,isSVG:i}),x.current&&f.current&&(f.current.manuallyAnimateOnMount=!0));const y=f.current,_=k.useContext(Jot);y&&!y.projection&&a&&(y.type==="html"||y.type==="svg")&&BGt(f.current,r,a,_);const b=k.useRef(!1);k.useInsertionEffect(()=>{y&&b.current&&y.update(r,c)});const j=r[lot],N=k.useRef(!!j&&typeof window<"u"&&!((C=window.MotionHandoffIsComplete)!=null&&C.call(window,j))&&((A=window.MotionHasOptimisedAnimation)==null?void 0:A.call(window,j)));return bit(()=>{x.current=!0,y&&(b.current=!0,window.MotionIsMounted=!0,y.updateFeatures(),y.scheduleRenderMicrotask(),N.current&&y.animationState&&y.animationState.animateChanges())}),k.useEffect(()=>{y&&(!N.current&&y.animationState&&y.animationState.animateChanges(),N.current&&(queueMicrotask(()=>{var E;(E=window.MotionHandoffMarkAsComplete)==null||E.call(window,j)}),N.current=!1),y.enteringChildren=void 0)}),y}function BGt(s,t,r,n){const{layoutId:a,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutAnchor:u,layoutCrossfade:m}=t;s.projection=new r(s.latestValues,t["data-framer-portal-id"]?void 0:elt(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&Q6(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:n,crossfade:m,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function elt(s){if(s)return s.options.allowProjection!==!1?s.projection:elt(s.parent)}function a_e(s,{forwardMotionProps:t=!1,type:r}={},n,a){n&&_Gt(n);const i=r?r==="svg":rEe(s),l=i?RGt:DGt;function o(d,u){let m;const f={...k.useContext(eEe),...d,layoutId:$Gt(d)},{isStatic:x}=f,y=SGt(d),_=l(d,x);if(!x&&typeof window<"u"){UGt();const b=qGt(f);m=b.MeasureLayout,y.visualElement=zGt(s,_,f,a,b.ProjectionNode,i)}return e.jsxs(jge.Provider,{value:y,children:[m&&y.visualElement?e.jsx(m,{visualElement:y.visualElement,...f}):null,IGt(s,d,FGt(_,y.visualElement,u),_,x,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=k.forwardRef(o);return c[OGt]=s,c}function $Gt({layoutId:s}){const t=k.useContext(TTe).id;return t&&s!==void 0?t+"-"+s:s}function UGt(s,t){k.useContext(Wot).strict}function qGt(s){const t=Kot(),{drag:r,layout:n}=t;if(!r&&!n)return{};const a={...r,...n};return{MeasureLayout:r!=null&&r.isEnabled(s)||n!=null&&n.isEnabled(s)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}function VGt(s,t){if(typeof Proxy>"u")return a_e;const r=new Map,n=(i,l)=>a_e(i,l,s,t),a=(i,l)=>n(i,l);return new Proxy(a,{get:(i,l)=>l==="create"?n:(r.has(l)||r.set(l,a_e(l,void 0,s,t)),r.get(l))})}const HGt=(s,t)=>t.isSVG??rEe(s)?new _Ht(t):new pHt(t,{allowProjection:s!==k.Fragment});class GGt extends r4{constructor(t){super(t),t.animationState||(t.animationState=SHt(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();_ge(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:r}=this.node.prevProps||{};t!==r&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let WGt=0;class KGt extends r4{constructor(){super(...arguments),this.id=WGt++,this.isExitComplete=!1}update(){var i;if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:r}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===n)return;if(t&&n===!1){if(this.isExitComplete){const{initial:l,custom:o}=this.node.getProps();if(typeof l=="string"){const c=YE(this.node,l,o);if(c){const{transition:d,transitionEnd:u,...m}=c;for(const f in m)(i=this.node.getValue(f))==null||i.jump(m[f])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const a=this.node.animationState.setActive("exit",!t);r&&!t&&a.then(()=>{this.isExitComplete=!0,r(this.id)})}mount(){const{register:t,onExitComplete:r}=this.node.presenceContext||{};r&&r(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const YGt={animation:{Feature:GGt},exit:{Feature:KGt}};function NB(s){return{point:{x:s.pageX,y:s.pageY}}}const ZGt=s=>t=>KTe(t)&&s(t,NB(t));function g7(s,t,r,n){return L9(s,t,ZGt(r),n)}const tlt=({current:s})=>s?s.ownerDocument.defaultView:null,L9e=(s,t)=>Math.abs(s-t);function XGt(s,t){const r=L9e(s.x,t.x),n=L9e(s.y,t.y);return Math.sqrt(r**2+n**2)}const D9e=new Set(["auto","scroll"]);class slt{constructor(t,r,{transformPagePoint:n,contextWindow:a=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=x=>{this.handleScroll(x.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=yq(this.lastRawMoveEventInfo,this.transformPagePoint));const x=i_e(this.lastMoveEventInfo,this.history),y=this.startEvent!==null,_=XGt(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!y&&!_)return;const{point:b}=x,{timestamp:j}=Df;this.history.push({...b,timestamp:j});const{onStart:N,onMove:C}=this.handlers;y||(N&&N(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,x)},this.handlePointerMove=(x,y)=>{this.lastMoveEvent=x,this.lastRawMoveEventInfo=y,this.lastMoveEventInfo=yq(y,this.transformPagePoint),qc.update(this.updatePoint,!0)},this.handlePointerUp=(x,y)=>{this.end();const{onEnd:_,onSessionEnd:b,resumeAnimation:j}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const N=i_e(x.type==="pointercancel"?this.lastMoveEventInfo:yq(y,this.transformPagePoint),this.history);this.startEvent&&_&&_(x,N),b&&b(x,N)},!KTe(t))return;this.dragSnapToOrigin=i,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=l,this.contextWindow=a||window;const c=NB(t),d=yq(c,this.transformPagePoint),{point:u}=d,{timestamp:m}=Df;this.history=[{...u,timestamp:m}];const{onSessionStart:f}=r;f&&f(t,i_e(d,this.history)),this.removeListeners=_B(g7(this.contextWindow,"pointermove",this.handlePointerMove),g7(this.contextWindow,"pointerup",this.handlePointerUp),g7(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let r=t.parentElement;for(;r;){const n=getComputedStyle(r);(D9e.has(n.overflowX)||D9e.has(n.overflowY))&&this.scrollPositions.set(r,{x:r.scrollLeft,y:r.scrollTop}),r=r.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const r=this.scrollPositions.get(t);if(!r)return;const n=t===window,a=n?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:a.x-r.x,y:a.y-r.y};i.x===0&&i.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(t,a),qc.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),RS(this.updatePoint)}}function yq(s,t){return t?{point:t(s.point)}:s}function R9e(s,t){return{x:s.x-t.x,y:s.y-t.y}}function i_e({point:s},t){return{point:s,delta:R9e(s,rlt(t)),offset:R9e(s,QGt(t)),velocity:JGt(t,.1)}}function QGt(s){return s[0]}function rlt(s){return s[s.length-1]}function JGt(s,t){if(s.length<2)return{x:0,y:0};let r=s.length-1,n=null;const a=rlt(s);for(;r>=0&&(n=s[r],!(a.timestamp-n.timestamp>vg(t)));)r--;if(!n)return{x:0,y:0};n===s[0]&&s.length>2&&a.timestamp-n.timestamp>vg(t)*2&&(n=s[1]);const i=Gy(a.timestamp-n.timestamp);if(i===0)return{x:0,y:0};const l={x:(a.x-n.x)/i,y:(a.y-n.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function eWt(s,{min:t,max:r},n){return t!==void 0&&sr&&(s=n?Nd(r,s,n.max):Math.min(s,r)),s}function O9e(s,t,r){return{min:t!==void 0?s.min+t:void 0,max:r!==void 0?s.max+r-(s.max-s.min):void 0}}function tWt(s,{top:t,left:r,bottom:n,right:a}){return{x:O9e(s.x,r,a),y:O9e(s.y,t,n)}}function F9e(s,t){let r=t.min-s.min,n=t.max-s.max;return t.max-t.minn?r=M9(t.min,t.max-n,s.min):n>a&&(r=M9(s.min,s.max-a,t.min)),$_(0,1,r)}function nWt(s,t){const r={};return t.min!==void 0&&(r.min=t.min-s.min),t.max!==void 0&&(r.max=t.max-s.min),r}const kke=.35;function aWt(s=kke){return s===!1?s=0:s===!0&&(s=kke),{x:z9e(s,"left","right"),y:z9e(s,"top","bottom")}}function z9e(s,t,r){return{min:B9e(s,t),max:B9e(s,r)}}function B9e(s,t){return typeof s=="number"?s:s[t]||0}const iWt=new WeakMap;class oWt{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=nm(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:r=!1,distanceThreshold:n}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const i=m=>{r&&this.snapToCursor(NB(m).point),this.stopAnimation()},l=(m,f)=>{const{drag:x,dragPropagation:y,onDragStart:_}=this.getProps();if(x&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=LVt(x),!this.openDragLock))return;this.latestPointerEvent=m,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Hb(j=>{let N=this.getAxisMotionValue(j).get()||0;if(I_.test(N)){const{projection:C}=this.visualElement;if(C&&C.layout){const A=C.layout.layoutBox[j];A&&(N=_x(A)*(parseFloat(N)/100))}}this.originPoint[j]=N}),_&&qc.update(()=>_(m,f),!1,!0),xke(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(m,f)=>{this.latestPointerEvent=m,this.latestPanInfo=f;const{dragPropagation:x,dragDirectionLock:y,onDirectionLock:_,onDrag:b}=this.getProps();if(!x&&!this.openDragLock)return;const{offset:j}=f;if(y&&this.currentDirection===null){this.currentDirection=cWt(j),this.currentDirection!==null&&_&&_(this.currentDirection);return}this.updateAxis("x",f.point,j),this.updateAxis("y",f.point,j),this.visualElement.render(),b&&qc.update(()=>b(m,f),!1,!0)},c=(m,f)=>{this.latestPointerEvent=m,this.latestPanInfo=f,this.stop(m,f),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:m}=this.getProps();(m||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new slt(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:tlt(this.visualElement),element:this.visualElement.current})}stop(t,r){const n=t||this.latestPointerEvent,a=r||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!a||!n)return;const{velocity:l}=a;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&qc.postRender(()=>o(n,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:r}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),r&&r.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,r,n){const{drag:a}=this.getProps();if(!n||!vq(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+n[t];this.constraints&&this.constraints[t]&&(l=eWt(l,this.constraints[t],this.elastic[t])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:t,dragElastic:r}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,a=this.constraints;t&&Q6(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&n?this.constraints=tWt(n.layoutBox,t):this.constraints=!1,this.elastic=aWt(r),a!==this.constraints&&!Q6(t)&&n&&this.constraints&&!this.hasMutatedConstraints&&Hb(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=nWt(n.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:r}=this.getProps();if(!t||!Q6(t))return!1;const n=t.current;mL(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:a}=this.visualElement;if(!a||!a.layout)return!1;const i=cHt(n,a.root,this.visualElement.getTransformPagePoint());let l=sWt(a.layout.layoutBox,i);if(r){const o=r(iHt(l));this.hasMutatedConstraints=!!o,o&&(l=Not(o))}return l}startAnimation(t){const{drag:r,dragMomentum:n,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=Hb(u=>{if(!vq(u,r,this.currentDirection))return;let m=c&&c[u]||{};(l===!0||l===u)&&(m={min:0,max:0});const f=a?200:1e6,x=a?40:1e7,y={type:"inertia",velocity:n?t[u]:0,bounceStiffness:f,bounceDamping:x,timeConstant:750,restDelta:1,restSpeed:10,...i,...m};return this.startAxisValueAnimation(u,y)});return Promise.all(d).then(o)}startAxisValueAnimation(t,r){const n=this.getAxisMotionValue(t);return xke(this.visualElement,t),n.start(UTe(t,n,0,r,this.visualElement,!1))}stopAnimation(){Hb(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const r=`_drag${t.toUpperCase()}`,n=this.visualElement.getProps(),a=n[r];return a||this.visualElement.getValue(t,(n.initial?n.initial[t]:void 0)||0)}snapToCursor(t){Hb(r=>{const{drag:n}=this.getProps();if(!vq(r,n,this.currentDirection))return;const{projection:a}=this.visualElement,i=this.getAxisMotionValue(r);if(a&&a.layout){const{min:l,max:o}=a.layout.layoutBox[r],c=i.get()||0;i.set(t[r]-Nd(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!Q6(r)||!n||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};Hb(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=rWt({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),Hb(l=>{if(!vq(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Nd(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;iWt.set(this.visualElement,this);const t=this.visualElement.current,r=g7(t,"pointerdown",d=>{const{drag:u,dragListener:m=!0}=this.getProps(),f=d.target,x=f!==t&&BVt(f);u&&m&&!x&&this.start(d)});let n;const a=()=>{const{dragConstraints:d}=this.getProps();Q6(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),n||(n=lWt(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),qc.read(a);const o=L9(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(Hb(m=>{const f=this.getAxisMotionValue(m);f&&(this.originPoint[m]+=d[m].translate,f.set(f.get()+d[m].translate))}),this.visualElement.render())});return()=>{o(),r(),l(),c&&c(),n&&n()}}getProps(){const t=this.visualElement.getProps(),{drag:r=!1,dragDirectionLock:n=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=kke,dragMomentum:o=!0}=t;return{...t,drag:r,dragDirectionLock:n,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function $9e(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function lWt(s,t,r){const n=K7e(s,$9e(r)),a=K7e(t,$9e(r));return()=>{n(),a()}}function vq(s,t,r){return(t===!0||t===s)&&(r===null||r===s)}function cWt(s,t=10){let r=null;return Math.abs(s.y)>t?r="y":Math.abs(s.x)>t&&(r="x"),r}class dWt extends r4{constructor(t){super(t),this.removeGroupControls=sv,this.removeListeners=sv,this.controls=new oWt(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||sv}update(){const{dragControls:t}=this.node.getProps(),{dragControls:r}=this.node.prevProps||{};t!==r&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const o_e=s=>(t,r)=>{s&&qc.update(()=>s(t,r),!1,!0)};class uWt extends r4{constructor(){super(...arguments),this.removePointerDownListener=sv}onPointerDown(t){this.session=new slt(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:tlt(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:r,onPan:n,onPanEnd:a}=this.node.getProps();return{onSessionStart:o_e(t),onStart:o_e(r),onMove:o_e(n),onEnd:(i,l)=>{delete this.session,a&&qc.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=g7(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 l_e=!1;class hWt extends k.Component{componentDidMount(){const{visualElement:t,layoutGroup:r,switchLayoutGroup:n,layoutId:a}=this.props,{projection:i}=t;i&&(r.group&&r.group.add(i),n&&n.register&&a&&n.register(i),l_e&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Wue.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:r,visualElement:n,drag:a,isPresent:i}=this.props,{projection:l}=n;return l&&(l.isPresent=i,t.layoutDependency!==r&&l.setOptions({...l.options,layoutDependency:r}),l_e=!0,a||t.layoutDependency!==r||r===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||qc.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:r}=this.props,{projection:n}=t;n&&(n.options.layoutAnchor=r,n.root.didUpdate(),WTe.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:a}=t;l_e=!0,a&&(a.scheduleCheckAfterUnmount(),r&&r.group&&r.group.remove(a),n&&n.deregister&&n.deregister(a))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function nlt(s){const[t,r]=Got(),n=k.useContext(TTe);return e.jsx(hWt,{...s,layoutGroup:n,switchLayoutGroup:k.useContext(Jot),isPresent:t,safeToRemove:r})}const mWt={pan:{Feature:uWt},drag:{Feature:dWt,ProjectionNode:Hot,MeasureLayout:nlt}};function U9e(s,t,r){const{props:n}=s;s.animationState&&n.whileHover&&s.animationState.setActive("whileHover",r==="Start");const a="onHover"+r,i=n[a];i&&qc.postRender(()=>i(t,NB(t)))}class fWt extends r4{mount(){const{current:t}=this.node;t&&(this.unmount=RVt(t,(r,n)=>(U9e(this.node,n,"Start"),a=>U9e(this.node,a,"End"))))}unmount(){}}class pWt extends r4{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=_B(L9(this.node.current,"focus",()=>this.onFocus()),L9(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function q9e(s,t,r){const{props:n}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&n.whileTap&&s.animationState.setActive("whileTap",r==="Start");const a="onTap"+(r==="End"?"":r),i=n[a];i&&qc.postRender(()=>i(t,NB(t)))}class xWt extends r4{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=UVt(t,(a,i)=>(q9e(this.node,i,"Start"),(l,{success:o})=>q9e(this.node,l,o?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const Ske=new WeakMap,c_e=new WeakMap,gWt=s=>{const t=Ske.get(s.target);t&&t(s)},yWt=s=>{s.forEach(gWt)};function vWt({root:s,...t}){const r=s||document;c_e.has(r)||c_e.set(r,{});const n=c_e.get(r),a=JSON.stringify(t);return n[a]||(n[a]=new IntersectionObserver(yWt,{root:s,...t})),n[a]}function bWt(s,t,r){const n=vWt(t);return Ske.set(s,r),n.observe(s),()=>{Ske.delete(s),n.unobserve(s)}}const _Wt={some:0,all:1};class wWt extends r4{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var c;(c=this.stopObserver)==null||c.call(this);const{viewport:t={}}=this.node.getProps(),{root:r,margin:n,amount:a="some",once:i}=t,l={root:r?r.current:void 0,rootMargin:n,threshold:typeof a=="number"?a:_Wt[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:m,onViewportLeave:f}=this.node.getProps(),x=u?m:f;x&&x(d)};this.stopObserver=bWt(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:r}=this.node;["amount","margin","root"].some(jWt(t,r))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function jWt({viewport:s={}},{viewport:t={}}={}){return r=>s[r]!==t[r]}const NWt={inView:{Feature:wWt},tap:{Feature:xWt},focus:{Feature:pWt},hover:{Feature:fWt}},kWt={layout:{ProjectionNode:Hot,MeasureLayout:nlt}},SWt={...YGt,...NWt,...mWt,...kWt},Zr=VGt(SWt,HGt),CWt={some:0,all:1};function TWt(s,t,{root:r,margin:n,amount:a="some"}={}){const i=GTe(s),l=new WeakMap,o=d=>{d.forEach(u=>{const m=l.get(u.target);if(u.isIntersecting!==!!m)if(u.isIntersecting){const f=t(u.target,u);typeof f=="function"?l.set(u.target,f):c.unobserve(u.target)}else typeof m=="function"&&(m(u),l.delete(u.target))})},c=new IntersectionObserver(o,{root:r,rootMargin:n,threshold:typeof a=="number"?a:CWt[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function EWt(s,{root:t,margin:r,amount:n,once:a=!1,initial:i=!1}={}){const[l,o]=k.useState(i);return k.useEffect(()=>{if(!s.current||a&&l)return;const c=()=>(o(!0),a?void 0:()=>o(!1)),d={root:t&&t.current||void 0,margin:r,amount:n};return TWt(s.current,c,d)},[t,s,r,a,n]),l}function AWt(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 V9e(s){return s.visitor_intent==="buying"&&!s.has_agent}function MWt({token:s}={}){var y;const t=xo(),r=s||t.token,{data:n,isLoading:a,isError:i}=pUt(r),l=is(),o=(y=n==null?void 0:n.open_houses)==null?void 0:y.id,{data:c}=pt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:_,error:b}=await U.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(b)throw b;return _},enabled:!!o});if(k.useEffect(()=>{if(!o)return;const _=U.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{U.removeChannel(_)}},[o,l]),a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:e.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(i||!n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),e.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const d=n.open_houses,u=(c==null?void 0:c.length)||0,m=(c==null?void 0:c.filter(_=>_.visitor_intent==="buying").length)||0,f=(c==null?void 0:c.filter(V9e).length)||0,x=_=>{if(!_)return"";const[b,j]=_.split(":"),N=parseInt(b);return`${N>12?N-12:N||12}:${j} ${N>=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(Dr,{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(ld,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:f})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:m})]})]})]}),e.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[e.jsx("span",{children:As(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[x(d.start_time),d.end_time?` – ${x(d.end_time)}`:""]})]}),e.jsx(ui,{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(tEe,{children:c.map((_,b)=>{var C;const j=AWt(_.visitor_intent),N=V9e(_);return e.jsxs(Zr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:b*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${N?"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 ${N?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(C=_.first_name[0])==null?void 0:C.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||""]}),N&&e.jsx(Xe,{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(Xe,{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(Xe,{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:As(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(h2,{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 IWt(){const t=vc().pathname.slice(1);if(k.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const r=t.slice(5);if(r)return e.jsx(MWt,{token:r})}return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Guest Book"}),e.jsx("p",{className:"text-white/60",children:"The modern open house sign-in experience."}),e.jsx("p",{className:"text-white/40 text-sm mt-2",children:"Visit a specific open house link to sign in."})]})}):e.jsx(iit,{slug:t})}const PWt="#2a4c64",LWt="#406E71";function DWt({dealData:s,agentProfile:t,welcomeMessage:r,isWon:n,branding:a}){var y;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.brand_color)||PWt,o=(a==null?void 0:a.accent_color)||LWt,c=(a==null?void 0:a.logo_url)||null,d=(a==null?void 0:a.cover_photo_url)||null,u=(a==null?void 0:a.tagline)||"Your Real Estate Agent",m=d?{backgroundImage:`linear-gradient(135deg, ${l}d9 0%, ${l}b3 50%, ${o}d9 100%), url(${d})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:`linear-gradient(135deg, ${l} 0%, ${l} 30%, ${o} 100%)`},f="flex items-center gap-2 px-4 py-2.5 rounded-xl transition-colors",x={backgroundColor:`${l}1a`,color:l};return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative text-white px-4 pt-10 pb-16",style:m,children:[!d&&e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[c&&e.jsx("div",{className:"mb-4 flex justify-center",children:e.jsx("div",{className:"bg-white/95 backdrop-blur-sm rounded-2xl px-4 py-2.5 shadow-lg",children:e.jsx("img",{src:c,alt:"Brand logo",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs("div",{className:"mb-6",children:[t.avatar_url?e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-20 h-20 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):e.jsx("div",{className:"w-20 h-20 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:e.jsx("span",{className:"text-2xl font-bold text-white/70",children:((y=t.name)==null?void 0:y.charAt(0))||"?"})}),e.jsx("p",{className:"text-sm font-medium text-white/95",children:t.name}),e.jsx("p",{className:"text-xs text-white/60 mt-0.5",children:u})]}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/10 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/80 mb-3",children:[e.jsx(Pn,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Listing":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1.5 font-serif",children:(s==null?void 0:s.deal_name)||"Your Transaction Portal"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-white/70 text-sm",children:[e.jsx(Ma,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:i})]}),r&&e.jsx("p",{className:"mt-4 text-sm text-white/80 leading-relaxed max-w-sm mx-auto",children:r})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-8 relative z-10",children:e.jsx("div",{className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-4",children:e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:f,style:x,children:[e.jsx(Mn,{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:f,style:x,children:[e.jsx(Ks,{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:f,style:x,children:[e.jsx(gc,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function alt({targetCloseDate:s,actualCloseDate:t,clientName:r}){if(t||!s)return null;const n=s.split(/[-/T]/),a=new Date(Number(n[0]),Number(n[1])-1,Number(n[2])),i=new Date,l=lv(a,i);if(QRt(a,i),M_(a)&&!um(a))return null;let o="from-blue-500 to-cyan-400",c="from-blue-50 to-cyan-50",d="text-blue-900",u="text-blue-600",m="🏡";l<=3?(o="from-emerald-500 to-teal-400",c="from-emerald-50 to-teal-50",d="text-emerald-900",u="text-emerald-600",m="🎉"):l<=7?(o="from-amber-500 to-orange-400",c="from-amber-50 to-orange-50",d="text-amber-900",u="text-amber-600",m="⏳"):l<=14&&(o="from-violet-500 to-purple-400",c="from-violet-50 to-purple-50",d="text-violet-900",u="text-violet-600",m="📅");const f=um(a)?"Today!":l===1?"1":String(l),x=um(a)?"Closing Day":l===1?"day until closing":"days until closing";return e.jsxs("div",{className:`bg-gradient-to-br ${c} rounded-2xl p-6 border border-white/60 shadow-sm text-center`,children:[e.jsx("span",{className:"text-3xl mb-2 block",children:m}),um(a)?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:`text-2xl font-bold ${d}`,children:"It's Closing Day!"}),e.jsxs("p",{className:`text-sm ${u} mt-1`,children:["Congratulations",r?`, ${r.split(" ")[0]}`:"","! 🎊"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-baseline justify-center gap-1.5",children:e.jsx("span",{className:`text-5xl font-bold ${d} tabular-nums leading-none`,children:f})}),e.jsx("p",{className:`text-sm font-medium ${u} mt-1.5`,children:x}),l<=7&&e.jsxs("p",{className:`text-xs ${u} opacity-70 mt-1`,children:["You're almost there",r?`, ${r.split(" ")[0]}`:"","!"]})]}),!um(a)&&l<=30&&e.jsx("div",{className:"mt-4 mx-auto w-full max-w-[200px]",children:e.jsx("div",{className:"h-2 rounded-full bg-white/60 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full bg-gradient-to-r ${o} transition-all duration-1000`,style:{width:`${Math.max(5,Math.min(100,(30-l)/30*100))}%`}})})})]})}function ilt({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800 mb-1",children:"Your Home Journey"}),e.jsx("p",{className:"text-xs text-slate-400 mb-5",children:"Follow along as your transaction progresses"}),e.jsx("div",{className:"relative",children:s.map((r,n)=>{const a=nt;return e.jsxs("div",{className:"flex items-start gap-3.5 relative",children:[n{var l,o;if(i.includes("youtube.com/watch")){const c=new URL(i).searchParams.get("v");return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("youtu.be/")){const c=(l=i.split("youtu.be/")[1])==null?void 0:l.split("?")[0];return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("loom.com/share/")){const c=(o=i.split("loom.com/share/")[1])==null?void 0:o.split("?")[0];return c?`https://www.loom.com/embed/${c}`:null}return i};return e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71]/5 via-white to-[#406E71]/5 rounded-2xl border border-[#406E71]/15 overflow-hidden",children:[e.jsx("div",{className:"bg-[#406E71] px-5 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ci,{className:"w-4 h-4 text-white/80"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Current Stage"})]})}),e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-lg font-bold text-slate-800",children:s.label}),e.jsx("p",{className:"text-sm text-slate-500 mt-1 leading-relaxed",children:s.description})]}),t&&e.jsxs("div",{className:"bg-slate-50 rounded-xl p-4 border border-slate-100",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5",children:"Update from your agent"}),e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:t})]}),r&&e.jsxs("div",{className:"bg-blue-50/60 rounded-xl p-4 border border-blue-100",children:[e.jsx("p",{className:"text-xs font-semibold text-blue-600 uppercase tracking-wider mb-1.5",children:"What's Next"}),e.jsx("p",{className:"text-sm text-blue-800 leading-relaxed",children:r})]}),n&&e.jsx("div",{className:"rounded-xl overflow-hidden bg-slate-900 aspect-video shadow-md",children:e.jsx("iframe",{src:a(n)||n,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})]})}function El(s){const t=s.split(/[-/T]/);if(t.length>=3){const r=Number(t[0]);return r>99?new Date(r,Number(t[1])-1,Number(t[2])):new Date(Number(t[2]),Number(t[0])-1,Number(t[1]))}return new Date(`${s}T12:00:00`)}function RWt(s,t){const r=As(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${r}/${r}`,details:"Added from your Client Portal"}).toString()}`}function OWt(s,t){const r=As(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${r} DTEND;VALUE=DATE:${r} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function llt({targetCloseDate:s,contractDate:t,inspectionDate:r,appraisalDate:n,actualCloseDate:a}){const i=[{label:"Contract Date",date:t,icon:VI,color:"text-blue-600 bg-blue-50"},{label:"Inspection",date:r,icon:_n,color:"text-amber-600 bg-amber-50"},{label:"Appraisal",date:n,icon:Pn,color:"text-purple-600 bg-purple-50"},{label:a?"Closed":"Target Close",date:a||s,icon:vn,color:"text-emerald-600 bg-emerald-50"}].filter(o=>o.date);if(i.length===0)return null;const l=(o,c,d)=>{const u=El(c);if(d==="google")window.open(RWt(o,u),"_blank");else{const m=OWt(o,u),f=document.createElement("a");f.href=m,f.download=`${o.replace(/\s+/g,"-").toLowerCase()}.ics`,f.click()}};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Key Dates"}),e.jsx("div",{className:"space-y-3",children:i.map(({label:o,date:c,icon:d,color:u})=>{const m=El(c),f=M_(m)&&!um(m),x=um(m),y=!f&&!x;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 ${u}`,children:e.jsx(d,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-slate-500",children:o}),e.jsxs("p",{className:`text-sm font-medium ${x?"text-emerald-600":f?"text-slate-400":"text-slate-800"}`,children:[As(m,"MMM d, yyyy"),x&&e.jsx("span",{className:"ml-1.5 text-xs bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded-full",children:"Today"})]})]}),f&&e.jsx("span",{className:"text-xs text-slate-400",children:"✓"}),y&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>l(o,c,"google"),className:"text-xs text-slate-400 hover:text-blue-500 transition-colors px-1.5 py-1 rounded hover:bg-blue-50",title:"Add to Google Calendar",children:e.jsx(Gj,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>l(o,c,"apple"),className:"text-[10px] text-slate-400 hover:text-slate-600 transition-colors px-1.5 py-1 rounded hover:bg-slate-100",title:"Download .ics file",children:".ics"})]})]},o)})})]})}function clt({documents:s}){const t=n=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,r=async n=>{const{data:a}=await U.storage.from("deal-files").createSignedUrl(n.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(n=>e.jsxs("button",{onClick:()=>r(n),className:"w-full flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors text-left group",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-100 flex items-center justify-center flex-shrink-0 group-hover:bg-blue-50 transition-colors",children:e.jsx(En,{className:"w-4 h-4 text-slate-500 group-hover:text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-slate-700 truncate",children:n.file_name}),e.jsx("p",{className:"text-xs text-slate-400",children:t(n.file_size)})]}),e.jsx(li,{className:"w-4 h-4 text-slate-300 group-hover:text-blue-500 transition-colors"})]},n.id))})]})}function dlt({updates:s}){const t=r=>{var n,a;if(r.includes("youtube.com/watch")){const i=new URL(r).searchParams.get("v");return i?`https://www.youtube.com/embed/${i}`:null}if(r.includes("youtu.be/")){const i=(n=r.split("youtu.be/")[1])==null?void 0:n.split("?")[0];return i?`https://www.youtube.com/embed/${i}`:null}if(r.includes("loom.com/share/")){const i=(a=r.split("loom.com/share/")[1])==null?void 0:a.split("?")[0];return i?`https://www.loom.com/embed/${i}`:null}return r};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-4",children:"Updates from Your Agent"}),e.jsx("div",{className:"space-y-4",children:s.map((r,n)=>e.jsx("div",{className:`${n>0?"pt-4 border-t border-slate-100":""}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0 ${r.is_stage_change?"bg-emerald-100":"bg-blue-100"}`,children:r.is_stage_change?e.jsx(Uu,{className:"w-3.5 h-3.5 text-emerald-600"}):e.jsx(ym,{className:"w-3.5 h-3.5 text-blue-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-slate-800",children:r.title}),e.jsx("span",{className:"text-xs text-slate-400 flex-shrink-0",children:As(new Date(r.created_at),"MMM d")})]}),r.content&&e.jsx("p",{className:"text-sm text-slate-500 mt-1 leading-relaxed",children:r.content}),r.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden bg-slate-900 aspect-video",children:e.jsx("iframe",{src:t(r.video_url)||r.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:r.title})})]})]})},r.id))})]})}const ke=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:zt("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));ke.displayName="Card";const Pt=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:zt("flex flex-col space-y-1.5 p-6",s),...t}));Pt.displayName="CardHeader";const Dt=k.forwardRef(({className:s,...t},r)=>e.jsx("h3",{ref:r,className:zt("text-2xl font-semibold leading-none tracking-tight",s),...t}));Dt.displayName="CardTitle";const Ur=k.forwardRef(({className:s,...t},r)=>e.jsx("p",{ref:r,className:zt("text-sm text-muted-foreground",s),...t}));Ur.displayName="CardDescription";const Pe=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:zt("p-6 pt-0",s),...t}));Pe.displayName="CardContent";const y7=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:zt("flex items-center p-6 pt-0",s),...t}));y7.displayName="CardFooter";const A8=[{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"}],FWt=[{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 zWt(s){return pt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s})}function BWt(){const s=xa(),{brokerageId:t}=Cs();return pt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let r=U.from("vendors").select("*");t?r=r.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):r=r.eq("owner_type","agent").eq("owner_user_id",s);const[{data:n,error:a},{data:i,error:l}]=await Promise.all([r.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),U.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:n||[],selections:i||[]}},enabled:!!s})}function $Wt(){const s=is();return Mt({mutationFn:async t=>{if(t.id){const{id:r,created_at:n,...a}=t,{data:i,error:l}=await U.from("vendors").update(a).eq("id",r).select().single();if(l)throw l;return i}else{const{data:r,error:n}=await U.from("vendors").insert(t).select().single();if(n)throw n;return r}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function ult(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("vendors").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function UWt(){const s=xa(),t=is();return Mt({mutationFn:async({vendorId:r,isVisible:n})=>{if(!s)throw new Error("No user");const{data:a}=await U.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",r).maybeSingle();if(a){const{error:i}=await U.from("agent_vendor_selections").update({is_visible:n}).eq("id",a.id);if(i)throw i}else{const{error:i}=await U.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:r,is_visible:n});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function hlt(s){return pt({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:r}=await U.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),n=r==null?void 0:r.brokerage_id,a=U.from("vendors").select("*").eq("is_active",!0),i=n?a.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${n})`):a.eq("owner_type","agent").eq("owner_user_id",t),[{data:l,error:o},{data:c},{data:d}]=await Promise.all([i.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),U.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),U.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(x=>u.set(x.vendor_id,{display_order:x.display_order,is_visible:x.is_visible}));const m=new Map;return(d||[]).forEach(x=>m.set(x.vendor_id,x.is_visible)),(l||[]).filter(x=>{if(m.get(x.id)===!1)return!1;const y=u.get(x.id);return!(y&&y.is_visible===!1&&!x.is_required)}).map(x=>{var y;return{...x,display_order:((y=u.get(x.id))==null?void 0:y.display_order)??x.sort_order??0}}).sort((x,y)=>(x.display_order||0)-(y.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function H9e(s){try{await U.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function mlt(s,t){return pt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:r}=await U.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),n=(r||[]).map(l=>l.id);if(n.length===0)return{};const{data:a}=await U.from("vendor_clicks").select("vendor_id").in("vendor_id",n),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function flt({portalId:s,ownerUserId:t,currentStage:r,brandingColor:n,layout:a="list"}){const{data:i=[],isLoading:l}=hlt({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(N=>!N.stage_filter||N.stage_filter.length===0||!r?!0:N.stage_filter.includes(r));if(o.length===0)return null;const c=n||"#406E71",d=(N,C)=>{switch(C){case"book":return N.booking_url;case"website":return N.website;case"call":return N.phone?`tel:${N.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return N.email?`mailto:${N.email}`:null}},u=N=>{const C=d(N,N.action_type);H9e({vendorId:N.id,portalId:s,agentUserId:t,actionTaken:N.action_type}),C&&window.open(C,N.action_type==="call"||N.action_type==="email"||N.action_type==="quote"?"_self":"_blank")},m=N=>{const C=d(N,N.action_type);return[{action:"website",label:"Website",icon:e.jsx(Ql,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(Ks,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(Mn,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(vn,{className:"w-3.5 h-3.5"})}].filter(E=>E.action!==N.action_type).map(E=>{const D=d(N,E.action);return!D||D===C?null:e.jsxs("button",{onClick:()=>{H9e({vendorId:N.id,portalId:s,agentUserId:t,actionTaken:E.action}),window.open(D,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)},f=N=>{switch(N.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"}},x=N=>{switch(N.action_type){case"book":return e.jsx(vn,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Mn,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(Ks,{className:"w-3.5 h-3.5"});case"website":return e.jsx(Ql,{className:"w-3.5 h-3.5"})}},y=N=>{var C;return((C=A8.find(A=>A.value===N))==null?void 0:C.label)||N},_=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(Ir,{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"})]})]}),b=o.some(N=>N.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(N=>N.disclosure_text).map(N=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[N.company||N.name,":"]})," ",N.disclosure_text]},N.id))});if(a==="grid")return e.jsxs(ke,{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(N=>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:N.logo_url?e.jsx("img",{src:N.logo_url,alt:N.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-base font-semibold text-slate-500",children:(N.company||N.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:N.company||N.name}),N.company&&N.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:N.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(N.category)})]})]}),N.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:N.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs(q,{size:"sm",onClick:()=>u(N),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[x(N),e.jsx("span",{className:"ml-1.5 text-xs",children:f(N)})]}),m(N).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:m(N)})]})]},N.id))}),b]});const j=o.reduce((N,C)=>((N[C.category]=N[C.category]||[]).push(C),N),{});return e.jsxs(ke,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[_,e.jsx("div",{className:"space-y-4",children:Object.entries(j).map(([N,C])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:y(N)}),e.jsx("div",{className:"space-y-2",children:C.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(q,{size:"sm",onClick:()=>u(A),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[x(A),e.jsx("span",{className:"ml-1.5 text-xs",children:f(A)})]})]},A.id))})]},N))}),b]})}function qWt(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 VWt(s){if(!s)return null;const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);if(t)return`https://www.youtube.com/embed/${t[1]}`;const r=s.match(/loom\.com\/share\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:(s.match(/\.(mp4|webm|mov)(\?|$)/i),s)}function plt({portalId:s,portalSlug:t,ownerUserId:r,rewardText:n,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=k.useState(!1),m=k.useRef(!1),f=qWt(t);k.useEffect(()=>{m.current||(m.current=!0,U.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:r,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,r]);const x=async D=>{await U.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:r,click_type:D,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: ${f}`,_=async()=>{await navigator.clipboard.writeText(f),u(!0),x("copy_link"),setTimeout(()=>u(!1),2e3)},b=()=>{x("share_sms");const D=encodeURIComponent(y());window.location.href=`sms:?&body=${D}`},j=()=>{x("share_email");const D=encodeURIComponent("A referral you'll thank me for"),R=encodeURIComponent(y());window.location.href=`mailto:?subject=${D}&body=${R}`},N=()=>{x("open_form"),window.open(f,"_blank")},C=a||"Know someone buying or selling?",A=c?VWt(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(Ir,{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(Di,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:C}),n&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",n]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:N,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(ci,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:b,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(gc,{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(Ks,{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(la,{className:"w-3.5 h-3.5"}):e.jsx(si,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>x("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(ci,{className:"w-4 h-4 text-slate-400"})]})})]})}function HWt(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function GWt(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 WWt={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. 🎉"}},xlt=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function Nge(s){return xlt.map(t=>{if(t==="Active")return{key:"Active",label:HWt(s),description:GWt(s)};const r=WWt[t];return{key:t,label:r.label,description:r.description}})}function Nme(s){if(!s)return 0;const t=xlt.indexOf(s);return t>=0?t:0}const KWt="#2a4c64",YWt="#406E71";function ZWt({portal:s,linkedPortal:t,activePortal:r,activeTab:n,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var ae,ue,me;const d=(l==null?void 0:l.brand_color)||KWt,u=(l==null?void 0:l.accent_color)||YWt,m=(l==null?void 0:l.cover_photo_url)||null,f=(l==null?void 0:l.logo_url)||null,x=(l==null?void 0:l.tagline)||"Your Real Estate Agent",y=r==null?void 0:r.deal_pipeline,_=y==null?void 0:y.deal_pipeline_stages,b=_==null?void 0:_.is_won_stage,j=y==null?void 0:y.deal_type,N=r==null?void 0:r.stage_mapping;let C=Nge(j);N&&N.length>0&&(C=N.map((de,fe)=>{var je,xe;return{key:`custom-${fe}`,label:de.label||((je=C[fe])==null?void 0:je.label)||`Stage ${fe+1}`,description:de.description||((xe=C[fe])==null?void 0:xe.description)||"",video_url:de.video_url||void 0}}));const A=N&&N.length>0?Math.min(Nme(_==null?void 0:_.name),C.length-1):Nme(_==null?void 0:_.name),E=C[A],D=E==null?void 0:E.video_url,R=b&&r.show_post_close_tips!==!1&&r.referral_enabled!==!1,F=y!=null&&y.property_address?`${y.property_address}, ${y.city||""}, ${y.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,O=!!t,B=(ae=s==null?void 0:s.deal_pipeline)==null?void 0:ae.deal_type,K=(ue=t==null?void 0:t.deal_pipeline)==null?void 0:ue.deal_type,Z=de=>de==="listing"?"Your Sale":de==="buy-side"?"Your Purchase":"Transaction",Q=C.length>1?Math.round((A+1)/C.length*100):0,{data:W=[]}=hlt({id:r==null?void 0:r.id,owner_user_id:r==null?void 0:r.owner_user_id}),te=W.some(de=>!de.stage_filter||de.stage_filter.length===0||!(_!=null&&_.name)?!0:de.stage_filter.includes(_.name)),ne=()=>{var de;(de=document.getElementById("trusted-vendors"))==null||de.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"min-h-screen relative",style:{background:`radial-gradient(ellipse 80% 60% at 50% -10%, ${d}22, transparent 60%), linear-gradient(180deg, #f8fafc 0%, #ffffff 100%)`},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[480px] opacity-50",style:{background:`radial-gradient(circle at 80% 0%, ${u}33, transparent 50%), radial-gradient(circle at 10% 10%, ${d}33, transparent 55%)`}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[f?e.jsx("div",{className:"bg-white/80 backdrop-blur-sm rounded-xl px-3 py-1.5 shadow-sm border border-white",children:e.jsx("img",{src:f,alt:"Brand",className:"h-7 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold shadow-md",style:{background:`linear-gradient(135deg, ${d}, ${u})`},children:e.jsx(Ir,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.18em] text-slate-400 font-semibold",children:"Client Portal"}),e.jsx("p",{className:"text-sm font-medium text-slate-700",children:r!=null&&r.client_name?`Welcome, ${r.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(Oh,{className:"w-3.5 h-3.5"}),"Secure portal"]})]}),e.jsxs(Zr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.5,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl shadow-2xl border border-white/60 mb-8",style:{minHeight:320},children:[e.jsx("div",{className:"absolute inset-0",style:m?{backgroundImage:`linear-gradient(135deg, ${d}e6 0%, ${d}b3 45%, ${u}cc 100%), url(${m})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:`linear-gradient(135deg, ${d} 0%, ${u} 100%)`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"28px 28px"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-10 text-white",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-4 self-start",children:[e.jsx(Pn,{className:"w-3 h-3"}),j==="listing"?"Listing":j==="buy-side"?"Purchase":"Transaction",b&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"•"}),"Complete"]})]}),e.jsx("h1",{className:"text-5xl font-bold tracking-tight leading-[1.05] mb-3 font-serif",children:(y==null?void 0:y.deal_name)||"Your Transaction"}),F&&e.jsxs("div",{className:"flex items-center gap-1.5 text-white/80 text-base",children:[e.jsx(Ma,{className:"w-4 h-4"}),e.jsx("span",{children:F})]}),(r==null?void 0:r.welcome_message)&&e.jsx("p",{className:"mt-5 text-white/85 text-sm leading-relaxed max-w-2xl",children:r.welcome_message})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(XWt,{pct:Q,brand:d,accent:u}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/70 mt-3",children:"Journey progress"}),e.jsxs("p",{className:"text-sm font-medium text-white/95 mt-1",children:["Stage ",A+1," of ",C.length]})]})]})]}),O&&e.jsx("div",{className:"inline-flex gap-1 bg-white/70 backdrop-blur border border-slate-200 rounded-xl p-1 mb-6 shadow-sm",children:["primary","linked"].map(de=>{const fe=de==="primary"?B:K;return e.jsx("button",{onClick:()=>a(de),className:`px-4 py-2 rounded-lg text-sm font-medium transition-all ${n===de?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:Z(fe)},de)})}),e.jsxs("div",{className:"grid grid-cols-12 gap-6",children:[e.jsx("aside",{className:"col-span-3",children:e.jsxs("div",{className:"sticky top-6 space-y-4",children:[e.jsxs(FN,{children:[e.jsxs("div",{className:"text-center pt-2",children:[i!=null&&i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 rounded-full mx-auto object-cover ring-4 ring-white shadow-lg"}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center text-3xl font-bold text-white ring-4 ring-white shadow-lg",style:{background:`linear-gradient(135deg, ${d}, ${u})`},children:((me=i==null?void 0:i.name)==null?void 0:me.charAt(0))||"?"}),e.jsx("h3",{className:"mt-4 text-lg font-bold text-slate-800",children:i==null?void 0:i.name}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:x})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(d_e,{href:`tel:${i.phone}`,icon:Mn,label:"Call",sub:i.phone,brand:d}),(i==null?void 0:i.phone)&&e.jsx(d_e,{href:`sms:${i.phone}`,icon:gc,label:"Text message",brand:d}),(i==null?void 0:i.email)&&e.jsx(d_e,{href:`mailto:${i.email}`,icon:Ks,label:"Email",sub:i.email,brand:d})]})]}),e.jsxs(FN,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-3",children:"At a glance"}),e.jsxs("div",{className:"space-y-3",children:[(y==null?void 0:y.target_close_date)&&e.jsx(u_e,{icon:vn,label:"Target close",value:G9e(y.target_close_date),brand:d}),(y==null?void 0:y.contract_date)&&e.jsx(u_e,{icon:jn,label:"Under contract",value:G9e(y.contract_date),brand:d}),e.jsx(u_e,{icon:Ir,label:"Progress",value:`${Q}%`,brand:d})]})]}),e.jsx("div",{className:"text-center pt-2 space-y-1",children:e.jsx("p",{className:"text-[11px] text-slate-400",children:"Powered by ReLevelUp"})})]})}),e.jsxs("main",{className:"col-span-6 space-y-6",children:[R&&e.jsx(plt,{portalId:r.id,portalSlug:r.slug,ownerUserId:r.owner_user_id,rewardText:r.referral_reward_text,ctaHeadline:r.referral_cta_headline,agentName:i==null?void 0:i.name,clientName:r.client_name,reviewUrl:r.review_url,hubVideoUrl:r.homeowner_hub_video_url}),e.jsx(alt,{targetCloseDate:y==null?void 0:y.target_close_date,actualCloseDate:y==null?void 0:y.actual_close_date,clientName:r.client_name}),E&&e.jsxs(FN,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-3",children:"Where you are now"}),e.jsx(olt,{currentStage:E,nextStepText:r.next_step_text,nextStepVideoUrl:D||r.next_step_video_url})]}),e.jsxs(FN,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-4",children:"Your journey"}),e.jsx(ilt,{journeyStages:C,currentIndex:A})]}),o&&o.length>0&&e.jsx(FN,{children:e.jsx(dlt,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-6",children:[e.jsx(FN,{children:e.jsx(llt,{targetCloseDate:y==null?void 0:y.target_close_date,contractDate:y==null?void 0:y.contract_date,inspectionDate:r.inspection_date,appraisalDate:r.appraisal_date,actualCloseDate:y==null?void 0:y.actual_close_date})}),c&&c.length>0&&e.jsx(FN,{children:e.jsx(clt,{documents:c})}),te&&e.jsx(FN,{children:e.jsxs("button",{onClick:ne,className:"w-full flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all hover:scale-[1.02] hover:shadow-sm border border-transparent hover:border-slate-100 text-left",style:{backgroundColor:`${d}0d`},children:[e.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${d}1f`,color:d},children:e.jsx(ZF,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-slate-800 leading-tight",children:"View Trusted Vendors"}),e.jsx("p",{className:"text-xs text-slate-500 truncate",children:"My vetted recommendations"})]})]})})]})]}),(r==null?void 0:r.id)&&(r==null?void 0:r.owner_user_id)&&e.jsx("div",{id:"trusted-vendors",className:"mt-6 scroll-mt-10",children:e.jsx(flt,{portalId:r.id,ownerUserId:r.owner_user_id,currentStage:_==null?void 0:_.name,brandingColor:d,layout:"grid"})})]})]})}function FN({children:s}){return e.jsx("div",{className:"bg-white/80 backdrop-blur-xl rounded-2xl border border-white shadow-[0_8px_32px_-8px_rgba(15,23,42,0.08)] p-5",children:s})}function d_e({href:s,icon:t,label:r,sub:n,brand:a}){return e.jsxs("a",{href:s,className:"flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all hover:scale-[1.02] hover:shadow-sm border border-transparent hover:border-slate-100",style:{backgroundColor:`${a}0d`},children:[e.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${a}1f`,color:a},children:e.jsx(t,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium text-slate-800 leading-tight",children:r}),n&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:n})]})]})}function u_e({icon:s,label:t,value:r,brand:n}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${n}14`,color:n},children:e.jsx(s,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[11px] text-slate-400 uppercase tracking-wide",children:t}),e.jsx("p",{className:"text-sm font-semibold text-slate-800 truncate",children:r})]})]})}function XWt({pct:s,brand:t,accent:r}){const l=2*Math.PI*74,o=l-s/100*l,c="pg-"+t.replace("#","");return e.jsxs("div",{className:"relative",style:{width:160,height:160},children:[e.jsxs("svg",{width:160,height:160,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"#ffffff",stopOpacity:"0.95"}),e.jsx("stop",{offset:"100%",stopColor:r,stopOpacity:"0.9"})]})}),e.jsx("circle",{cx:160/2,cy:160/2,r:74,stroke:"rgba(255,255,255,0.18)",strokeWidth:12,fill:"none"}),e.jsx(Zr.circle,{cx:160/2,cy:160/2,r:74,stroke:`url(#${c})`,strokeWidth:12,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:l},animate:{strokeDashoffset:o},transition:{duration:1.2,ease:"easeOut"},strokeDasharray:l})]}),e.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:e.jsxs("span",{className:"text-4xl font-bold tabular-nums",children:[s,"%"]})})]})}function G9e(s){const t=s.split(/[-/T]/),r=new Date(Number(t[0]),Number(t[1])-1,Number(t[2]));return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(r)}function QWt({portal:s,dealData:t,agentProfile:r,customQuestions:n,deviceFingerprint:a,onComplete:i}){var y,_;const[l,o]=k.useState({first_name:((y=s.client_name)==null?void 0:y.split(" ")[0])||"",last_name:((_=s.client_name)==null?void 0:_.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=k.useState({}),[u,m]=k.useState(!1),f=Mt({mutationFn:async()=>{const{error:b}=await U.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(b)throw b},onSuccess:i,onError:b=>{console.error("[PortalOnboarding] Submit failed:",b),he.error("Something went wrong. Please try again.")}}),x=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null;return e.jsxs("div",{className:"max-w-md mx-auto px-4 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[(r==null?void 0:r.avatar_url)&&e.jsx("img",{src:r.avatar_url,alt:r.name,className:"w-14 h-14 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-xl font-bold text-slate-800",children:"Welcome to Your Portal"}),x&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(Ma,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:x.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),f.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"First Name *"}),e.jsx(Ne,{required:!0,value:l.first_name,onChange:b=>o(j=>({...j,first_name:b.target.value})),className:"mt-1 rounded-xl",placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Last Name"}),e.jsx(Ne,{value:l.last_name,onChange:b=>o(j=>({...j,last_name:b.target.value})),className:"mt-1 rounded-xl",placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Email"}),e.jsx(Ne,{type:"email",value:l.email,onChange:b=>o(j=>({...j,email:b.target.value})),className:"mt-1 rounded-xl",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Phone"}),e.jsx(Ne,{type:"tel",value:l.phone,onChange:b=>o(j=>({...j,phone:b.target.value})),className:"mt-1 rounded-xl",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Preferred Contact Method"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(b=>e.jsx("button",{type:"button",onClick:()=>o(j=>({...j,preferred_contact_method:b.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===b.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.label},b.value))})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Your Role"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(b=>e.jsx("button",{type:"button",onClick:()=>o(j=>({...j,client_role:b})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===b?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.charAt(0).toUpperCase()+b.slice(1)},b))})]}),n.map(b=>e.jsxs("div",{children:[e.jsxs(ce,{className:"text-xs text-slate-600",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(Ne,{required:b.is_required,value:c[b.id]||"",onChange:j=>d(N=>({...N,[b.id]:j.target.value})),className:"mt-1 rounded-xl"}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:j=>d(N=>({...N,[b.id]:j.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:j=>d(N=>({...N,[b.id]:j.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm h-10",children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(j=>e.jsx("option",{value:j,children:j},j))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(j=>e.jsx("button",{type:"button",onClick:()=>d(N=>({...N,[b.id]:j})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===j?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:j},j))})]},b.id)),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(j=>({...j,notes:b.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Anything you'd like your agent to know..."})]}),s.allow_spouse&&e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>m(!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 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"First Name"}),e.jsx(Ne,{value:l.spouse_first_name,onChange:b=>o(j=>({...j,spouse_first_name:b.target.value})),className:"mt-1 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Last Name"}),e.jsx(Ne,{value:l.spouse_last_name,onChange:b=>o(j=>({...j,spouse_last_name:b.target.value})),className:"mt-1 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Email"}),e.jsx(Ne,{type:"email",value:l.spouse_email,onChange:b=>o(j=>({...j,spouse_email:b.target.value})),className:"mt-1 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-slate-600",children:"Phone"}),e.jsx(Ne,{type:"tel",value:l.spouse_phone,onChange:b=>o(j=>({...j,spouse_phone:b.target.value})),className:"mt-1 rounded-xl"})]})]})]}),e.jsx(q,{type:"submit",disabled:f.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:f.isPending?"Submitting...":"Access My Portal"})]})]})}function JWt(s,t){const r=(n,a)=>a!=null&&a!==""?a:n!=null&&n!==""?n:null;return{logo_url:r(s==null?void 0:s.logo_url,t==null?void 0:t.logo_url),cover_photo_url:r(s==null?void 0:s.cover_photo_url,t==null?void 0:t.cover_photo_url),brand_color:r(s==null?void 0:s.brand_color,t==null?void 0:t.brand_color),accent_color:r(s==null?void 0:s.accent_color,t==null?void 0:t.accent_color),tagline:r(s==null?void 0:s.tagline,t==null?void 0:t.tagline),welcome_message:r(s==null?void 0:s.welcome_message,t==null?void 0:t.welcome_message)}}function glt(){const s=xa();return pt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function eKt(s){return pt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function tKt(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("agent_portal_branding").upsert({user_id:s,...r},{onConflict:"user_id"}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function ylt(s,t,r){var o;const n=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${r}-${Date.now()}.${n}`,{error:i}=await U.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=U.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function sKt(s,t){return pt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:r,error:n}=await U.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",s).eq("is_enabled",!0).maybeSingle();if(n)throw n;return r},enabled:t})}function rKt(s){return pt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",s).eq("is_enabled",!0).maybeSingle();if(r)throw r;return t},enabled:!!s})}function vlt({slug:s}){var ae,ue,me,de,fe,je;const[t,r]=k.useState(!1),[n,a]=k.useState("primary"),[i]=k.useState(()=>{const xe=`portal_fp_${s}`;let Ee=localStorage.getItem(xe);return Ee||(Ee=localStorage.getItem("portal_fp"),Ee?localStorage.setItem(xe,Ee):(Ee=crypto.randomUUID(),localStorage.setItem(xe,Ee),localStorage.setItem("portal_fp",Ee))),Ee});k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=sKt(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=rKt(d),m=(ae=l==null?void 0:l.deal_pipeline)==null?void 0:ae.owner_user_id;pt({queryKey:["portal-stages",m],queryFn:async()=>{const{data:xe,error:Ee}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",m).order("sort_order",{ascending:!0});if(Ee)throw Ee;return xe},enabled:!!m});const{data:f}=pt({queryKey:["portal-agent",m],queryFn:async()=>{const{data:xe,error:Ee}=await U.from("profiles").select("id, name, avatar_url, phone, email").eq("id",m).single();if(Ee)throw Ee;return xe},enabled:!!m}),{data:x}=eKt(m),y=n==="linked"&&u?u:l,_=y==null?void 0:y.id,b=JWt(x,y==null?void 0:y.branding_override),{data:j}=pt({queryKey:["portal-updates-public",_],queryFn:async()=>{const{data:xe,error:Ee}=await U.from("portal_updates").select("*").eq("portal_id",_).order("created_at",{ascending:!1});if(Ee)throw Ee;return xe},enabled:!!_}),N=(ue=y==null?void 0:y.deal_pipeline)==null?void 0:ue.id,{data:C}=pt({queryKey:["portal-documents",N],queryFn:async()=>{const{data:xe,error:Ee}=await U.from("deal_files").select("*").eq("deal_id",N).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(Ee)throw Ee;return xe},enabled:!!N}),A=l==null?void 0:l.id,E=A?`portal_onboarded_${A}_${i}`:null,D=E?localStorage.getItem(E)==="1":!1,{data:R,isLoading:F}=pt({queryKey:["portal-onboarding-check",A,i],queryFn:async()=>{const{data:xe,error:Ee}=await U.from("portal_onboarding_submissions").select("id").eq("portal_id",A).eq("device_fingerprint",i).maybeSingle();if(Ee)throw Ee;return xe&&E&&localStorage.setItem(E,"1"),xe},enabled:!!A&&!!(l!=null&&l.require_onboarding)&&!D,staleTime:5*60*1e3}),O=!!(l!=null&&l.require_onboarding)&&!D&&!R&&!t,{data:B}=pt({queryKey:["portal-custom-questions-public",m],queryFn:async()=>{const{data:xe,error:Ee}=await U.from("portal_custom_questions").select("*").eq("owner_user_id",m).eq("is_active",!0).order("sort_order",{ascending:!0});if(Ee)throw Ee;return xe},enabled:!!m&&O}),K=D||!!R||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!D&&F)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(ls,{className:"w-6 h-6 text-slate-400 animate-spin"})});if(c||!l)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("span",{className:"text-2xl",children:"🔒"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Portal Not Available"}),e.jsx("p",{className:"text-slate-500",children:"This portal is no longer active or doesn't exist."})]})});if(!K){const xe=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:e.jsx(QWt,{portal:l,dealData:xe,agentProfile:f,customQuestions:B||[],deviceFingerprint:i,onComplete:()=>{E&&localStorage.setItem(E,"1"),r(!0)}})})}const Z=(me=l==null?void 0:l.deal_pipeline)==null?void 0:me.deal_type,Q=(de=u==null?void 0:u.deal_pipeline)==null?void 0:de.deal_type,W=!!u,te=xe=>xe==="listing"?"Your Sale":xe==="buy-side"?"Your Purchase":"Transaction",ne=xe=>xe==="listing"?e.jsx(Pn,{className:"w-3.5 h-3.5"}):e.jsx(gg,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(ZWt,{portal:l,linkedPortal:u,activePortal:y,activeTab:n,onTabChange:a,agentProfile:f,branding:b,updates:j,documents:C})}),e.jsxs("div",{className:"lg:hidden min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[e.jsx(DWt,{dealData:y==null?void 0:y.deal_pipeline,agentProfile:f,welcomeMessage:(y==null?void 0:y.welcome_message)||b.welcome_message,isWon:(je=(fe=y==null?void 0:y.deal_pipeline)==null?void 0:fe.deal_pipeline_stages)==null?void 0:je.is_won_stage,branding:b}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-6",children:[W&&e.jsxs("div",{className:"flex gap-1 bg-slate-100 rounded-xl p-1",children:[e.jsxs("button",{onClick:()=>a("primary"),className:`flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all ${n==="primary"?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[ne(Z),te(Z)]}),e.jsxs("button",{onClick:()=>a("linked"),className:`flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all ${n==="linked"?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[ne(Q),te(Q)]})]}),e.jsx(nKt,{portal:y,updates:j,documents:C,agentProfile:f}),e.jsxs("div",{className:"text-center pt-6 pb-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-slate-400",children:[e.jsx(Oh,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-xs",children:"Secure Client Portal"})]}),f&&e.jsxs("p",{className:"text-xs text-slate-400",children:["Managed by ",e.jsx("span",{className:"font-medium text-slate-500",children:f.name})]}),e.jsx("p",{className:"text-[10px] text-slate-300",children:"Powered by ReLevelUp"})]})]})]})]})}function nKt({portal:s,updates:t,documents:r,agentProfile:n}){const a=s,i=a==null?void 0:a.deal_pipeline,l=i==null?void 0:i.deal_pipeline_stages,o=l==null?void 0:l.is_won_stage,c=i==null?void 0:i.deal_type,d=s.stage_mapping;let u=Nge(c);d&&d.length>0&&(u=d.map((_,b)=>{var j,N;return{key:`custom-${b}`,label:_.label||((j=u[b])==null?void 0:j.label)||`Stage ${b+1}`,description:_.description||((N=u[b])==null?void 0:N.description)||"",video_url:_.video_url||void 0}}));const m=d&&d.length>0?Math.min(Nme(l==null?void 0:l.name),u.length-1):Nme(l==null?void 0:l.name),f=u[m],x=f==null?void 0:f.video_url,y=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[y&&e.jsx(plt,{portalId:s.id,portalSlug:s.slug,ownerUserId:s.owner_user_id,rewardText:s.referral_reward_text,ctaHeadline:s.referral_cta_headline,agentName:n==null?void 0:n.name,clientName:s.client_name,reviewUrl:s.review_url,hubVideoUrl:s.homeowner_hub_video_url}),e.jsx(alt,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(ilt,{journeyStages:u,currentIndex:m}),f&&e.jsx(olt,{currentStage:f,nextStepText:s.next_step_text,nextStepVideoUrl:x||s.next_step_video_url}),e.jsx(llt,{targetCloseDate:i==null?void 0:i.target_close_date,contractDate:i==null?void 0:i.contract_date,inspectionDate:s.inspection_date,appraisalDate:s.appraisal_date,actualCloseDate:i==null?void 0:i.actual_close_date}),r&&r.length>0&&e.jsx(clt,{documents:r}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(flt,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(dlt,{updates:t})]})}function blt({slug:s}){const t=xo(),r=s||t.slug,[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState("buying"),[C,A]=k.useState("");k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:E,isLoading:D,error:R}=pt({queryKey:["portal-referral-target",r],queryFn:async()=>{if(!r)return null;const{data:B,error:K}=await U.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",r).eq("is_enabled",!0).maybeSingle();if(K)throw K;return B},enabled:!!r}),{data:F}=pt({queryKey:["portal-referral-agent",E==null?void 0:E.owner_user_id],queryFn:async()=>{const{data:B}=await U.from("profiles").select("id, name, avatar_url").eq("id",E.owner_user_id).single();return B},enabled:!!(E!=null&&E.owner_user_id)}),O=async B=>{if(B.preventDefault(),!E||!m.trim()){he.error("Please enter your friend's name");return}if(!x.trim()&&!_.trim()){he.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:K}=await U.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:m.trim(),friend_email:x.trim()||null,friend_phone:_.trim()||null,friend_interest:j,friend_message:C.trim()||null});if(K)throw K;l(!0)}catch(K){he.error(K.message||"Could not submit referral")}finally{a(!1)}};return D?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(dr,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):R||!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(la,{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 ",(F==null?void 0:F.name)||"your agent",". They'll reach out to"," ",e.jsx("span",{className:"font-semibold text-slate-800",children:m})," personally and treat them like family."]}),e.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[e.jsx(Aa,{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:[F!=null&&F.avatar_url?e.jsx("img",{src:F.avatar_url,alt:F.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(Di,{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(Di,{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 ",(F==null?void 0:F.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:O,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(ce,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ne,{id:"friend_name",value:m,onChange:B=>f(B.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(ce,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(Ne,{id:"friend_email",type:"email",value:x,onChange:B=>y(B.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(Ne,{id:"friend_phone",type:"tel",value:_,onChange:B=>b(B.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(ce,{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(B=>e.jsx("button",{type:"button",onClick:()=>N(B.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${j===B.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:B.l},B.v))})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:C,onChange:B=>A(B.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(ce,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(Ne,{id:"referrer_name",value:o,onChange:B=>c(B.target.value),placeholder:E.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(Ne,{id:"referrer_email",type:"email",value:d,onChange:B=>u(B.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:n,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[n?e.jsx(ls,{className:"w-4 h-4 animate-spin"}):e.jsx(Di,{className:"w-4 h-4"}),n?"Sending...":"Send Referral"]}),e.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}function aKt(){const t=vc().pathname.slice(1).replace(/\/$/,"");if(k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),e.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const r=t.match(/^([^/]+)\/refer$/);return r?e.jsx(blt,{slug:r[1]}):t.includes("/")?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):e.jsx(vlt,{slug:t})}function iKt(s){const t=[],r=n=>{n&&!t.includes(n)&&t.push(n)};for(const n of s.filter(Boolean)){r(n);try{const a=new URL(n),i=a.searchParams.get("u");i&&/\/functions\/v1\/trestle-media/i.test(a.pathname)&&r(i)}catch{}}return t}function kme({photos:s,alt:t="",className:r="w-full h-full",imgClassName:n="w-full h-full object-cover",iconClassName:a="w-8 h-8"}){const i=k.useMemo(()=>iKt(Array.isArray(s)?s:[]),[s]),[l,o]=k.useState(0);return k.useEffect(()=>{o(0)},[i.join("|")]),!i.length||l>=i.length?e.jsx("div",{className:`${r} bg-muted flex items-center justify-center text-muted-foreground`,children:e.jsx(Pn,{className:`${a} opacity-40`})}):e.jsx("div",{className:`${r} overflow-hidden bg-muted`,children:e.jsx("img",{src:i[l],alt:t,className:n,onError:()=>o(c=>c+1)})})}function _lt({comp:s,open:t,onClose:r}){var d;const[n,a]=k.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[m,f,x]=u.split(/[-/T]/);return m?`${f}/${x}/${m}`:null};return e.jsx(vs,{open:t,onOpenChange:u=>{u||r()},children:e.jsxs(ys,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(_s,{className:"px-6 pt-6 pb-2",children:[e.jsx(bs,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Ma,{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(kme,{photos:i.slice(n),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,m)=>e.jsx("button",{onClick:()=>a(m),className:`flex-none w-20 h-16 rounded overflow-hidden border-2 transition ${m===n?"border-primary":"border-transparent opacity-70 hover:opacity-100"}`,children:e.jsx(kme,{photos:[u],iconClassName:"w-5 h-5"})},m))})]}):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(Pn,{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(Xl,{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(Xe,{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(h_e,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(h_e,{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(h_e,{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(bq,{icon:e.jsx(k0,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(bq,{icon:e.jsx(of,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(bq,{icon:e.jsx(m2,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(bq,{icon:e.jsx(vn,{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(lx,{label:"MLS #",value:s.mlsNumber}),e.jsx(lx,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(lx,{label:"Lot Size",value:s.lotSize}),e.jsx(lx,{label:"Garage",value:s.garageSpaces}),e.jsx(lx,{label:"Stories",value:s.stories}),e.jsx(lx,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(lx,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(lx,{label:"Heating",value:s.heating}),e.jsx(lx,{label:"Cooling",value:s.cooling}),e.jsx(lx,{label:"Parking",value:s.parking}),e.jsx(lx,{label:"Elementary",value:s.elementarySchool}),e.jsx(lx,{label:"Middle",value:s.middleSchool}),e.jsx(lx,{label:"High",value:s.highSchool}),e.jsx(lx,{label:"Listed By",value:s.listAgentFullName}),e.jsx(lx,{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 bq({icon:s,label:t,value:r}){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:r})]})}function lx({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 h_e({label:s,date:t,active:r}){return e.jsxs("div",{className:`rounded-lg border p-2 text-center ${r?"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 _q({to:s,durationMs:t=1400,prefix:r="",suffix:n="",className:a,delayMs:i=0}){const[l,o]=k.useState(0),c=k.useRef(null);return k.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,m=x=>1-Math.pow(1-x,3),f=setTimeout(()=>{const x=y=>{d||(d=y);const _=y-d,b=Math.min(1,_/t);o(Math.round(u+(s-u)*m(b))),b<1&&(c.current=requestAnimationFrame(x))};c.current=requestAnimationFrame(x)},i);return()=>{clearTimeout(f),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[r,l.toLocaleString(),n]})}function oKt({low:s,likely:t,high:r,defaultMortgage:n=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=k.useState(t),[c,d]=k.useState(n),[u,m]=k.useState(a),[f,x]=k.useState(i),{commission:y,closing:_,net:b}=k.useMemo(()=>{const C=Math.round(l*u/100),A=Math.round(l*f/100);return{commission:C,closing:A,net:Math.max(0,l-C-A-(c||0))}},[l,u,f,c]),j=C=>`$${C.toLocaleString()}`,N=r>s?(l-s)/(r-s)*100:50;return e.jsxs(ke,{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(Wo,{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(Pe,{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(nf,{value:[l],min:s,max:r,step:1e3,onValueChange:([C])=>o(C)}),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(r)})]})]}),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,N))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(Ne,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:C=>d(Number(C.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Commission %"}),e.jsx(Ne,{type:"number",step:"0.25",value:u,onChange:C=>m(Number(C.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Closing costs %"}),e.jsx(Ne,{type:"number",step:"0.25",value:f,onChange:C=>x(Number(C.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 (",f,"%)"]}),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(uP,{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(b)})]})]}),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 wlt({tokenOverride:s}={}){var Le,$e,ve,Qe,we,nt,Se,Ge,We,Ce,qe,et;const t=xo(),r=s??t.token,[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState([]),[d,u]=k.useState(!0),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState(!1),[C,A]=k.useState(!1),[E,D]=k.useState(null),[R,F]=k.useState(null),[O,B]=k.useState(!1),{toast:K}=Ba();k.useEffect(()=>{r&&(async()=>{const{data:Ze}=await U.from("cmas").select("*").eq("share_token",r).eq("status","shared").maybeSingle();if(!Ze){u(!1);return}a(Ze);const[{data:rt},{data:ct}]=await Promise.all([U.from("cma_comps").select("*").eq("cma_id",Ze.id).order("position"),U.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",Ze.agent_id).maybeSingle()]);c((rt||[]).filter(kt=>kt.selected)),l(ct);const vt=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",vt),await U.from("cma_views").insert({cma_id:Ze.id,visitor_token:vt,user_agent:navigator.userAgent}),u(!1)})()},[r]);const Z=async Ze=>{if(!n)return;const rt=localStorage.getItem("cma_visitor_token")||"";await U.from("cma_views").insert({cma_id:n.id,visitor_token:rt,reactions:{[Ze]:!0}}),U.functions.invoke("cma-reply-notify",{body:{shareToken:r,reaction:Ze,visitorToken:rt}}).catch(()=>{}),K({title:"Thanks — your agent just got notified ✨"})},Q=!(n!=null&&n.contact_id),W=async()=>{if(!n||!m.trim())return;if(Q&&(!x.trim()||!_.trim())){K({title:"Please add your name and email",variant:"destructive"});return}N(!0);const Ze=localStorage.getItem("cma_visitor_token")||"",{data:rt,error:ct}=await U.functions.invoke("cma-reply-notify",{body:{shareToken:r,message:m,visitorToken:Ze,viewerName:x.trim()||void 0,viewerEmail:_.trim()||void 0}});if(N(!1),ct||!(rt!=null&&rt.success)){K({title:"Could not send",description:(ct==null?void 0:ct.message)||(rt==null?void 0:rt.error),variant:"destructive"});return}f(""),A(!0),K({title:"Message sent to your agent"})},te=k.useMemo(()=>{const Ze=o.map(rt=>{const ct=rt.snapshot,vt=(ct==null?void 0:ct.soldPrice)||(ct==null?void 0:ct.price);return vt&&(ct!=null&&ct.sqft)?vt/ct.sqft:null}).filter(rt=>!!rt).sort((rt,ct)=>rt-ct);return Ze.length?Math.round(Ze[Math.floor(Ze.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(ls,{className:"w-8 h-8 animate-spin"})});if(!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:e.jsxs("div",{children:[e.jsx(Pn,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const ne=n.subject||{},ae=(Le=n.settings)==null?void 0:Le.personalVideo,ue=($e=ne.photos)==null?void 0:$e[0],me=n.contact_first_name?n.contact_first_name:null,de=((i==null?void 0:i.name)||"A").split(" ").map(Ze=>Ze[0]).slice(0,2).join("").toUpperCase(),fe=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,je=i!=null&&i.email?`mailto:${i.email}`:null,xe=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,Ee=n.price_low??null,Me=n.price_likely??null,Oe=n.price_high??null,Ie=Ee&&Me&&Oe,ze=Me&&ne.sqft?Math.round(Me/ne.sqft):null,Ve=ze&&te?Math.round((ze-te)/te*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:de}),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(Ga,{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:[fe&&e.jsx(q,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:fe,children:[e.jsx(Mn,{className:"w-4 h-4 mr-1"}),"Call"]})}),je&&e.jsx(q,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:je,children:[e.jsx(Ks,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[ue?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:ue,alt:ne.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${ae!=null&&ae.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(Xe,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(Ir,{className:"w-3 h-3 mr-1"}),me?`Prepared for ${me}`:n.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:ne.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(Ma,{className:"w-4 h-4"}),ne.city,", ",ne.state," ",ne.zip]}),Ie&&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(_q,{to:Me,prefix:"$",durationMs:1600,delayMs:250})})}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(_q,{to:Ee,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(_q,{to:Me,prefix:"$",delayMs:650})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(_q,{to:Oe,prefix:"$",delayMs:800})})]})]})]})]}),(ae==null?void 0:ae.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>B(!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:[ae.thumb?e.jsx("img",{src:ae.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:ae.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[e.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 rounded-full bg-white/95 text-primary flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform",children:e.jsx(Al,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),e.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((ve=i==null?void 0:i.name)==null?void 0:ve.split(" ")[0])||"your agent"]})]})]})})]})})]}),O&&(ae==null?void 0:ae.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>B(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:Ze=>Ze.stopPropagation(),children:[e.jsx("video",{src:ae.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx(q,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>B(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:ne.bedrooms??"—"},{label:"Baths",value:ne.bathrooms??"—"},{label:"Sq Ft",value:((Qe=ne.sqft)==null?void 0:Qe.toLocaleString())??"—"},{label:"Year Built",value:ne.yearBuilt??"—"}].map((Ze,rt)=>e.jsx(ke,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${rt*80}ms`},children:e.jsxs(Pe,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:Ze.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:Ze.label})]})},rt))}),((nt=(we=n.settings)==null?void 0:we.priceOverride)==null?void 0:nt.enabled)&&((Ge=(Se=n.settings)==null?void 0:Se.priceOverride)==null?void 0:Ge.note)&&e.jsx(ke,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Pe,{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:n.settings.priceOverride.note})]})}),Ie&&e.jsx(oKt,{low:Ee,likely:Me,high:Oe}),te&&ze&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(ke,{className:"md:col-span-2",children:e.jsxs(Pe,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),e.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",e.jsxs("strong",{className:"text-foreground",children:[o.length," comparable ",o.length===1?"home":"homes"]})," in ",ne.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",te,"/sqft"]}),". Applied to your home's ",(We=ne.sqft)==null?void 0:We.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(te*(ne.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(ke,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Pe,{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:["$",ze,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:["$",te,"/sqft"]})]}),Ve!==null&&Ve!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Ve>0?"text-emerald-600":"text-rose-600"}`,children:[Ve>0?"▲":"▼"," ",Math.abs(Ve),"% ",Ve>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(Xe,{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((Ze,rt)=>{var kt;const ct=Ze.snapshot,vt=ct.soldPrice||ct.price;return e.jsxs(ke,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${R===rt?"ring-2 ring-primary":""}`,style:{animationDelay:`${rt*60}ms`},onClick:()=>D(rt),onMouseEnter:()=>F(rt),onMouseLeave:()=>F(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(kme,{photos:ct.photos,className:"w-full h-44"}),e.jsxs(Xe,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",rt+1]}),e.jsx(Xe,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:ct.status})]}),e.jsxs(Pe,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:ct.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[ct.city,", ",ct.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[ct.bedrooms??"?","bd · ",ct.bathrooms??"?","ba · ",((kt=ct.sqft)==null?void 0:kt.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:["$",vt==null?void 0:vt.toLocaleString()]}),ct.sqft&&vt?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(vt/ct.sqft),"/sqft"]}):null]})]})]},rt)})})]}),e.jsx(_lt,{comp:E!==null?(Ce=o[E])==null?void 0:Ce.snapshot:null,open:E!==null,onClose:()=>D(null)}),e.jsx(ke,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Pe,{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",me?`, ${me}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((qe=i==null?void 0:i.name)==null?void 0:qe.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:yi,label:"I love this price"},{kind:"fair",icon:wm,label:"Seems fair"},{kind:"lower",icon:E_,label:"I'd price lower"},{kind:"higher",icon:Wo,label:"I'd price higher"},{kind:"ready_to_list",icon:j_,label:"Ready to list"},{kind:"want_walkthrough",icon:Nn,label:"Want a walkthrough"},{kind:"need_time",icon:vn,label:"Need more time"},{kind:"have_questions",icon:e_,label:"I have questions"}].map(({kind:Ze,icon:rt,label:ct})=>e.jsxs(q,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>Z(Ze),children:[e.jsx(rt,{className:"w-4 h-4 mr-2"}),ct]},Ze))}),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(gc,{className:"w-4 h-4"}),"Ask your agent a question"]}),C?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! ",((et=i==null?void 0:i.name)==null?void 0:et.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[Q&&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:x,onChange:Ze=>y(Ze.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:_,onChange:Ze=>b(Ze.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:m,onChange:Ze=>f(Ze.target.value)}),e.jsx(q,{onClick:W,disabled:!m.trim()||j,className:"mt-2",children:j?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(ke,{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:de}),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:[fe&&e.jsx(q,{asChild:!0,children:e.jsxs("a",{href:fe,children:[e.jsx(Mn,{className:"w-4 h-4 mr-2"}),i.phone]})}),je&&e.jsx(q,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:je,children:[e.jsx(Ks,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx(q,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ql,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(fe||xe||je)&&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:[fe&&e.jsx(q,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:fe,children:[e.jsx(Mn,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),xe&&e.jsx(q,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:xe,children:[e.jsx(gc,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),je&&e.jsx(q,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:je,children:[e.jsx(Ks,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function lKt(){const t=vc().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(wlt,{tokenOverride:t})}const Cke="levelup_affiliate_ref",cKt=30,dKt=()=>{const[s]=ic();k.useEffect(()=>{const t=s.get("ref");if(t){const r={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(Cke,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",t)}},[s])},uKt=()=>{try{const s=localStorage.getItem(Cke);if(!s)return null;const t=JSON.parse(s),r=cKt*24*60*60*1e3;return Date.now()-t.timestamp>r?(localStorage.removeItem(Cke),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},Sme="/assets/levelup-logo-header-_ZX7DvlA.png",hKt="/assets/scale-your-team-ku4MPatU.png";function mKt({open:s,onOpenChange:t}){return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(_s,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:e.jsx(Ga,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(bs,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(an,{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 Wm={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}},fKt=[{icon:Ff,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:dl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:vn,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:gc,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:En,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Di,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],pKt=[{icon:Dr,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Ir,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Mn,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:_m,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Ma,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Mo,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:yi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:zh,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],xKt=[{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."}],gKt=()=>{const{user:s,loading:t}=Cs(),r=qr(),[n]=ic();k.useEffect(()=>{const R=window.location.host==="listings.relevelup.com",F=window.location.pathname==="/";if(R&&F){r("/public/listings",{replace:!0});return}},[r]);const[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,m]=k.useState(""),[f,x]=k.useState(""),[y,_]=k.useState(""),[b,j]=k.useState(!1),[N,C]=k.useState(!1),A=(R,F=!1)=>{o({tier:R,skipTrial:F}),d(!0)};dKt(),k.useEffect(()=>{const R=window.location.host==="listings.relevelup.com",F=location.pathname.startsWith("/public/");!t&&s&&!R&&!F&&r("/dashboard")},[s,t,r,location.pathname]),k.useEffect(()=>{n.get("canceled")==="true"&&he.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const E=async(R,F=!1)=>{if(!u){he.error("Please enter your email address");return}if(!f.trim()){he.error("Please enter your full name");return}j(!0),i(R+(F?"_direct":""));const O=uKt();try{const{data:B,error:K}=await U.functions.invoke("create-checkout",{body:{tier:R,email:u,name:f.trim(),couponCode:y.trim()||void 0,skipTrial:F,referralCode:O}});if(K)throw K;if(B!=null&&B.url)window.open(B.url,"_blank","noopener,noreferrer"),he.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(B){console.error("Checkout error:",B),he.error(B.message||"Failed to start checkout. Please try again.")}finally{j(!1),i(null),d(!1),o(null)}},D=()=>{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:Sme,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(q,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var R;return(R=document.getElementById("features"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(q,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(q,{onClick:()=>r("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-[136px] md:h-[164px] drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("p",{className:"text-lg text-white/80 max-w-3xl mx-auto leading-relaxed font-sans font-bold md:text-4xl",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[e.jsxs(q,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("free-trial"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(ci,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(q,{size:"lg",variant:"outline",onClick:()=>{var R;return(R=document.getElementById("features"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#1e3a4c] rounded-full",children:"See What's Included"})]})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs(q,{size:"lg",variant:"outline",onClick:()=>{var R;return(R=document.getElementById("brokerage"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Ga,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(q,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(qi,{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:fKt.map((R,F)=>e.jsxs(ke,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Pt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(R.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Dt,{className:"text-xl font-sans",children:R.title})]}),e.jsx(Pe,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:R.description})})]},F))})]})}),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(Ir,{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:pKt.map((R,F)=>e.jsxs(ke,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Pt,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(R.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Dt,{className:"text-lg font-semibold text-white",children:R.title})]}),e.jsx(Pe,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:R.description})})]},F))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(q,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",e.jsx(ci,{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(Ga,{className:"w-4 h-4"}),"For Brokerages"]}),e.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),e.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((R,F)=>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(la,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:R})]},F))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(q,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(Ia,{className:"ml-2 w-5 h-5"})]}),e.jsxs(q,{size:"lg",variant:"outline",onClick:()=>C(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(vn,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:hKt,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:xKt.map((R,F)=>e.jsx(ke,{className:"bg-muted/30 border-0",children:e.jsxs(Pe,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(O=>e.jsx(fa,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},O))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',R.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:R.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:R.role})]})]})},F))})]})}),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(q,{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(ci,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),e.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),e.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:[e.jsxs(ke,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Pt,{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(qi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(Dt,{className:"text-xl font-sans",children:Wm.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:Wm.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Wm.individual_agent.period})]}),e.jsx(Ur,{className:"text-base mt-2",children:Wm.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(jn,{className:"w-4 h-4"}),Wm.individual_agent.trial]})]}),e.jsx(Pe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Wm.individual_agent.features.map((R,F)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(la,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},F))})}),e.jsxs(y7,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(q,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("individual_agent"),children:"Start Free Trial"}),e.jsx(q,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>A("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(ke,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl scale-105 bg-background",children:[e.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),e.jsxs(Pt,{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(Ga,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-xl font-sans",children:Wm.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Wm.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:Wm.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Wm.brokerage_under_25.period})]}),e.jsx(Ur,{className:"text-base mt-2",children:Wm.brokerage_under_25.description})]}),e.jsx(Pe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Wm.brokerage_under_25.features.map((R,F)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(la,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},F))})}),e.jsx(y7,{className:"pt-4",children:e.jsx(q,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(ke,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Pt,{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(Ga,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-xl font-sans",children:Wm.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Wm.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:Wm.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Wm.brokerage_over_25.period})]}),e.jsx(Ur,{className:"text-base mt-2",children:Wm.brokerage_over_25.description})]}),e.jsx(Pe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Wm.brokerage_over_25.features.map((R,F)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(la,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},F))})}),e.jsx(y7,{className:"pt-4",children:e.jsx(q,{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(Oh,{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(ke,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Pe,{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(Ga,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(ke,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Pe,{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(ke,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Pe,{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(M1,{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(ke,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Pe,{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(En,{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(q,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",e.jsx(ci,{className:"ml-2 w-5 h-5"})]}),e.jsx(q,{size:"lg",onClick:()=>r("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})]}),e.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("img",{src:Sme,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(mKt,{open:N,onOpenChange:C}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsx(bs,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(an,{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(ce,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ne,{id:"dialog-name",type:"text",placeholder:"John Smith",value:f,onChange:R=>x(R.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ce,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ne,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:R=>m(R.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ce,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(Ne,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:y,onChange:R=>_(R.target.value),className:"mt-1"})]})]}),e.jsx(q,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:D,disabled:b,children:b?"Loading...":"Continue to Checkout"})]})})]})},W9e=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{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"})]})]})]})]})})]}),K9e=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{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"})]})]})]})]})})]}),yKt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{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"})]})]})]})]})})]}),Y9e="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.",vKt=tw({name:ho().trim().min(1,"Name is required").max(200),phone:ho().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:ho().trim().email("Enter a valid email").max(320).optional().or(tf(""))});function bKt(){const[s,t]=k.useState(""),[r,n]=k.useState(""),[a,i]=k.useState(""),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,m]=k.useState(!1),f=async x=>{var b;if(x.preventDefault(),!l){he.error("Please check the consent box to opt in.");return}const y=vKt.safeParse({name:s,phone:r,email:a});if(!y.success){he.error(((b=y.error.issues[0])==null?void 0:b.message)??"Please check your inputs.");return}d(!0);const{error:_}=await U.from("sms_opt_in_consents").insert({name:y.data.name,phone:y.data.phone,email:y.data.email||null,consent_text:Y9e,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),_){he.error("Something went wrong. Please try again.");return}m(!0)};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-muted/30 py-10 px-4",children:[e.jsxs(Yo,{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(Ui,{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(ke,{className:"p-8 text-center",children:[e.jsx(qn,{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(ke,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:f,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"name",children:"Full Name *"}),e.jsx(Ne,{id:"name",value:s,onChange:x=>t(x.target.value),required:!0,maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"phone",children:"Mobile Number *"}),e.jsx(Ne,{id:"phone",type:"tel",value:r,onChange:x=>n(x.target.value),required:!0,maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"email",children:"Email (optional)"}),e.jsx(Ne,{id:"email",type:"email",value:a,onChange:x=>i(x.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(Ri,{id:"consent",checked:l,onCheckedChange:x=>o(x===!0),className:"mt-0.5"}),e.jsx(ce,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:Y9e})]})}),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(Vn,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(Vn,{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(q,{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(A1,{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 jlt="/assets/levelup-logo-horizontal-DEFNc0ms.png",_Kt=tw({email:ho().email("Invalid email address"),password:ho().min(6,"Password must be at least 6 characters")}),wKt="https://dashboard.relevelup.com";function jKt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}const NKt=()=>{const{signIn:s,user:t}=Cs(),r=qr(),[n]=ic(),[a,i]=k.useState(!1),[l,o]=k.useState({}),[c,d]=k.useState(""),[u,m]=k.useState(!1),[f,x]=k.useState(!1);k.useEffect(()=>{const b=n.get("authorization_id");if(b&&window.location.hostname==="tile-portal.lovable.app"){const N=new URL("/auth",wKt);N.searchParams.set("authorization_id",b),window.location.replace(N.toString());return}if(b){const N=`/oauth/consent?authorization_id=${encodeURIComponent(b)}`;sessionStorage.setItem("redirectAfterLogin",N);return}const j=n.get("next");j&&jKt(j)&&sessionStorage.setItem("redirectAfterLogin",j)},[n]),k.useEffect(()=>{if(t){const b=n.get("authorization_id");if(b){sessionStorage.removeItem("redirectAfterLogin"),window.location.assign(`/oauth/consent?authorization_id=${encodeURIComponent(b)}`);return}const j=sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(j.startsWith("/oauth/consent")||j.startsWith("/.lovable/oauth/consent")){window.location.assign(j);return}sessionStorage.removeItem("redirectAfterLogin"),r(j)}},[t,r,n]);const y=async b=>{b.preventDefault(),o({}),i(!0);const j=new FormData(b.currentTarget),N=j.get("email"),C=j.get("password");try{_Kt.parse({email:N,password:C}),await s(N,C)}catch(A){if(A instanceof VBt){const E={};A.issues.forEach(D=>{D.path[0]&&(E[D.path[0]]=D.message)}),o(E)}}finally{i(!1)}},_=async()=>{if(!c){he.error("Please enter your email address");return}m(!0);try{const{error:b}=await U.functions.invoke("send-password-reset",{body:{email:c,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(b)throw b;he.success("Password reset email sent! Check your inbox."),x(!1),d("")}catch(b){he.error(b.message||"Failed to send reset email")}finally{m(!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(Vn,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(Aa,{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:jlt,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ke,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Pt,{className:"space-y-1 text-center pb-4",children:[e.jsx(Dt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Ur,{className:"text-gray-600",children:"Sign in to access your dashboard"})]}),e.jsx(Pe,{children:e.jsxs("form",{onSubmit:y,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(Ne,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),l.email&&e.jsx("p",{className:"text-sm text-red-600",children:l.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(Ne,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),l.password&&e.jsx("p",{className:"text-sm text-red-600",children:l.password})]}),e.jsx(q,{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:a,children:a?"Signing in...":"Sign In"}),e.jsxs(vs,{open:f,onOpenChange:x,children:[e.jsx(Yi,{asChild:!0,children:e.jsx(q,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(ys,{className:"bg-white",children:[e.jsxs(_s,{children:[e.jsx(bs,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(an,{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(ce,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(Ne,{id:"reset-email",type:"email",placeholder:"your@email.com",value:c,onChange:b=>d(b.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(q,{onClick:_,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:u,children:u?"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(Vn,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},m_e=()=>U.auth.oauth,kKt="https://dashboard.relevelup.com";function SKt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function Z9e(){var u;const[s]=ic(),t=s.get("authorization_id")??"",[r,n]=k.useState(null),[a,i]=k.useState(null),[l,o]=k.useState(!1);k.useEffect(()=>{let m=!0;return(async()=>{if(!t){i("Missing authorization_id");return}const f=window.location.pathname+window.location.search;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${kKt}${f}`;return}const{data:x}=await U.auth.getSession();if(!x.session){SKt(f)&&sessionStorage.setItem("redirectAfterLogin",f),window.location.href=`/auth?authorization_id=${encodeURIComponent(t)}`;return}sessionStorage.removeItem("redirectAfterLogin");const{data:y,error:_}=await m_e().getAuthorizationDetails(t);if(!m)return;if(_){i(_.message);return}const b=(y==null?void 0:y.redirect_url)??(y==null?void 0:y.redirect_to);if(b&&!(y!=null&&y.client)){window.location.href=b;return}n(y)})(),()=>{m=!1}},[t]);async function c(m){o(!0);const{data:f,error:x}=m?await m_e().approveAuthorization(t):await m_e().denyAuthorization(t);if(x){o(!1),i(x.message);return}const y=(f==null?void 0:f.redirect_url)??(f==null?void 0:f.redirect_to);if(!y){o(!1),i("No redirect returned by the authorization server.");return}window.location.href=y}if(a)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(ke,{className:"w-full max-w-md",children:e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Authorization error"}),e.jsx(Ur,{children:a})]})})});if(!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-primary"})});const d=((u=r.client)==null?void 0:u.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{children:["Connect ",d," to LevelUp"]}),e.jsxs(Ur,{children:[d," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Pe,{className:"flex gap-3 justify-end",children:[e.jsx(q,{variant:"outline",disabled:l,onClick:()=>c(!1),children:"Deny"}),e.jsx(q,{disabled:l,onClick:()=>c(!0),children:l?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const Nlt=s=>{const[t,r]=k.useState(null),[n,a]=k.useState(!0);return k.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await U.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=U.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);r(`${c.publicUrl}?t=${Date.now()}`)}else r(null)}catch(o){console.error("Error fetching avatar:",o),r(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:n,refreshAvatar:async()=>{if(s)try{const{data:l}=await U.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=U.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);r(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},klt=async s=>{const t=new Map;return await Promise.all(s.map(async r=>{try{const{data:n}=await U.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:a}=U.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);t.set(r,a.publicUrl)}}catch{}})),t},CKt=s=>{const[t,r]=k.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return k.useEffect(()=>{if(!s){r(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await U.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),r(m=>({...m,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const m=new Date().getTime(),f=new Date(d).getTime(),x=Math.ceil((f-m)/(1e3*60*60*24)),y=x<=0;r({isTrial:!0,isExpired:y,expiresAt:d,daysLeft:y?0:x,loading:!1})}else r({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),r(i=>({...i,loading:!1}))}})()},[s]),t},Slt=()=>{const{data:s,isLoading:t}=pt({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:a}=await U.from("feature_flags").select("*");if(a)throw a;return n}}),r=n=>{if(!s)return!1;const a=s.find(i=>i.key===n);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:r,isAgentOSEnabled:r("agent_os_enabled"),isInnerCircleEnabled:r("innercircle_enabled"),isMarketplaceEnabled:r("marketplace")}},X9e="community_last_seen_post_at";function TKt(){const{user:s}=Cs(),t=vc(),[r,n]=k.useState(0),[a,i]=k.useState(null);k.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${X9e}_${s.id}`);i(o)},[s]),k.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const x=sessionStorage.getItem(o);if(x){const y=JSON.parse(x);if(y.ts&&Date.now()-y.ts{if(!s)return;const o=U.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||n(_=>_+1);const{data:m}=await U.from("profiles").select("name").eq("id",d.user_id).single(),f=(m==null?void 0:m.name)||"Someone",x=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),y=x.length>50?x.substring(0,50)+"...":x;u||he("New Community Post",{description:`${f}: ${y}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{U.removeChannel(o)}},[s,t.pathname]);const l=k.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${X9e}_${s.id}`,o),i(o),n(0)},[s]);return k.useEffect(()=>{t.pathname==="/community"&&r>0&&l()},[t.pathname,r,l]),{unreadCount:r,markAsRead:l}}function EKt(){const{isAdmin:s}=Cs(),{data:t=0}=pt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await U.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(n)throw n;return r||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}var kge="Collapsible",[AKt,Hnr]=bu(kge),[MKt,nEe]=AKt(kge),Clt=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,open:n,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=df({prop:n,defaultProp:a??!1,onChange:l,caller:kge});return e.jsx(MKt,{scope:r,disabled:i,contentId:jm(),open:c,onOpenToggle:k.useCallback(()=>d(u=>!u),[d]),children:e.jsx(Yn.div,{"data-state":iEe(c),"data-disabled":i?"":void 0,...o,ref:t})})});Clt.displayName=kge;var Tlt="CollapsibleTrigger",Elt=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,...n}=s,a=nEe(Tlt,r);return e.jsx(Yn.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":iEe(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...n,ref:t,onClick:dn(s.onClick,a.onOpenToggle)})});Elt.displayName=Tlt;var aEe="CollapsibleContent",Alt=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=nEe(aEe,s.__scopeCollapsible);return e.jsx(yh,{present:r||a.open,children:({present:i})=>e.jsx(IKt,{...n,ref:t,present:i})})});Alt.displayName=aEe;var IKt=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,present:n,children:a,...i}=s,l=nEe(aEe,r),[o,c]=k.useState(n),d=k.useRef(null),u=_i(t,d),m=k.useRef(0),f=m.current,x=k.useRef(0),y=x.current,_=l.open||o,b=k.useRef(_),j=k.useRef(void 0);return k.useEffect(()=>{const N=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(N)},[]),Gu(()=>{const N=d.current;if(N){j.current=j.current||{transitionDuration:N.style.transitionDuration,animationName:N.style.animationName},N.style.transitionDuration="0s",N.style.animationName="none";const C=N.getBoundingClientRect();m.current=C.height,x.current=C.width,b.current||(N.style.transitionDuration=j.current.transitionDuration,N.style.animationName=j.current.animationName),c(n)}},[l.open,n]),e.jsx(Yn.div,{"data-state":iEe(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!_,...i,ref:u,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":y?`${y}px`:void 0,...s.style},children:_&&a})});function iEe(s){return s?"open":"closed"}var PKt=Clt;const E0=PKt,A0=Elt,M0=Alt,LKt="/assets/levelup-logo-Eif24dqY.png",DKt="/assets/levelup-logo-icon-C-7iromj.png",RKt="/assets/levelup-logo-mobile-B9skSjUG.png";var kB=s=>s.type==="checkbox",QT=s=>s instanceof Date,gx=s=>s==null;const Mlt=s=>typeof s=="object";var gh=s=>!gx(s)&&!Array.isArray(s)&&Mlt(s)&&!QT(s),Ilt=s=>gh(s)&&s.target?kB(s.target)?s.target.checked:s.target.value:s,OKt=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,Plt=(s,t)=>s.has(OKt(t)),FKt=s=>{const t=s.constructor&&s.constructor.prototype;return gh(t)&&t.hasOwnProperty("isPrototypeOf")},oEe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function rm(s){let t;const r=Array.isArray(s),n=typeof FileList<"u"?s instanceof FileList:!1;if(s instanceof Date)t=new Date(s);else if(!(oEe&&(s instanceof Blob||n))&&(r||gh(s)))if(t=r?[]:{},!r&&!FKt(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=rm(s[a]));else return s;return t}var Sge=s=>/^\w*$/.test(s),nh=s=>s===void 0,lEe=s=>Array.isArray(s)?s.filter(Boolean):[],cEe=s=>lEe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),wa=(s,t,r)=>{if(!t||!gh(s))return r;const n=(Sge(t)?[t]:cEe(t)).reduce((a,i)=>gx(a)?a:a[i],s);return nh(n)||n===s?nh(s[t])?r:s[t]:n},m0=s=>typeof s=="boolean",cc=(s,t,r)=>{let n=-1;const a=Sge(t)?[t]:cEe(t),i=a.length,l=i-1;for(;++nCt.useContext(dEe),zKt=s=>{const{children:t,...r}=s;return Ct.createElement(dEe.Provider,{value:r},t)};var Llt=(s,t,r,n=!0)=>{const a={defaultValues:t._defaultValues};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==x1.all&&(t._proxyFormState[l]=!n||x1.all),r&&(r[l]=!0),s[l]}});return a};const uEe=typeof window<"u"?Ct.useLayoutEffect:Ct.useEffect;function BKt(s){const t=Cge(),{control:r=t.control,disabled:n,name:a,exact:i}=s||{},[l,o]=Ct.useState(r._formState),c=Ct.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return uEe(()=>r._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!n&&o({...r._formState,...d})}}),[a,n,i]),Ct.useEffect(()=>{c.current.isValid&&r._setValid(!0)},[r]),Ct.useMemo(()=>Llt(l,r,c.current,!1),[l,r])}var d_=s=>typeof s=="string",Dlt=(s,t,r,n,a)=>d_(s)?(n&&t.watch.add(s),wa(r,s,a)):Array.isArray(s)?s.map(i=>(n&&t.watch.add(i),wa(r,i))):(n&&(t.watchAll=!0),r),Tke=s=>gx(s)||!Mlt(s);function Uj(s,t,r=new WeakSet){if(Tke(s)||Tke(t))return s===t;if(QT(s)&&QT(t))return s.getTime()===t.getTime();const n=Object.keys(s),a=Object.keys(t);if(n.length!==a.length)return!1;if(r.has(s)||r.has(t))return!0;r.add(s),r.add(t);for(const i of n){const l=s[i];if(!a.includes(i))return!1;if(i!=="ref"){const o=t[i];if(QT(l)&&QT(o)||gh(l)&&gh(o)||Array.isArray(l)&&Array.isArray(o)?!Uj(l,o,r):l!==o)return!1}}return!0}function $Kt(s){const t=Cge(),{control:r=t.control,name:n,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 m=Ct.useMemo(()=>r._getWatch(n,c.current),[r,n]),[f,x]=Ct.useState(d.current?d.current(m):m);return uEe(()=>r._subscribe({name:n,formState:{values:!0},exact:l,callback:y=>{if(!i){const _=Dlt(n,r._names,y.values||r._formValues,!1,c.current);if(d.current){const b=d.current(_);Uj(b,u.current)||(x(b),u.current=b)}else x(_)}}}),[r,i,n,l]),Ct.useEffect(()=>r._removeUnmounted()),f}function UKt(s){const t=Cge(),{name:r,disabled:n,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=Plt(a._names.array,r),c=Ct.useMemo(()=>wa(a._formValues,r,wa(a._defaultValues,r,l)),[a,r,l]),d=$Kt({control:a,name:r,defaultValue:c,exact:!0}),u=BKt({control:a,name:r,exact:!0}),m=Ct.useRef(s),f=Ct.useRef(a.register(r,{...s.rules,value:d,...m0(s.disabled)?{disabled:s.disabled}:{}}));m.current=s;const x=Ct.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!wa(u.errors,r)},isDirty:{enumerable:!0,get:()=>!!wa(u.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!wa(u.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!wa(u.validatingFields,r)},error:{enumerable:!0,get:()=>wa(u.errors,r)}}),[u,r]),y=Ct.useCallback(N=>f.current.onChange({target:{value:Ilt(N),name:r},type:Cme.CHANGE}),[r]),_=Ct.useCallback(()=>f.current.onBlur({target:{value:wa(a._formValues,r),name:r},type:Cme.BLUR}),[r,a._formValues]),b=Ct.useCallback(N=>{const C=wa(a._fields,r);C&&N&&(C._f.ref={focus:()=>N.focus&&N.focus(),select:()=>N.select&&N.select(),setCustomValidity:A=>N.setCustomValidity(A),reportValidity:()=>N.reportValidity()})},[a._fields,r]),j=Ct.useMemo(()=>({name:r,value:d,...m0(n)||u.disabled?{disabled:u.disabled||n}:{},onChange:y,onBlur:_,ref:b}),[r,n,u.disabled,y,_,b,d]);return Ct.useEffect(()=>{const N=a._options.shouldUnregister||i;a.register(r,{...m.current.rules,...m0(m.current.disabled)?{disabled:m.current.disabled}:{}});const C=(A,E)=>{const D=wa(a._fields,A);D&&D._f&&(D._f.mount=E)};if(C(r,!0),N){const A=rm(wa(a._options.defaultValues,r));cc(a._defaultValues,r,A),nh(wa(a._formValues,r))&&cc(a._formValues,r,A)}return!o&&a.register(r),()=>{(o?N&&!a._state.action:N)?a.unregister(r):C(r,!1)}},[r,a,o,i]),Ct.useEffect(()=>{a._setDisabledField({disabled:n,name:r})},[n,r,a]),Ct.useMemo(()=>({field:j,formState:u,fieldState:x}),[j,u,x])}const qKt=s=>s.render(UKt(s));var Rlt=(s,t,r,n,a)=>t?{...r[s],types:{...r[s]&&r[s].types?r[s].types:{},[n]:a||!0}}:{},v7=s=>Array.isArray(s)?s:[s],Q9e=()=>{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=[]}}},tg=s=>gh(s)&&!Object.keys(s).length,hEe=s=>s.type==="file",g1=s=>typeof s=="function",Tme=s=>{if(!oEe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Olt=s=>s.type==="select-multiple",mEe=s=>s.type==="radio",VKt=s=>mEe(s)||kB(s),f_e=s=>Tme(s)&&s.isConnected;function HKt(s,t){const r=t.slice(0,-1).length;let n=0;for(;n{for(const t in s)if(g1(s[t]))return!0;return!1};function Eme(s,t={}){const r=Array.isArray(s);if(gh(s)||r)for(const n in s)Array.isArray(s[n])||gh(s[n])&&!Flt(s[n])?(t[n]=Array.isArray(s[n])?[]:{},Eme(s[n],t[n])):gx(s[n])||(t[n]=!0);return t}function zlt(s,t,r){const n=Array.isArray(s);if(gh(s)||n)for(const a in s)Array.isArray(s[a])||gh(s[a])&&!Flt(s[a])?nh(t)||Tke(r[a])?r[a]=Array.isArray(s[a])?Eme(s[a],[]):{...Eme(s[a])}:zlt(s[a],gx(t)?{}:t[a],r[a]):r[a]=!Uj(s[a],t[a]);return r}var $R=(s,t)=>zlt(s,t,Eme(t));const J9e={value:!1,isValid:!1},eze={value:!0,isValid:!0};var Blt=s=>{if(Array.isArray(s)){if(s.length>1){const t=s.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:t,isValid:!!t.length}}return s[0].checked&&!s[0].disabled?s[0].attributes&&!nh(s[0].attributes.value)?nh(s[0].value)||s[0].value===""?eze:{value:s[0].value,isValid:!0}:eze:J9e}return J9e},$lt=(s,{valueAsNumber:t,valueAsDate:r,setValueAs:n})=>nh(s)?s:t?s===""?NaN:s&&+s:r&&d_(s)?new Date(s):n?n(s):s;const tze={isValid:!1,value:null};var Ult=s=>Array.isArray(s)?s.reduce((t,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:t,tze):tze;function sze(s){const t=s.ref;return hEe(t)?t.files:mEe(t)?Ult(s.refs).value:Olt(t)?[...t.selectedOptions].map(({value:r})=>r):kB(t)?Blt(s.refs).value:$lt(nh(t.value)?s.ref.value:t.value,s)}var WKt=(s,t,r,n)=>{const a={};for(const i of s){const l=wa(t,i);l&&cc(a,i,l._f)}return{criteriaMode:r,names:[...s],fields:a,shouldUseNativeValidation:n}},Ame=s=>s instanceof RegExp,UR=s=>nh(s)?s:Ame(s)?s.source:gh(s)?Ame(s.value)?s.value.source:s.value:s,rze=s=>({isOnSubmit:!s||s===x1.onSubmit,isOnBlur:s===x1.onBlur,isOnChange:s===x1.onChange,isOnAll:s===x1.all,isOnTouch:s===x1.onTouched});const nze="AsyncFunction";var KKt=s=>!!s&&!!s.validate&&!!(g1(s.validate)&&s.validate.constructor.name===nze||gh(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===nze)),YKt=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),aze=(s,t,r)=>!r&&(t.watchAll||t.watch.has(s)||[...t.watch].some(n=>s.startsWith(n)&&/^\.\w+/.test(s.slice(n.length))));const b7=(s,t,r,n)=>{for(const a of r||Object.keys(s)){const i=wa(s,a);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!n)return!0;if(l.ref&&t(l.ref,l.name)&&!n)return!0;if(b7(o,t))break}else if(gh(o)&&b7(o,t))break}}};function ize(s,t,r){const n=wa(s,r);if(n||Sge(r))return{error:n,name:r};const a=r.split(".");for(;a.length;){const i=a.join("."),l=wa(t,i),o=wa(s,i);if(l&&!Array.isArray(l)&&r!==i)return{name:r};if(o&&o.type)return{name:i,error:o};if(o&&o.root&&o.root.type)return{name:`${i}.root`,error:o.root};a.pop()}return{name:r}}var ZKt=(s,t,r,n)=>{r(s);const{name:a,...i}=s;return tg(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!n||x1.all))},XKt=(s,t,r)=>!s||!t||s===t||v7(s).some(n=>n&&(r?n===t:n.startsWith(t)||t.startsWith(n))),QKt=(s,t,r,n,a)=>a.isOnAll?!1:!r&&a.isOnTouch?!(t||s):(r?n.isOnBlur:a.isOnBlur)?!s:(r?n.isOnChange:a.isOnChange)?s:!0,JKt=(s,t)=>!lEe(wa(s,t)).length&&Th(s,t),eYt=(s,t,r)=>{const n=v7(wa(s,r));return cc(n,"root",t[r]),cc(s,r,n),s},Kue=s=>d_(s);function oze(s,t,r="validate"){if(Kue(s)||Array.isArray(s)&&s.every(Kue)||m0(s)&&!s)return{type:r,message:Kue(s)?s:"",ref:t}}var j6=s=>gh(s)&&!Ame(s)?s:{value:s,message:""},lze=async(s,t,r,n,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:m,max:f,pattern:x,validate:y,name:_,valueAsNumber:b,mount:j}=s._f,N=wa(r,_);if(!j||t.has(_))return{};const C=o?o[0]:l,A=Z=>{a&&C.reportValidity&&(C.setCustomValidity(m0(Z)?"":Z||""),C.reportValidity())},E={},D=mEe(l),R=kB(l),F=D||R,O=(b||hEe(l))&&nh(l.value)&&nh(N)||Tme(l)&&l.value===""||N===""||Array.isArray(N)&&!N.length,B=Rlt.bind(null,_,n,E),K=(Z,Q,W,te=mj.maxLength,ne=mj.minLength)=>{const ae=Z?Q:W;E[_]={type:Z?te:ne,message:ae,ref:l,...B(Z?te:ne,ae)}};if(i?!Array.isArray(N)||!N.length:c&&(!F&&(O||gx(N))||m0(N)&&!N||R&&!Blt(o).isValid||D&&!Ult(o).isValid)){const{value:Z,message:Q}=Kue(c)?{value:!!c,message:c}:j6(c);if(Z&&(E[_]={type:mj.required,message:Q,ref:C,...B(mj.required,Q)},!n))return A(Q),E}if(!O&&(!gx(m)||!gx(f))){let Z,Q;const W=j6(f),te=j6(m);if(!gx(N)&&!isNaN(N)){const ne=l.valueAsNumber||N&&+N;gx(W.value)||(Z=ne>W.value),gx(te.value)||(Q=nenew Date(new Date().toDateString()+" "+de),ue=l.type=="time",me=l.type=="week";d_(W.value)&&N&&(Z=ue?ae(N)>ae(W.value):me?N>W.value:ne>new Date(W.value)),d_(te.value)&&N&&(Q=ue?ae(N)+Z.value,te=!gx(Q.value)&&N.length<+Q.value;if((W||te)&&(K(W,Z.message,Q.message),!n))return A(E[_].message),E}if(x&&!O&&d_(N)){const{value:Z,message:Q}=j6(x);if(Ame(Z)&&!N.match(Z)&&(E[_]={type:mj.pattern,message:Q,ref:l,...B(mj.pattern,Q)},!n))return A(Q),E}if(y){if(g1(y)){const Z=await y(N,r),Q=oze(Z,C);if(Q&&(E[_]={...Q,...B(mj.validate,Q.message)},!n))return A(Q.message),E}else if(gh(y)){let Z={};for(const Q in y){if(!tg(Z)&&!n)break;const W=oze(await y[Q](N,r),C,Q);W&&(Z={...W,...B(Q,W.message)},A(W.message),n&&(E[_]=Z))}if(!tg(Z)&&(E[_]={ref:C,...Z},!n))return E}}return A(!0),E};const tYt={mode:x1.onSubmit,reValidateMode:x1.onChange,shouldFocusError:!0};function sYt(s={}){let t={...tYt,...s},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:g1(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},n={},a=gh(t.defaultValues)||gh(t.values)?rm(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:rm(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 m={...u};const f={array:Q9e(),state:Q9e()},x=t.criteriaMode===x1.all,y=qe=>et=>{clearTimeout(d),d=setTimeout(qe,et)},_=async qe=>{if(!t.disabled&&(u.isValid||m.isValid||qe)){const et=t.resolver?tg((await R()).errors):await O(n,!0);et!==r.isValid&&f.state.next({isValid:et})}},b=(qe,et)=>{!t.disabled&&(u.isValidating||u.validatingFields||m.isValidating||m.validatingFields)&&((qe||Array.from(o.mount)).forEach(Ze=>{Ze&&(et?cc(r.validatingFields,Ze,et):Th(r.validatingFields,Ze))}),f.state.next({validatingFields:r.validatingFields,isValidating:!tg(r.validatingFields)}))},j=(qe,et=[],Ze,rt,ct=!0,vt=!0)=>{if(rt&&Ze&&!t.disabled){if(l.action=!0,vt&&Array.isArray(wa(n,qe))){const kt=Ze(wa(n,qe),rt.argA,rt.argB);ct&&cc(n,qe,kt)}if(vt&&Array.isArray(wa(r.errors,qe))){const kt=Ze(wa(r.errors,qe),rt.argA,rt.argB);ct&&cc(r.errors,qe,kt),JKt(r.errors,qe)}if((u.touchedFields||m.touchedFields)&&vt&&Array.isArray(wa(r.touchedFields,qe))){const kt=Ze(wa(r.touchedFields,qe),rt.argA,rt.argB);ct&&cc(r.touchedFields,qe,kt)}(u.dirtyFields||m.dirtyFields)&&(r.dirtyFields=$R(a,i)),f.state.next({name:qe,isDirty:K(qe,et),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else cc(i,qe,et)},N=(qe,et)=>{cc(r.errors,qe,et),f.state.next({errors:r.errors})},C=qe=>{r.errors=qe,f.state.next({errors:r.errors,isValid:!1})},A=(qe,et,Ze,rt)=>{const ct=wa(n,qe);if(ct){const vt=wa(i,qe,nh(Ze)?wa(a,qe):Ze);nh(vt)||rt&&rt.defaultChecked||et?cc(i,qe,et?vt:sze(ct._f)):W(qe,vt),l.mount&&_()}},E=(qe,et,Ze,rt,ct)=>{let vt=!1,kt=!1;const St={name:qe};if(!t.disabled){if(!Ze||rt){(u.isDirty||m.isDirty)&&(kt=r.isDirty,r.isDirty=St.isDirty=K(),vt=kt!==St.isDirty);const Yt=Uj(wa(a,qe),et);kt=!!wa(r.dirtyFields,qe),Yt?Th(r.dirtyFields,qe):cc(r.dirtyFields,qe,!0),St.dirtyFields=r.dirtyFields,vt=vt||(u.dirtyFields||m.dirtyFields)&&kt!==!Yt}if(Ze){const Yt=wa(r.touchedFields,qe);Yt||(cc(r.touchedFields,qe,Ze),St.touchedFields=r.touchedFields,vt=vt||(u.touchedFields||m.touchedFields)&&Yt!==Ze)}vt&&ct&&f.state.next(St)}return vt?St:{}},D=(qe,et,Ze,rt)=>{const ct=wa(r.errors,qe),vt=(u.isValid||m.isValid)&&m0(et)&&r.isValid!==et;if(t.delayError&&Ze?(c=y(()=>N(qe,Ze)),c(t.delayError)):(clearTimeout(d),c=null,Ze?cc(r.errors,qe,Ze):Th(r.errors,qe)),(Ze?!Uj(ct,Ze):ct)||!tg(rt)||vt){const kt={...rt,...vt&&m0(et)?{isValid:et}:{},errors:r.errors,name:qe};r={...r,...kt},f.state.next(kt)}},R=async qe=>{b(qe,!0);const et=await t.resolver(i,t.context,WKt(qe||o.mount,n,t.criteriaMode,t.shouldUseNativeValidation));return b(qe),et},F=async qe=>{const{errors:et}=await R(qe);if(qe)for(const Ze of qe){const rt=wa(et,Ze);rt?cc(r.errors,Ze,rt):Th(r.errors,Ze)}else r.errors=et;return et},O=async(qe,et,Ze={valid:!0})=>{for(const rt in qe){const ct=qe[rt];if(ct){const{_f:vt,...kt}=ct;if(vt){const St=o.array.has(vt.name),Yt=ct._f&&KKt(ct._f);Yt&&u.validatingFields&&b([rt],!0);const es=await lze(ct,o.disabled,i,x,t.shouldUseNativeValidation&&!et,St);if(Yt&&u.validatingFields&&b([rt]),es[vt.name]&&(Ze.valid=!1,et))break;!et&&(wa(es,vt.name)?St?eYt(r.errors,es,vt.name):cc(r.errors,vt.name,es[vt.name]):Th(r.errors,vt.name))}!tg(kt)&&await O(kt,et,Ze)}}return Ze.valid},B=()=>{for(const qe of o.unMount){const et=wa(n,qe);et&&(et._f.refs?et._f.refs.every(Ze=>!f_e(Ze)):!f_e(et._f.ref))&&Ie(qe)}o.unMount=new Set},K=(qe,et)=>!t.disabled&&(qe&&et&&cc(i,qe,et),!Uj(de(),a)),Z=(qe,et,Ze)=>Dlt(qe,o,{...l.mount?i:nh(et)?a:d_(qe)?{[qe]:et}:et},Ze,et),Q=qe=>lEe(wa(l.mount?i:a,qe,t.shouldUnregister?wa(a,qe,[]):[])),W=(qe,et,Ze={})=>{const rt=wa(n,qe);let ct=et;if(rt){const vt=rt._f;vt&&(!vt.disabled&&cc(i,qe,$lt(et,vt)),ct=Tme(vt.ref)&&gx(et)?"":et,Olt(vt.ref)?[...vt.ref.options].forEach(kt=>kt.selected=ct.includes(kt.value)):vt.refs?kB(vt.ref)?vt.refs.forEach(kt=>{(!kt.defaultChecked||!kt.disabled)&&(Array.isArray(ct)?kt.checked=!!ct.find(St=>St===kt.value):kt.checked=ct===kt.value||!!ct)}):vt.refs.forEach(kt=>kt.checked=kt.value===ct):hEe(vt.ref)?vt.ref.value="":(vt.ref.value=ct,vt.ref.type||f.state.next({name:qe,values:rm(i)})))}(Ze.shouldDirty||Ze.shouldTouch)&&E(qe,ct,Ze.shouldTouch,Ze.shouldDirty,!0),Ze.shouldValidate&&me(qe)},te=(qe,et,Ze)=>{for(const rt in et){if(!et.hasOwnProperty(rt))return;const ct=et[rt],vt=qe+"."+rt,kt=wa(n,vt);(o.array.has(qe)||gh(ct)||kt&&!kt._f)&&!QT(ct)?te(vt,ct,Ze):W(vt,ct,Ze)}},ne=(qe,et,Ze={})=>{const rt=wa(n,qe),ct=o.array.has(qe),vt=rm(et);cc(i,qe,vt),ct?(f.array.next({name:qe,values:rm(i)}),(u.isDirty||u.dirtyFields||m.isDirty||m.dirtyFields)&&Ze.shouldDirty&&f.state.next({name:qe,dirtyFields:$R(a,i),isDirty:K(qe,vt)})):rt&&!rt._f&&!gx(vt)?te(qe,vt,Ze):W(qe,vt,Ze),aze(qe,o)&&f.state.next({...r,name:qe}),f.state.next({name:l.mount?qe:void 0,values:rm(i)})},ae=async qe=>{l.mount=!0;const et=qe.target;let Ze=et.name,rt=!0;const ct=wa(n,Ze),vt=Yt=>{rt=Number.isNaN(Yt)||QT(Yt)&&isNaN(Yt.getTime())||Uj(Yt,wa(i,Ze,Yt))},kt=rze(t.mode),St=rze(t.reValidateMode);if(ct){let Yt,es;const zs=et.type?sze(ct._f):Ilt(qe),sr=qe.type===Cme.BLUR||qe.type===Cme.FOCUS_OUT,ms=!YKt(ct._f)&&!t.resolver&&!wa(r.errors,Ze)&&!ct._f.deps||QKt(sr,wa(r.touchedFields,Ze),r.isSubmitted,St,kt),gt=aze(Ze,o,sr);cc(i,Ze,zs),sr?(ct._f.onBlur&&ct._f.onBlur(qe),c&&c(0)):ct._f.onChange&&ct._f.onChange(qe);const Ut=E(Ze,zs,sr),ht=!tg(Ut)||gt;if(!sr&&f.state.next({name:Ze,type:qe.type,values:rm(i)}),ms)return(u.isValid||m.isValid)&&(t.mode==="onBlur"?sr&&_():sr||_()),ht&&f.state.next({name:Ze,...gt?{}:Ut});if(!sr&>&&f.state.next({...r}),t.resolver){const{errors:Jt}=await R([Ze]);if(vt(zs),rt){const Ms=ize(r.errors,n,Ze),ts=ize(Jt,n,Ms.name||Ze);Yt=ts.error,Ze=ts.name,es=tg(Jt)}}else b([Ze],!0),Yt=(await lze(ct,o.disabled,i,x,t.shouldUseNativeValidation))[Ze],b([Ze]),vt(zs),rt&&(Yt?es=!1:(u.isValid||m.isValid)&&(es=await O(n,!0)));rt&&(ct._f.deps&&me(ct._f.deps),D(Ze,es,Yt,Ut))}},ue=(qe,et)=>{if(wa(r.errors,et)&&qe.focus)return qe.focus(),1},me=async(qe,et={})=>{let Ze,rt;const ct=v7(qe);if(t.resolver){const vt=await F(nh(qe)?qe:ct);Ze=tg(vt),rt=qe?!ct.some(kt=>wa(vt,kt)):Ze}else qe?(rt=(await Promise.all(ct.map(async vt=>{const kt=wa(n,vt);return await O(kt&&kt._f?{[vt]:kt}:kt)}))).every(Boolean),!(!rt&&!r.isValid)&&_()):rt=Ze=await O(n);return f.state.next({...!d_(qe)||(u.isValid||m.isValid)&&Ze!==r.isValid?{}:{name:qe},...t.resolver||!qe?{isValid:Ze}:{},errors:r.errors}),et.shouldFocus&&!rt&&b7(n,ue,qe?ct:o.mount),rt},de=qe=>{const et={...l.mount?i:a};return nh(qe)?et:d_(qe)?wa(et,qe):qe.map(Ze=>wa(et,Ze))},fe=(qe,et)=>({invalid:!!wa((et||r).errors,qe),isDirty:!!wa((et||r).dirtyFields,qe),error:wa((et||r).errors,qe),isValidating:!!wa(r.validatingFields,qe),isTouched:!!wa((et||r).touchedFields,qe)}),je=qe=>{qe&&v7(qe).forEach(et=>Th(r.errors,et)),f.state.next({errors:qe?r.errors:{}})},xe=(qe,et,Ze)=>{const rt=(wa(n,qe,{_f:{}})._f||{}).ref,ct=wa(r.errors,qe)||{},{ref:vt,message:kt,type:St,...Yt}=ct;cc(r.errors,qe,{...Yt,...et,ref:rt}),f.state.next({name:qe,errors:r.errors,isValid:!1}),Ze&&Ze.shouldFocus&&rt&&rt.focus&&rt.focus()},Ee=(qe,et)=>g1(qe)?f.state.subscribe({next:Ze=>"values"in Ze&&qe(Z(void 0,et),Ze)}):Z(qe,et,!0),Me=qe=>f.state.subscribe({next:et=>{XKt(qe.name,et.name,qe.exact)&&ZKt(et,qe.formState||u,Ge,qe.reRenderRoot)&&qe.callback({values:{...i},...r,...et,defaultValues:a})}}).unsubscribe,Oe=qe=>(l.mount=!0,m={...m,...qe.formState},Me({...qe,formState:m})),Ie=(qe,et={})=>{for(const Ze of qe?v7(qe):o.mount)o.mount.delete(Ze),o.array.delete(Ze),et.keepValue||(Th(n,Ze),Th(i,Ze)),!et.keepError&&Th(r.errors,Ze),!et.keepDirty&&Th(r.dirtyFields,Ze),!et.keepTouched&&Th(r.touchedFields,Ze),!et.keepIsValidating&&Th(r.validatingFields,Ze),!t.shouldUnregister&&!et.keepDefaultValue&&Th(a,Ze);f.state.next({values:rm(i)}),f.state.next({...r,...et.keepDirty?{isDirty:K()}:{}}),!et.keepIsValid&&_()},ze=({disabled:qe,name:et})=>{(m0(qe)&&l.mount||qe||o.disabled.has(et))&&(qe?o.disabled.add(et):o.disabled.delete(et))},Ve=(qe,et={})=>{let Ze=wa(n,qe);const rt=m0(et.disabled)||m0(t.disabled);return cc(n,qe,{...Ze||{},_f:{...Ze&&Ze._f?Ze._f:{ref:{name:qe}},name:qe,mount:!0,...et}}),o.mount.add(qe),Ze?ze({disabled:m0(et.disabled)?et.disabled:t.disabled,name:qe}):A(qe,!0,et.value),{...rt?{disabled:et.disabled||t.disabled}:{},...t.progressive?{required:!!et.required,min:UR(et.min),max:UR(et.max),minLength:UR(et.minLength),maxLength:UR(et.maxLength),pattern:UR(et.pattern)}:{},name:qe,onChange:ae,onBlur:ae,ref:ct=>{if(ct){Ve(qe,et),Ze=wa(n,qe);const vt=nh(ct.value)&&ct.querySelectorAll&&ct.querySelectorAll("input,select,textarea")[0]||ct,kt=VKt(vt),St=Ze._f.refs||[];if(kt?St.find(Yt=>Yt===vt):vt===Ze._f.ref)return;cc(n,qe,{_f:{...Ze._f,...kt?{refs:[...St.filter(f_e),vt,...Array.isArray(wa(a,qe))?[{}]:[]],ref:{type:vt.type,name:qe}}:{ref:vt}}}),A(qe,!1,void 0,vt)}else Ze=wa(n,qe,{}),Ze._f&&(Ze._f.mount=!1),(t.shouldUnregister||et.shouldUnregister)&&!(Plt(o.array,qe)&&l.action)&&o.unMount.add(qe)}}},Le=()=>t.shouldFocusError&&b7(n,ue,o.mount),$e=qe=>{m0(qe)&&(f.state.next({disabled:qe}),b7(n,(et,Ze)=>{const rt=wa(n,Ze);rt&&(et.disabled=rt._f.disabled||qe,Array.isArray(rt._f.refs)&&rt._f.refs.forEach(ct=>{ct.disabled=rt._f.disabled||qe}))},0,!1))},ve=(qe,et)=>async Ze=>{let rt;Ze&&(Ze.preventDefault&&Ze.preventDefault(),Ze.persist&&Ze.persist());let ct=rm(i);if(f.state.next({isSubmitting:!0}),t.resolver){const{errors:vt,values:kt}=await R();r.errors=vt,ct=rm(kt)}else await O(n);if(o.disabled.size)for(const vt of o.disabled)Th(ct,vt);if(Th(r.errors,"root"),tg(r.errors)){f.state.next({errors:{}});try{await qe(ct,Ze)}catch(vt){rt=vt}}else et&&await et({...r.errors},Ze),Le(),setTimeout(Le);if(f.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:tg(r.errors)&&!rt,submitCount:r.submitCount+1,errors:r.errors}),rt)throw rt},Qe=(qe,et={})=>{wa(n,qe)&&(nh(et.defaultValue)?ne(qe,rm(wa(a,qe))):(ne(qe,et.defaultValue),cc(a,qe,rm(et.defaultValue))),et.keepTouched||Th(r.touchedFields,qe),et.keepDirty||(Th(r.dirtyFields,qe),r.isDirty=et.defaultValue?K(qe,rm(wa(a,qe))):K()),et.keepError||(Th(r.errors,qe),u.isValid&&_()),f.state.next({...r}))},we=(qe,et={})=>{const Ze=qe?rm(qe):a,rt=rm(Ze),ct=tg(qe),vt=ct?a:rt;if(et.keepDefaultValues||(a=Ze),!et.keepValues){if(et.keepDirtyValues){const kt=new Set([...o.mount,...Object.keys($R(a,i))]);for(const St of Array.from(kt))wa(r.dirtyFields,St)?cc(vt,St,wa(i,St)):ne(St,wa(vt,St))}else{if(oEe&&nh(qe))for(const kt of o.mount){const St=wa(n,kt);if(St&&St._f){const Yt=Array.isArray(St._f.refs)?St._f.refs[0]:St._f.ref;if(Tme(Yt)){const es=Yt.closest("form");if(es){es.reset();break}}}}if(et.keepFieldsRef)for(const kt of o.mount)ne(kt,wa(vt,kt));else n={}}i=t.shouldUnregister?et.keepDefaultValues?rm(a):{}:rm(vt),f.array.next({values:{...vt}}),f.state.next({values:{...vt}})}o={mount:et.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!u.isValid||!!et.keepIsValid||!!et.keepDirtyValues,l.watch=!!t.shouldUnregister,f.state.next({submitCount:et.keepSubmitCount?r.submitCount:0,isDirty:ct?!1:et.keepDirty?r.isDirty:!!(et.keepDefaultValues&&!Uj(qe,a)),isSubmitted:et.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:ct?{}:et.keepDirtyValues?et.keepDefaultValues&&i?$R(a,i):r.dirtyFields:et.keepDefaultValues&&qe?$R(a,qe):et.keepDirty?r.dirtyFields:{},touchedFields:et.keepTouched?r.touchedFields:{},errors:et.keepErrors?r.errors:{},isSubmitSuccessful:et.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},nt=(qe,et)=>we(g1(qe)?qe(i):qe,et),Se=(qe,et={})=>{const Ze=wa(n,qe),rt=Ze&&Ze._f;if(rt){const ct=rt.refs?rt.refs[0]:rt.ref;ct.focus&&(ct.focus(),et.shouldSelect&&g1(ct.select)&&ct.select())}},Ge=qe=>{r={...r,...qe}},Ce={control:{register:Ve,unregister:Ie,getFieldState:fe,handleSubmit:ve,setError:xe,_subscribe:Me,_runSchema:R,_focusError:Le,_getWatch:Z,_getDirty:K,_setValid:_,_setFieldArray:j,_setDisabledField:ze,_setErrors:C,_getFieldArray:Q,_reset:we,_resetDefaultValues:()=>g1(t.defaultValues)&&t.defaultValues().then(qe=>{nt(qe,t.resetOptions),f.state.next({isLoading:!1})}),_removeUnmounted:B,_disableForm:$e,_subjects:f,_proxyFormState:u,get _fields(){return n},get _formValues(){return i},get _state(){return l},set _state(qe){l=qe},get _defaultValues(){return a},get _names(){return o},set _names(qe){o=qe},get _formState(){return r},get _options(){return t},set _options(qe){t={...t,...qe}}},subscribe:Oe,trigger:me,register:Ve,handleSubmit:ve,watch:Ee,setValue:ne,getValues:de,reset:nt,resetField:Qe,clearErrors:je,unregister:Ie,setError:xe,setFocus:Se,getFieldState:fe};return{...Ce,formControl:Ce}}function Tge(s={}){const t=Ct.useRef(void 0),r=Ct.useRef(void 0),[n,a]=Ct.useState({isDirty:!1,isValidating:!1,isLoading:g1(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:g1(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:n},s.defaultValues&&!g1(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=sYt(s);t.current={...o,formState:n}}const i=t.current.control;return i._options=s,uEe(()=>{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!==n.isDirty&&i._subjects.state.next({isDirty:l})}},[i,n.isDirty]),Ct.useEffect(()=>{s.values&&!Uj(s.values,r.current)?(i._reset(s.values,{keepFieldsRef:!0,...i._options.resetOptions}),r.current=s.values,a(l=>({...l}))):i._resetDefaultValues()},[i,s.values]),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=Llt(n,i),t.current}const cze=(s,t,r)=>{if(s&&"reportValidity"in s){const n=wa(r,t);s.setCustomValidity(n&&n.message||""),s.reportValidity()}},qlt=(s,t)=>{for(const r in t.fields){const n=t.fields[r];n&&n.ref&&"reportValidity"in n.ref?cze(n.ref,r,s):n.refs&&n.refs.forEach(a=>cze(a,r,s))}},rYt=(s,t)=>{t.shouldUseNativeValidation&&qlt(s,t);const r={};for(const n in s){const a=wa(t.fields,n),i=Object.assign(s[n]||{},{ref:a&&a.ref});if(nYt(t.names||Object.keys(s),n)){const l=Object.assign({},wa(r,n));cc(l,"root",i),cc(r,n,l)}else cc(r,n,i)}return r},nYt=(s,t)=>s.some(r=>r.startsWith(t+"."));var aYt=function(s,t){for(var r={};s.length;){var n=s[0],a=n.code,i=n.message,l=n.path.join(".");if(!r[l])if("unionErrors"in n){var o=n.unionErrors[0].errors[0];r[l]={message:o.message,type:o.code}}else r[l]={message:i,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(u){return u.errors.forEach(function(m){return s.push(m)})}),t){var c=r[l].types,d=c&&c[n.code];r[l]=Rlt(l,t,r,a,d?[].concat(d,n.message):n.message)}s.shift()}return r},Ege=function(s,t,r){return r===void 0&&(r={}),function(n,a,i){try{return Promise.resolve(function(l,o){try{var c=Promise.resolve(s[r.mode==="sync"?"parse":"parseAsync"](n,t)).then(function(d){return i.shouldUseNativeValidation&&qlt({},i),{errors:{},values:r.raw?n:d}})}catch(d){return o(d)}return c&&c.then?c.then(void 0,o):c}(0,function(l){if(function(o){return Array.isArray(o==null?void 0:o.errors)}(l))return{values:{},errors:rYt(aYt(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const Age=zKt,Vlt=k.createContext({}),au=({...s})=>e.jsx(Vlt.Provider,{value:{name:s.name},children:e.jsx(qKt,{...s})}),Mge=()=>{const s=k.useContext(Vlt),t=k.useContext(Hlt),{getFieldState:r,formState:n}=Cge(),a=r(s.name,n);if(!s)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:s.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...a}},Hlt=k.createContext({}),zd=k.forwardRef(({className:s,...t},r)=>{const n=k.useId();return e.jsx(Hlt.Provider,{value:{id:n},children:e.jsx("div",{ref:r,className:zt("space-y-2",s),...t})})});zd.displayName="FormItem";const Bd=k.forwardRef(({className:s,...t},r)=>{const{error:n,formItemId:a}=Mge();return e.jsx(ce,{ref:r,className:zt(n&&"text-destructive",s),htmlFor:a,...t})});Bd.displayName="FormLabel";const $d=k.forwardRef(({...s},t)=>{const{error:r,formItemId:n,formDescriptionId:a,formMessageId:i}=Mge();return e.jsx(i5e,{ref:t,id:n,"aria-describedby":r?`${a} ${i}`:`${a}`,"aria-invalid":!!r,...s})});$d.displayName="FormControl";const Yue=k.forwardRef(({className:s,...t},r)=>{const{formDescriptionId:n}=Mge();return e.jsx("p",{ref:r,id:n,className:zt("text-sm text-muted-foreground",s),...t})});Yue.displayName="FormDescription";const wx=k.forwardRef(({className:s,children:t,...r},n)=>{const{error:a,formMessageId:i}=Mge(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:n,id:i,className:zt("text-sm font-medium text-destructive",s),...r,children:l}):null});wx.displayName="FormMessage";const iYt=tw({category:_Te(["general","technology","crm","marketing"]),subject:ho().min(5,"Subject must be at least 5 characters").max(200),description:ho().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),oYt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Eke({trigger:s}){const[t,r]=k.useState(!1),[n,a]=k.useState(!1),{user:i}=Cs(),l=Tge({resolver:Ege(iYt),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){he.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await U.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await U.functions.invoke("support-ticket-notify",{body:{category:oYt[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}he.success("Support ticket submitted successfully!"),l.reset(),r(!1)}catch(d){console.error("Error submitting ticket:",d),he.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(vs,{open:t,onOpenChange:r,children:[e.jsx(Yi,{asChild:!0,children:s||e.jsxs(q,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(DF,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(ys,{className:"sm:max-w-[500px]",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Need Help?"}),e.jsx(an,{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(Mn,{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(Age,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(au,{control:l.control,name:"category",render:({field:c})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Category"}),e.jsxs(Ds,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx($d,{children:e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a category"})})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"general",children:"General Support"}),e.jsx(lt,{value:"technology",children:"Technology Support"}),e.jsx(lt,{value:"crm",children:"CRM Support"}),e.jsx(lt,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(wx,{})]})}),e.jsx(au,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Subject"}),e.jsx($d,{children:e.jsx(Ne,{placeholder:"Brief description of your issue",...c})}),e.jsx(wx,{})]})}),e.jsx(au,{control:l.control,name:"description",render:({field:c})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Description"}),e.jsx($d,{children:e.jsx(pr,{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(q,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}const lYt=()=>{const{user:s}=Cs(),t=qr(),[r,n]=k.useState([]),[a,i]=k.useState(0),[l,o]=k.useState(!1),[c,d]=k.useState(null),u=k.useRef(null);k.useEffect(()=>{u.current=c},[c]),k.useEffect(()=>{if(!s)return;const _=`notification_last_read_${s.id}`,b=localStorage.getItem(_);b&&!u.current&&(u.current=b,d(b));const j=`nb_cache_${s.id}`,N=60*1e3,C=async()=>{try{const F=sessionStorage.getItem(j);if(F){const O=JSON.parse(F);if(O.ts&&Date.now()-O.ts{n(D);const R=u.current?new Date(u.current):null,F=D.filter(O=>R?new Date(O.created_at)>R:!0);i(F.length)};C();const E=U.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},D=>{const R=D.new;n(O=>{const B=[R,...O].slice(0,20);try{sessionStorage.setItem(j,JSON.stringify({ts:Date.now(),data:B}))}catch{}return B});const F=u.current?new Date(u.current):null;(!F||new Date(R.created_at)>F)&&i(O=>O+1),Notification.permission==="granted"&&new Notification(R.title,{body:R.body,icon:"/favicon.ico"})}).subscribe();return()=>{U.removeChannel(E)}},[s]);const m=_=>{const b=_.toLowerCase();return b.includes("community")||b.includes("post")?Ui:b.includes("academy")||b.includes("video")?bn:b.includes("template")?dl:b.includes("event")?vn:b.includes("newsletter")?E1:b.includes("brokerage")?bm:b.includes("swag")||b.includes("social")?Di:b.includes("toolbox")||b.includes("tool")?A_:b.includes("brief")?Ir:Ui},f=_=>{o(!1),_.url&&_.url!=="/"&&t(_.url)},x=()=>{if(!s)return;const _=new Date().toISOString(),b=`notification_last_read_${s.id}`;localStorage.setItem(b,_),d(_),i(0)},y=_=>{o(_),_&&a>0&&x()};return e.jsxs(Gd,{open:l,onOpenChange:y,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(ym,{className:"h-5 w-5"}),a>0&&e.jsx(Xe,{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(Sd,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&e.jsx(q,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:x,children:"Mark all read"})]}),e.jsx(ui,{className:"h-[300px]",children:r.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(_=>{const b=m(_.title);return e.jsxs(ti,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>f(_),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(b,{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:Nl(new Date(_.created_at),{addSuffix:!0})})]})]},_.id)})})]})]})};var dze=1,cYt=.9,dYt=.8,uYt=.17,p_e=.1,x_e=.999,hYt=.9999,mYt=.99,fYt=/[\\\/_+.#"@\[\(\{&]/,pYt=/[\\\/_+.#"@\[\(\{&]/g,xYt=/[\s-]/,Glt=/[\s-]/g;function Ake(s,t,r,n,a,i,l){if(i===t.length)return a===s.length?dze:mYt;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=n.charAt(i),d=r.indexOf(c,a),u=0,m,f,x,y;d>=0;)m=Ake(s,t,r,n,d+1,i+1,l),m>u&&(d===a?m*=dze:fYt.test(s.charAt(d-1))?(m*=dYt,x=s.slice(a,d-1).match(pYt),x&&a>0&&(m*=Math.pow(x_e,x.length))):xYt.test(s.charAt(d-1))?(m*=cYt,y=s.slice(a,d-1).match(Glt),y&&a>0&&(m*=Math.pow(x_e,y.length))):(m*=uYt,a>0&&(m*=Math.pow(x_e,d-a))),s.charAt(d)!==t.charAt(i)&&(m*=hYt)),(mm&&(m=f*p_e)),m>u&&(u=m),d=r.indexOf(c,d+1);return l[o]=u,u}function uze(s){return s.toLowerCase().replace(Glt," ")}function gYt(s,t,r){return s=r&&r.length>0?`${s+" "+r.join(" ")}`:s,Ake(s,t,uze(s),uze(t),0,0,{})}var qR='[cmdk-group=""]',g_e='[cmdk-group-items=""]',yYt='[cmdk-group-heading=""]',Wlt='[cmdk-item=""]',hze=`${Wlt}:not([aria-disabled="true"])`,Mke="cmdk-item-select",J6="data-value",vYt=(s,t,r)=>gYt(s,t,r),Klt=k.createContext(void 0),SB=()=>k.useContext(Klt),Ylt=k.createContext(void 0),fEe=()=>k.useContext(Ylt),Zlt=k.createContext(void 0),Xlt=k.forwardRef((s,t)=>{let r=eI(()=>{var je,xe;return{search:"",value:(xe=(je=s.value)!=null?je:s.defaultValue)!=null?xe:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=eI(()=>new Set),a=eI(()=>new Map),i=eI(()=>new Map),l=eI(()=>new Set),o=Qlt(s),{label:c,children:d,value:u,onValueChange:m,filter:f,shouldFilter:x,loop:y,disablePointerSelection:_=!1,vimBindings:b=!0,...j}=s,N=jm(),C=jm(),A=jm(),E=k.useRef(null),D=AYt();jA(()=>{if(u!==void 0){let je=u.trim();r.current.value=je,R.emit()}},[u]),jA(()=>{D(6,Q)},[]);let R=k.useMemo(()=>({subscribe:je=>(l.current.add(je),()=>l.current.delete(je)),snapshot:()=>r.current,setState:(je,xe,Ee)=>{var Me,Oe,Ie,ze;if(!Object.is(r.current[je],xe)){if(r.current[je]=xe,je==="search")Z(),B(),D(1,K);else if(je==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Ve=document.getElementById(A);Ve?Ve.focus():(Me=document.getElementById(N))==null||Me.focus()}if(D(7,()=>{var Ve;r.current.selectedItemId=(Ve=W())==null?void 0:Ve.id,R.emit()}),Ee||D(5,Q),((Oe=o.current)==null?void 0:Oe.value)!==void 0){let Ve=xe??"";(ze=(Ie=o.current).onValueChange)==null||ze.call(Ie,Ve);return}}R.emit()}},emit:()=>{l.current.forEach(je=>je())}}),[]),F=k.useMemo(()=>({value:(je,xe,Ee)=>{var Me;xe!==((Me=i.current.get(je))==null?void 0:Me.value)&&(i.current.set(je,{value:xe,keywords:Ee}),r.current.filtered.items.set(je,O(xe,Ee)),D(2,()=>{B(),R.emit()}))},item:(je,xe)=>(n.current.add(je),xe&&(a.current.has(xe)?a.current.get(xe).add(je):a.current.set(xe,new Set([je]))),D(3,()=>{Z(),B(),r.current.value||K(),R.emit()}),()=>{i.current.delete(je),n.current.delete(je),r.current.filtered.items.delete(je);let Ee=W();D(4,()=>{Z(),(Ee==null?void 0:Ee.getAttribute("id"))===je&&K(),R.emit()})}),group:je=>(a.current.has(je)||a.current.set(je,new Set),()=>{i.current.delete(je),a.current.delete(je)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:N,inputId:A,labelId:C,listInnerRef:E}),[]);function O(je,xe){var Ee,Me;let Oe=(Me=(Ee=o.current)==null?void 0:Ee.filter)!=null?Me:vYt;return je?Oe(je,r.current.search,xe):0}function B(){if(!r.current.search||o.current.shouldFilter===!1)return;let je=r.current.filtered.items,xe=[];r.current.filtered.groups.forEach(Me=>{let Oe=a.current.get(Me),Ie=0;Oe.forEach(ze=>{let Ve=je.get(ze);Ie=Math.max(Ve,Ie)}),xe.push([Me,Ie])});let Ee=E.current;te().sort((Me,Oe)=>{var Ie,ze;let Ve=Me.getAttribute("id"),Le=Oe.getAttribute("id");return((Ie=je.get(Le))!=null?Ie:0)-((ze=je.get(Ve))!=null?ze:0)}).forEach(Me=>{let Oe=Me.closest(g_e);Oe?Oe.appendChild(Me.parentElement===Oe?Me:Me.closest(`${g_e} > *`)):Ee.appendChild(Me.parentElement===Ee?Me:Me.closest(`${g_e} > *`))}),xe.sort((Me,Oe)=>Oe[1]-Me[1]).forEach(Me=>{var Oe;let Ie=(Oe=E.current)==null?void 0:Oe.querySelector(`${qR}[${J6}="${encodeURIComponent(Me[0])}"]`);Ie==null||Ie.parentElement.appendChild(Ie)})}function K(){let je=te().find(Ee=>Ee.getAttribute("aria-disabled")!=="true"),xe=je==null?void 0:je.getAttribute(J6);R.setState("value",xe||void 0)}function Z(){var je,xe,Ee,Me;if(!r.current.search||o.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let Oe=0;for(let Ie of n.current){let ze=(xe=(je=i.current.get(Ie))==null?void 0:je.value)!=null?xe:"",Ve=(Me=(Ee=i.current.get(Ie))==null?void 0:Ee.keywords)!=null?Me:[],Le=O(ze,Ve);r.current.filtered.items.set(Ie,Le),Le>0&&Oe++}for(let[Ie,ze]of a.current)for(let Ve of ze)if(r.current.filtered.items.get(Ve)>0){r.current.filtered.groups.add(Ie);break}r.current.filtered.count=Oe}function Q(){var je,xe,Ee;let Me=W();Me&&(((je=Me.parentElement)==null?void 0:je.firstChild)===Me&&((Ee=(xe=Me.closest(qR))==null?void 0:xe.querySelector(yYt))==null||Ee.scrollIntoView({block:"nearest"})),Me.scrollIntoView({block:"nearest"}))}function W(){var je;return(je=E.current)==null?void 0:je.querySelector(`${Wlt}[aria-selected="true"]`)}function te(){var je;return Array.from(((je=E.current)==null?void 0:je.querySelectorAll(hze))||[])}function ne(je){let xe=te()[je];xe&&R.setState("value",xe.getAttribute(J6))}function ae(je){var xe;let Ee=W(),Me=te(),Oe=Me.findIndex(ze=>ze===Ee),Ie=Me[Oe+je];(xe=o.current)!=null&&xe.loop&&(Ie=Oe+je<0?Me[Me.length-1]:Oe+je===Me.length?Me[0]:Me[Oe+je]),Ie&&R.setState("value",Ie.getAttribute(J6))}function ue(je){let xe=W(),Ee=xe==null?void 0:xe.closest(qR),Me;for(;Ee&&!Me;)Ee=je>0?TYt(Ee,qR):EYt(Ee,qR),Me=Ee==null?void 0:Ee.querySelector(hze);Me?R.setState("value",Me.getAttribute(J6)):ae(je)}let me=()=>ne(te().length-1),de=je=>{je.preventDefault(),je.metaKey?me():je.altKey?ue(1):ae(1)},fe=je=>{je.preventDefault(),je.metaKey?ne(0):je.altKey?ue(-1):ae(-1)};return k.createElement(Yn.div,{ref:t,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:je=>{var xe;(xe=j.onKeyDown)==null||xe.call(j,je);let Ee=je.nativeEvent.isComposing||je.keyCode===229;if(!(je.defaultPrevented||Ee))switch(je.key){case"n":case"j":{b&&je.ctrlKey&&de(je);break}case"ArrowDown":{de(je);break}case"p":case"k":{b&&je.ctrlKey&&fe(je);break}case"ArrowUp":{fe(je);break}case"Home":{je.preventDefault(),ne(0);break}case"End":{je.preventDefault(),me();break}case"Enter":{je.preventDefault();let Me=W();if(Me){let Oe=new Event(Mke);Me.dispatchEvent(Oe)}}}}},k.createElement("label",{"cmdk-label":"",htmlFor:F.inputId,id:F.labelId,style:IYt},c),Ige(s,je=>k.createElement(Ylt.Provider,{value:R},k.createElement(Klt.Provider,{value:F},je))))}),bYt=k.forwardRef((s,t)=>{var r,n;let a=jm(),i=k.useRef(null),l=k.useContext(Zlt),o=SB(),c=Qlt(s),d=(n=(r=c.current)==null?void 0:r.forceMount)!=null?n:l==null?void 0:l.forceMount;jA(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=Jlt(a,i,[s.value,s.children,i],s.keywords),m=fEe(),f=OS(D=>D.value&&D.value===u.current),x=OS(D=>d||o.filter()===!1?!0:D.search?D.filtered.items.get(a)>0:!0);k.useEffect(()=>{let D=i.current;if(!(!D||s.disabled))return D.addEventListener(Mke,y),()=>D.removeEventListener(Mke,y)},[x,s.onSelect,s.disabled]);function y(){var D,R;_(),(R=(D=c.current).onSelect)==null||R.call(D,u.current)}function _(){m.setState("value",u.current,!0)}if(!x)return null;let{disabled:b,value:j,onSelect:N,forceMount:C,keywords:A,...E}=s;return k.createElement(Yn.div,{ref:N2(i,t),...E,id:a,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!f,"data-disabled":!!b,"data-selected":!!f,onPointerMove:b||o.getDisablePointerSelection()?void 0:_,onClick:b?void 0:y},s.children)}),_Yt=k.forwardRef((s,t)=>{let{heading:r,children:n,forceMount:a,...i}=s,l=jm(),o=k.useRef(null),c=k.useRef(null),d=jm(),u=SB(),m=OS(x=>a||u.filter()===!1?!0:x.search?x.filtered.groups.has(l):!0);jA(()=>u.group(l),[]),Jlt(l,o,[s.value,s.heading,c]);let f=k.useMemo(()=>({id:l,forceMount:a}),[a]);return k.createElement(Yn.div,{ref:N2(o,t),...i,"cmdk-group":"",role:"presentation",hidden:m?void 0:!0},r&&k.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},r),Ige(s,x=>k.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?d:void 0},k.createElement(Zlt.Provider,{value:f},x))))}),wYt=k.forwardRef((s,t)=>{let{alwaysRender:r,...n}=s,a=k.useRef(null),i=OS(l=>!l.search);return!r&&!i?null:k.createElement(Yn.div,{ref:N2(a,t),...n,"cmdk-separator":"",role:"separator"})}),jYt=k.forwardRef((s,t)=>{let{onValueChange:r,...n}=s,a=s.value!=null,i=fEe(),l=OS(d=>d.search),o=OS(d=>d.selectedItemId),c=SB();return k.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),k.createElement(Yn.input,{ref:t,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":o,id:c.inputId,type:"text",value:a?s.value:l,onChange:d=>{a||i.setState("search",d.target.value),r==null||r(d.target.value)}})}),NYt=k.forwardRef((s,t)=>{let{children:r,label:n="Suggestions",...a}=s,i=k.useRef(null),l=k.useRef(null),o=OS(d=>d.selectedItemId),c=SB();return k.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,m,f=new ResizeObserver(()=>{m=requestAnimationFrame(()=>{let x=d.offsetHeight;u.style.setProperty("--cmdk-list-height",x.toFixed(1)+"px")})});return f.observe(d),()=>{cancelAnimationFrame(m),f.unobserve(d)}}},[]),k.createElement(Yn.div,{ref:N2(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":n,id:c.listId},Ige(s,d=>k.createElement("div",{ref:N2(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),kYt=k.forwardRef((s,t)=>{let{open:r,onOpenChange:n,overlayClassName:a,contentClassName:i,container:l,...o}=s;return k.createElement(Gxe,{open:r,onOpenChange:n},k.createElement(Wxe,{container:l},k.createElement(w8,{"cmdk-overlay":"",className:a}),k.createElement(j8,{"aria-label":s.label,"cmdk-dialog":"",className:i},k.createElement(Xlt,{ref:t,...o}))))}),SYt=k.forwardRef((s,t)=>OS(r=>r.filtered.count===0)?k.createElement(Yn.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),CYt=k.forwardRef((s,t)=>{let{progress:r,children:n,label:a="Loading...",...i}=s;return k.createElement(Yn.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},Ige(s,l=>k.createElement("div",{"aria-hidden":!0},l)))}),Eg=Object.assign(Xlt,{List:NYt,Item:bYt,Input:jYt,Group:_Yt,Separator:wYt,Dialog:kYt,Empty:SYt,Loading:CYt});function TYt(s,t){let r=s.nextElementSibling;for(;r;){if(r.matches(t))return r;r=r.nextElementSibling}}function EYt(s,t){let r=s.previousElementSibling;for(;r;){if(r.matches(t))return r;r=r.previousElementSibling}}function Qlt(s){let t=k.useRef(s);return jA(()=>{t.current=s}),t}var jA=typeof window>"u"?k.useEffect:k.useLayoutEffect;function eI(s){let t=k.useRef();return t.current===void 0&&(t.current=s()),t}function OS(s){let t=fEe(),r=()=>s(t.snapshot());return k.useSyncExternalStore(t.subscribe,r,r)}function Jlt(s,t,r,n=[]){let a=k.useRef(),i=SB();return jA(()=>{var l;let o=(()=>{var d;for(let u of r){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=n.map(d=>d.trim());i.value(s,o,c),(l=t.current)==null||l.setAttribute(J6,o),a.current=o}),a}var AYt=()=>{let[s,t]=k.useState(),r=eI(()=>new Map);return jA(()=>{r.current.forEach(n=>n()),r.current=new Map},[s]),(n,a)=>{r.current.set(n,a),t({})}};function MYt(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function Ige({asChild:s,children:t},r){return s&&k.isValidElement(t)?k.cloneElement(MYt(t),{ref:t.ref},r(t.props.children)):r(t)}var IYt={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const jg=k.forwardRef(({className:s,...t},r)=>e.jsx(Eg,{ref:r,className:zt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));jg.displayName=Eg.displayName;const PYt=({children:s,...t})=>e.jsx(vs,{...t,children:e.jsx(ys,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(jg,{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})})}),Ng=k.forwardRef(({className:s,...t},r)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(_n,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Eg.Input,{ref:r,className:zt("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})]}));Ng.displayName=Eg.Input.displayName;const kg=k.forwardRef(({className:s,...t},r)=>e.jsx(Eg.List,{ref:r,className:zt("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));kg.displayName=Eg.List.displayName;const Sg=k.forwardRef((s,t)=>e.jsx(Eg.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));Sg.displayName=Eg.Empty.displayName;const Cg=k.forwardRef(({className:s,...t},r)=>e.jsx(Eg.Group,{ref:r,className:zt("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}));Cg.displayName=Eg.Group.displayName;const LYt=k.forwardRef(({className:s,...t},r)=>e.jsx(Eg.Separator,{ref:r,className:zt("-mx-1 h-px bg-border",s),...t}));LYt.displayName=Eg.Separator.displayName;const Sp=k.forwardRef(({className:s,...t},r)=>e.jsx(Eg.Item,{ref:r,className:zt("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}));Sp.displayName=Eg.Item.displayName;const DYt={event:{label:"Events",icon:xu,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:dl,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:ch,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:A_,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:Ir,color:"bg-fuchsia-500/10 text-fuchsia-600"}},mze=()=>{const[s,t]=k.useState(!1),[r,n]=k.useState(""),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=qr();k.useEffect(()=>{const f=x=>{x.key==="k"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),t(y=>!y))};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[]);const d=k.useCallback(async f=>{if(!f.trim()){i([]);return}o(!0);const x=`%${f}%`;try{const[y,_,b,j,N]=await Promise.all([U.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${x},description.ilike.${x}`).limit(5),U.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${x},description.ilike.${x}`).limit(5),U.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${x},description.ilike.${x}`).limit(5),U.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${x},description.ilike.${x}`).limit(5),U.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${x},description.ilike.${x}`).limit(5)]),C=[];y.data&&y.data.forEach(A=>{C.push({id:A.id,title:A.title,description:A.description,type:"event",date:A.event_date,path:`/event/${A.id}`})}),_.data&&_.data.forEach(A=>{C.push({id:A.id,title:A.name,description:A.description,type:"template",date:A.publish_date,path:`/templates/${A.id}`})}),b.data&&b.data.forEach(A=>{C.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=>{C.push({id:A.id,title:A.name,description:A.description,type:"toolbox",date:A.publish_date,path:`/toolbox/${A.id}`})}),N.data&&N.data.forEach(A=>{C.push({id:A.id,title:A.title,description:A.description,type:"social-swag",date:A.publish_date,path:`/social-swag/${A.id}`})}),i(C)}catch(y){console.error("Search error:",y)}finally{o(!1)}},[]);k.useEffect(()=>{const f=setTimeout(()=>{d(r)},300);return()=>clearTimeout(f)},[r,d]);const u=f=>{t(!1),n(""),c(f)},m=a.reduce((f,x)=>(f[x.type]||(f[x.type]=[]),f[x.type].push(x),f),{});return e.jsxs(e.Fragment,{children:[e.jsxs(q,{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(_n,{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(PYt,{open:s,onOpenChange:t,children:[e.jsx(Ng,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:r,onValueChange:n}),e.jsxs(kg,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&r&&a.length===0&&e.jsxs(Sg,{children:['No results found for "',r,'"']}),!l&&!r&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search across all content..."}),Object.entries(m).map(([f,x])=>{const y=DYt[f],_=y.icon;return e.jsx(Cg,{heading:y.label,children:x.map(b=>e.jsxs(Sp,{value:`${b.type}-${b.id}-${b.title}`,onSelect:()=>u(b.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:b.title}),b.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:b.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(Xe,{variant:"secondary",className:"text-xs",children:y.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Nl(new Date(b.date),{addSuffix:!0})})]})]},`${b.type}-${b.id}`))},f)})]})]})]})},RYt=({expiresAt:s,className:t,showUpgradeButton:r=!0})=>{const[n,a]=k.useState(null),i=qr();if(k.useEffect(()=>{const d=()=>{const m=new Date().getTime(),x=new Date(s).getTime()-m;if(x<=0){a({days:0,hours:0,minutes:0});return}const y=Math.floor(x/(1e3*60*60*24)),_=Math.floor(x%(1e3*60*60*24)/(1e3*60*60)),b=Math.floor(x%(1e3*60*60)/(1e3*60));a({days:y,hours:_,minutes:b})};d();const u=setInterval(d,6e4);return()=>clearInterval(u)},[s]),!n)return null;const l=n.days===0&&n.hours===0&&n.minutes===0,o=n.days<=1,c=n.days<=3&&!o;return l?e.jsxs("div",{className:zt("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(du,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),r&&e.jsxs(q,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:zt("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(jn,{className:zt("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:zt("text-sm font-medium",o?"text-destructive":c?"text-amber-600":"text-primary"),children:"Free Trial:"}),e.jsxs("div",{className:"flex items-center gap-1",children:[n.days>0&&e.jsxs("span",{className:zt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.days,"d"]}),e.jsxs("span",{className:zt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),e.jsxs("span",{className:zt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),e.jsx("span",{className:zt("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&e.jsxs(q,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:zt("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},OYt=()=>{const s=qr();return e.jsx("div",{className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto",children:e.jsxs(ke,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Pt,{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(du,{className:"h-8 w-8 text-destructive"})}),e.jsx(Dt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Ur,{className:"text-base",children:"Your 7-day free trial has expired. Upgrade now to continue accessing all the powerful tools and resources LevelUp has to offer!"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(ke,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Pe,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Dr,{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(q,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(ke,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Pe,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Ga,{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(q,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Ga,{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(Mn,{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(Ks,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},FYt=({hasUnseenBrief:s,onClick:t,className:r})=>e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"icon",onClick:t,className:zt("relative transition-colors",s&&"text-primary hover:text-primary",r),children:[e.jsx(fh,{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(Sc,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var pEe="Radio",[zYt,ect]=bu(pEe),[BYt,$Yt]=zYt(pEe),tct=k.forwardRef((s,t)=>{const{__scopeRadio:r,name:n,checked:a=!1,required:i,disabled:l,value:o="on",onCheck:c,form:d,...u}=s,[m,f]=k.useState(null),x=_i(t,b=>f(b)),y=k.useRef(!1),_=m?d||!!m.closest("form"):!0;return e.jsxs(BYt,{scope:r,checked:a,disabled:l,children:[e.jsx(Yn.button,{type:"button",role:"radio","aria-checked":a,"data-state":act(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:x,onClick:dn(s.onClick,b=>{a||c==null||c(),_&&(y.current=b.isPropagationStopped(),y.current||b.stopPropagation())})}),_&&e.jsx(nct,{control:m,bubbles:!y.current,name:n,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});tct.displayName=pEe;var sct="RadioIndicator",rct=k.forwardRef((s,t)=>{const{__scopeRadio:r,forceMount:n,...a}=s,i=$Yt(sct,r);return e.jsx(yh,{present:n||i.checked,children:e.jsx(Yn.span,{"data-state":act(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});rct.displayName=sct;var UYt="RadioBubbleInput",nct=k.forwardRef(({__scopeRadio:s,control:t,checked:r,bubbles:n=!0,...a},i)=>{const l=k.useRef(null),o=_i(l,i),c=yB(r),d=rB(t);return k.useEffect(()=>{const u=l.current;if(!u)return;const m=window.HTMLInputElement.prototype,x=Object.getOwnPropertyDescriptor(m,"checked").set;if(c!==r&&x){const y=new Event("click",{bubbles:n});x.call(u,r),u.dispatchEvent(y)}},[c,r,n]),e.jsx(Yn.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});nct.displayName=UYt;function act(s){return s?"checked":"unchecked"}var qYt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Pge="RadioGroup",[VYt,Gnr]=bu(Pge,[XS,ect]),ict=XS(),oct=ect(),[HYt,GYt]=VYt(Pge),lct=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,name:n,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:u=!0,onValueChange:m,...f}=s,x=ict(r),y=ZS(d),[_,b]=df({prop:i,defaultProp:a??null,onChange:m,caller:Pge});return e.jsx(HYt,{scope:r,name:n,required:l,disabled:o,value:_,onValueChange:b,children:e.jsx(Fxe,{asChild:!0,...x,orientation:c,dir:y,loop:u,children:e.jsx(Yn.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:y,...f,ref:t})})})});lct.displayName=Pge;var cct="RadioGroupItem",dct=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,disabled:n,...a}=s,i=GYt(cct,r),l=i.disabled||n,o=ict(r),c=oct(r),d=k.useRef(null),u=_i(t,d),m=i.value===a.value,f=k.useRef(!1);return k.useEffect(()=>{const x=_=>{qYt.includes(_.key)&&(f.current=!0)},y=()=>f.current=!1;return document.addEventListener("keydown",x),document.addEventListener("keyup",y),()=>{document.removeEventListener("keydown",x),document.removeEventListener("keyup",y)}},[]),e.jsx(zxe,{asChild:!0,...o,focusable:!l,active:m,children:e.jsx(tct,{disabled:l,required:i.required,checked:m,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:dn(x=>{x.key==="Enter"&&x.preventDefault()}),onFocus:dn(a.onFocus,()=>{var x;f.current&&((x=d.current)==null||x.click())})})})});dct.displayName=cct;var WYt="RadioGroupIndicator",uct=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,...n}=s,a=oct(r);return e.jsx(rct,{...a,...n,ref:t})});uct.displayName=WYt;var hct=lct,mct=dct,KYt=uct;const u_=k.forwardRef(({className:s,...t},r)=>e.jsx(hct,{className:zt("grid gap-2",s),...t,ref:r}));u_.displayName=hct.displayName;const Du=k.forwardRef(({className:s,...t},r)=>e.jsx(mct,{ref:r,className:zt("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(KYt,{className:"flex items-center justify-center",children:e.jsx(Rh,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Du.displayName=mct.displayName;const YYt=({brief:s,open:t,onClose:r,onDismiss:n})=>{const{user:a}=Cs(),[i,l]=k.useState({}),[o,c]=k.useState({}),[d,u]=k.useState([]);k.useEffect(()=>{t&&a&&s.polls.length>0&&m()},[t,a,s.polls]);const m=async()=>{if(!a)return;const b=s.polls.map(N=>N.id),{data:j}=await U.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",b);if(j){const N={};j.forEach(C=>{N[C.poll_id]||(N[C.poll_id]=[]),N[C.poll_id].push(C.option_id)}),c(N)}},f=(b,j)=>{l(N=>({...N,[b]:j}))},x=(b,j,N)=>{l(C=>{const A=C[b]||[];return N?{...C,[b]:[...A,j]}:{...C,[b]:A.filter(E=>E!==j)}})},y=async b=>{if(!a)return;const j=i[b];if(!j||Array.isArray(j)&&j.length===0){he.error("Please select an option");return}u(N=>[...N,b]);try{await U.from("levelup_brief_poll_responses").delete().eq("poll_id",b).eq("user_id",a.id);const N=Array.isArray(j)?j:[j],C=N.map(E=>({poll_id:b,option_id:E,user_id:a.id})),{error:A}=await U.from("levelup_brief_poll_responses").insert(C);if(A)throw A;c(E=>({...E,[b]:N})),he.success("Response submitted!")}catch(N){console.error("Error submitting poll response:",N),he.error("Failed to submit response")}finally{u(N=>N.filter(C=>C!==b))}},_=b=>(b.includes("mediadelivery.net")||b.includes("bunny"),b);return e.jsx(vs,{open:t,onOpenChange:b=>!b&&r(),children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[e.jsx("button",{onClick:r,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:e.jsx($r,{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(fh,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(Xe,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(bs,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(ui,{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(b=>e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>window.open(b.url,"_blank"),className:"gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),b.title]},b.id))})]}),s.polls.map(b=>{var C,A;const j=((C=o[b.id])==null?void 0:C.length)>0,N=d.includes(b.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:b.question}),j&&e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(qn,{className:"h-3 w-3"}),"Responded"]})]}),b.poll_type==="single"?e.jsx(u_,{value:i[b.id]||((A=o[b.id])==null?void 0:A[0])||"",onValueChange:E=>f(b.id,E),className:"space-y-2",children:b.options.map(E=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:E.id,id:E.id}),e.jsx(ce,{htmlFor:E.id,className:"cursor-pointer",children:E.option_text})]},E.id))}):e.jsx("div",{className:"space-y-2",children:b.options.map(E=>{const R=(i[b.id]||o[b.id]||[]).includes(E.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ri,{id:E.id,checked:R,onCheckedChange:F=>x(b.id,E.id,F)}),e.jsx(ce,{htmlFor:E.id,className:"cursor-pointer",children:E.option_text})]},E.id)})}),e.jsx(q,{size:"sm",onClick:()=>y(b.id),disabled:N,children:N?"Submitting...":j?"Update Response":"Submit"})]},b.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx(q,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(q,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},ZYt=()=>{const{user:s}=Cs(),[t,r]=k.useState(null),[n,a]=k.useState(!1),[i,l]=k.useState(!0),[o,c]=k.useState(!1),d=k.useCallback(async()=>{if(!s){l(!1);return}try{const{data:y,error:_}=await U.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(_||!y){l(!1);return}const{data:b}=await U.from("levelup_brief_views").select("*").eq("brief_id",y.id).eq("user_id",s.id).maybeSingle(),[j,N]=await Promise.all([U.from("levelup_brief_links").select("*").eq("brief_id",y.id).order("sort_order"),U.from("levelup_brief_polls").select("*").eq("brief_id",y.id).order("sort_order")]),C=[];if(N.data)for(const F of N.data){const{data:O}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",F.id).order("sort_order");C.push({...F,options:O||[]})}const A={brief:y,links:j.data||[],polls:C};r(A);const E=!!b,D=(b==null?void 0:b.dismissed_at)!=null,R=localStorage.getItem(`brief-dismissed-${y.id}`)==="true";if(D||R)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 F=new Date(b.viewed_at);(new Date().getTime()-F.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(y){console.error("Error fetching brief:",y)}finally{l(!1)}},[s]);k.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:y}=await U.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();y?await U.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",y.id):await U.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:n,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 U.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:b}=await U.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",y.id).eq("user_id",s.id);b&&console.error("Error updating brief dismiss:",b)}else{const{error:b}=await U.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});b&&console.error("Error inserting brief dismiss:",b)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(y){console.error("Error dismissing brief:",y),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function XYt(){const[s,t]=k.useState(!1),[r,n]=k.useState(!1),[a,i]=k.useState(null);k.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const m=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(m),t(!0);const f=x=>{x.preventDefault(),i(x)};return window.addEventListener("beforeinstallprompt",f),()=>{window.removeEventListener("beforeinstallprompt",f)}},[]);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(li,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),r?e.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",e.jsx(KF,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):e.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&a&&e.jsx(q,{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($r,{className:"h-4 w-4"})})]})]})}):null}const QYt=({children:s,onRefresh:t})=>{const[r,n]=k.useState(!1),[a,i]=k.useState(0),[l,o]=k.useState(!1),c=k.useRef(null),d=k.useRef(0),u=is(),m=80,f=120,x=k.useCallback(N=>{const C=c.current;C&&C.scrollTop<=0&&(d.current=N.touches[0].clientY,n(!0))},[]),y=k.useCallback(N=>{if(!r||l)return;const C=c.current;if(!C||C.scrollTop>0){n(!1),i(0);return}const E=N.touches[0].clientY-d.current;if(E>0){const R=Math.min(E*.5,f);i(R),R>10&&N.preventDefault()}},[r,l]),_=k.useCallback(async()=>{if(r)if(n(!1),a>=m&&!l){o(!0),i(m);try{t?await t():await u.invalidateQueries()}catch(N){console.error("Refresh failed:",N)}finally{o(!1),i(0)}}else i(0)},[r,a,l,t,u]),b=Math.min(a/m,1),j=b*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:x,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:b},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(lo,{className:"h-5 w-5 text-primary"})})}),e.jsx("div",{style:{transform:a>0?`translateY(${Math.max(0,a-60)}px)`:void 0,transition:r?void 0:"transform 0.2s ease-out"},children:s})]})},fct=()=>{const{user:s}=Cs(),[t,r]=k.useState(!1),[n,a]=k.useState(!1),[i,l]=k.useState(0),[o,c]=k.useState(!0);k.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:x}=await U.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(x){a(!0),r(!1),c(!1);return}const{data:y}=await U.from("profiles").select("login_count").eq("id",s.id).single(),_=(y==null?void 0:y.login_count)||0;l(_);const b=sessionStorage.getItem("review-prompt-dismissed");r(_>=4&&!b)}catch(x){console.error("Error checking review eligibility:",x)}finally{c(!1)}})()},[s]);const d=k.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),u=k.useCallback(async(f,x)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:y}=await U.from("membership_reviews").insert({user_id:s.id,rating:f,review_text:x});if(y)throw y;return a(!0),r(!1),{success:!0,pointsAwarded:25}}catch(y){return console.error("Error submitting review:",y),{success:!1,error:y.message}}},[s]),m=k.useCallback(async()=>{if(s)try{await U.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(f){console.error("Error updating Google review status:",f)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:n,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:m}},JYt="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",eZt=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:r,submitReview:n,markPostedToGoogle:a}=fct(),[i,l]=k.useState(!1),[o,c]=k.useState("review"),[d,u]=k.useState(0),[m,f]=k.useState(0),[x,y]=k.useState(""),[_,b]=k.useState(!1),[j,N]=k.useState(!1);if(t||!s&&!j)return null;const C=async()=>{if(d===0){Dn({title:"Please select a rating",variant:"destructive"});return}b(!0);const D=await n(d,x);b(!1),D.success?(N(!0),Dn({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):Dn({title:"Error submitting review",description:D.error,variant:"destructive"})},A=async D=>{D&&(await navigator.clipboard.writeText(x||`${d} star rating for LevelUp!`),Dn({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(JYt,"_blank")),l(!1),r()},E=()=>{l(!1),r()};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>l(!0),className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 rounded-full bg-primary/90 px-3 py-2 text-xs text-primary-foreground shadow-lg backdrop-blur-sm transition-all hover:bg-primary hover:scale-105 md:bottom-6",children:[e.jsx(fa,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(vs,{open:i,onOpenChange:E,children:e.jsx(ys,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(_s,{children:[e.jsx(bs,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(an,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(D=>e.jsx("button",{type:"button",onClick:()=>u(D),onMouseEnter:()=>f(D),onMouseLeave:()=>f(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(fa,{className:zt("h-8 w-8 transition-colors",(m||d)>=D?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},D))}),e.jsx(pr,{placeholder:"Tell us about your experience (optional)",value:x,onChange:D=>y(D.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",onClick:E,className:"flex-1",children:"Maybe Later"}),e.jsx(q,{onClick:C,disabled:_||d===0,className:"flex-1",children:_?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_s,{children:[e.jsx(bs,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(an,{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(q,{variant:"outline",onClick:()=>A(!1),className:"flex-1",children:"No Thanks"}),e.jsx(q,{onClick:()=>A(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function tZt(s){const t="=".repeat((4-s.length%4)%4),r=(s+t).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(r),a=new Uint8Array(n.length);for(let i=0;i{if(!m){l(!1);return}(async()=>{try{const _="vapid_public_key";let b=localStorage.getItem(_);if(!b){const{data:C,error:A}=await U.functions.invoke("get-vapid-public-key",{body:{}});if(A)throw A;if(b=(C==null?void 0:C.vapidPublicKey)??null,!b)throw new Error("Missing VAPID public key");localStorage.setItem(_,b)}u(b);const j=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(j),r(Notification.permission);const N=await j.pushManager.getSubscription();a(!!N)}catch(_){console.error("Error initializing push notifications:",_)}finally{l(!1)}})()},[m]);const f=k.useCallback(async()=>{if(!m||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return he.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:C}=await U.from("push_subscriptions").delete().eq("user_id",s.id);C&&console.warn("Failed to cleanup push_subscriptions rows:",C)}if(Notification.permission!=="granted"){const C=await Notification.requestPermission();if(r(C),C!=="granted")return C==="denied"?he.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):he.error("Notification permission was dismissed. Please try again."),!1}const _=tZt(d);let b;try{b=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:_})}catch(C){console.error("PushManager.subscribe() failed:",C);const A=(C==null?void 0:C.message)||String(C);return A.includes("permission")?he.error("Push permission denied. Check your browser notification settings."):A.includes("key")||A.includes("VAPID")?he.error("Push configuration error. Please contact support."):A.includes("AbortError")?he.error("Push subscription was cancelled. Please try again."):he.error(`Failed to subscribe: ${A}`),!1}const j=b.toJSON(),{error:N}=await U.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(N)throw console.error("Error saving subscription:",N),he.error("Failed to save notification preferences. Please try again."),N;return a(!0),he.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";he.error("Failed to enable push notifications: "+_)}return!1}finally{l(!1)}},[m,o,s,d]),x=k.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const y=await o.pushManager.getSubscription();return y&&await y.unsubscribe(),await U.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),he.success("Push notifications disabled"),!0}catch(y){console.error("Error unsubscribing:",y);const _=y instanceof Error?y.message:"Unknown error";return he.error("Failed to disable push notifications: "+_),!1}finally{l(!1)}},[o,s]);return{isSupported:m,permission:t,isSubscribed:n,isLoading:i,vapidPublicKey:d,subscribe:f,unsubscribe:x}}const y_e="push_notification_prompt_dismissed",sZt=["/dashboard","/admin"],rZt=()=>{const{user:s}=Cs(),{isSupported:t,isSubscribed:r,isLoading:n,subscribe:a}=pct(),i=vc(),[l,o]=k.useState(!1),[c,d]=k.useState(!1),u=sZt.some(x=>i.pathname===x||i.pathname.startsWith(`${x}/`));k.useEffect(()=>{if(u){o(!1);return}if(!s||!t||r||n||localStorage.getItem(`${y_e}_${s.id}`))return;const y=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(y)},[s,t,r,n,u]);const m=async()=>{d(!0);const x=await a();d(!1),x&&(s&&localStorage.setItem(`${y_e}_${s.id}`,"true"),o(!1))},f=()=>{s&&localStorage.setItem(`${y_e}_${s.id}`,"true"),o(!1)};return!t||r||u?null:e.jsx(vs,{open:l,onOpenChange:x=>!x&&f(),children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:e.jsx(ym,{className:"h-6 w-6 text-primary"})}),e.jsx(bs,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(an,{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(q,{onClick:m,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(q,{variant:"ghost",onClick:f,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."})]})})},fze=s=>{let t;const r=new Set,n=(d,u)=>{const m=typeof d=="function"?d(t):d;if(!Object.is(m,t)){const f=t;t=u??(typeof m!="object"||m===null)?m:Object.assign({},t,m),r.forEach(x=>x(t,f))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>c,subscribe:d=>(r.add(d),()=>r.delete(d))},c=t=s(n,a,o);return o},nZt=s=>s?fze(s):fze,aZt=s=>s;function iZt(s,t=aZt){const r=Ct.useSyncExternalStore(s.subscribe,Ct.useCallback(()=>t(s.getState()),[s,t]),Ct.useCallback(()=>t(s.getInitialState()),[s,t]));return Ct.useDebugValue(r),r}const pze=s=>{const t=nZt(s),r=n=>iZt(t,n);return Object.assign(r,t),r},oZt=s=>s?pze(s):pze;function lZt(s,t){let r;try{r=s()}catch{return}return{getItem:a=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),o=(i=r.getItem(a))!=null?i:null;return o instanceof Promise?o.then(l):l(o)},setItem:(a,i)=>r.setItem(a,JSON.stringify(i,void 0)),removeItem:a=>r.removeItem(a)}}const Ike=s=>t=>{try{const r=s(t);return r instanceof Promise?r:{then(n){return Ike(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return Ike(n)(r)}}}},cZt=(s,t)=>(r,n,a)=>{let i={storage:lZt(()=>window.localStorage),partialize:b=>b,version:0,merge:(b,j)=>({...j,...b}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),r(...b)},n,a);const m=()=>{const b=i.partialize({...n()});return u.setItem(i.name,{state:b,version:i.version})},f=a.setState;a.setState=(b,j)=>(f(b,j),m());const x=s((...b)=>(r(...b),m()),n,a);a.getInitialState=()=>x;let y;const _=()=>{var b,j;if(!u)return;const N=++o;l=!1,c.forEach(A=>{var E;return A((E=n())!=null?E:x)});const C=((j=i.onRehydrateStorage)==null?void 0:j.call(i,(b=n())!=null?b:x))||void 0;return Ike(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(D=>[!0,D]):[!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(N!==o)return;const[D,R]=A;if(y=i.merge(R,(E=n())!=null?E:x),r(y,!0),D)return m()}).then(()=>{N===o&&(C==null||C(n(),void 0),y=n(),l=!0,d.forEach(A=>A(y)))}).catch(A=>{N===o&&(C==null||C(void 0,A))})};return a.persist={setOptions:b=>{i={...i,...b},b.storage&&(u=b.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>l,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(d.add(b),()=>{d.delete(b)})},i.skipHydration||_(),y||x},dZt=cZt,Lge=oZt()(dZt((s,t)=>({cartItems:[],addToCart:(r,n,a=1,i)=>{s(l=>{const o=l.cartItems.findIndex(c=>{var d;return c.product.id===r.id&&((d=c.variant)==null?void 0:d.id)===(n==null?void 0:n.id)});if(o>=0){const c=[...l.cartItems];return c[o].quantity+=a,i&&(c[o].artworkUrl=i),{cartItems:c}}return{cartItems:[...l.cartItems,{product:r,variant:n,quantity:a,artworkUrl:i}]}})},removeFromCart:(r,n)=>{s(a=>({cartItems:a.cartItems.filter(i=>{var l;return!(i.product.id===r&&((l=i.variant)==null?void 0:l.id)===n)})}))},updateQuantity:(r,n,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===r&&((o=l.variant)==null?void 0:o.id)===n?{...l,quantity:Math.max(1,a)}:l})}))},updateArtwork:(r,n,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===r&&((o=l.variant)==null?void 0:o.id)===n?{...l,artworkUrl:a}:l})}))},clearCart:()=>s({cartItems:[]}),getItemPrice:r=>{const n=Number(r.product.base_price),a=r.variant?Number(r.variant.price_adjustment):0;return n+a},getSubtotal:()=>{const{cartItems:r,getItemPrice:n}=t();return r.reduce((a,i)=>a+n(i)*i.quantity,0)},getShippingTotal:()=>{const{cartItems:r}=t();return r.reduce((n,a)=>n+Number(a.product.shipping_fee)*a.quantity,0)},getTotal:()=>{const{getSubtotal:r,getShippingTotal:n}=t();return r()+n()}}),{name:"marketplace-cart",partialize:s=>({cartItems:s.cartItems})}));function uZt(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function hf(){const{user:s}=Cs(),{data:t,isLoading:r}=pt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:n,error:a}=await U.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 uZt(n)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:r,siteUrl:t?`https://${t.subdomain_slug}.thelocalmove.com`:null}}const xze="dashboard-sidebar-collapsed",ws=({children:s,title:t})=>{var nt;const{user:r,signOut:n,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=Cs(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=D5e(),{isImpersonating:m}=Rxe(),x=(c&&!!d?40:0)+(m?40:0),{avatarUrl:y}=Nlt(r==null?void 0:r.id),{isTrial:_,isExpired:b,expiresAt:j}=CKt(r==null?void 0:r.id),{isInnerCircleEnabled:N,isMarketplaceEnabled:C}=Slt(),{currentBrief:A,shouldShowPopup:E,hasUnseenBrief:D,openBrief:R,closeBrief:F,dismissBrief:O}=ZYt(),{unreadCount:B}=TKt(),{openCount:K}=EKt(),{data:Z}=uv(),Q=!!Z,te=Lge(Se=>Se.cartItems).reduce((Se,Ge)=>Se+Ge.quantity,0),{leadSite:ne,hasLeadSite:ae,siteUrl:ue}=hf(),me=qr(),de=vc(),[fe,je]=k.useState(null);k.useEffect(()=>{r!=null&&r.id&&U.from("profiles").select("name").eq("id",r.id).single().then(({data:Se})=>{Se!=null&&Se.name&&je(Se.name)})},[r==null?void 0:r.id]);const xe=fe||((nt=r==null?void 0:r.user_metadata)==null?void 0:nt.name)||(r==null?void 0:r.email)||"User",[Ee,Me]=k.useState(()=>typeof window<"u"?localStorage.getItem(xze)==="true":!1);k.useEffect(()=>{localStorage.setItem(xze,String(Ee))},[Ee]);const[Oe,Ie]=k.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),ze=Se=>{Ie(Ge=>({...Ge,[Se]:!Ge[Se]}))},Ve=Se=>Se.split(" ").map(Ge=>Ge[0]).join("").toUpperCase().slice(0,2),Le=Se=>de.pathname===Se,$e=Se=>Se.some(Ge=>de.pathname===Ge),ve=({path:Se,icon:Ge,label:We,badgeCount:Ce})=>{const qe=e.jsxs(q,{variant:"ghost",size:"sm",className:zt("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Le(Se)&&"bg-sidebar-accent text-sidebar-accent-foreground",Ee?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>me(Se),children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ge,{className:"h-4 w-4 shrink-0"}),Ee&&Ce!=null&&Ce>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!Ee&&We,!Ee&&Ce!=null&&Ce>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:Ce>9?"9+":Ce})]});return Ee?e.jsxs(Oc,{delayDuration:0,children:[e.jsx(Fc,{asChild:!0,children:qe}),e.jsxs(Sc,{side:"right",className:"flex items-center gap-2",children:[We,Ce!=null&&Ce>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:Ce>9?"9+":Ce})]})]}):qe},Qe=({id:Se,label:Ge,icon:We,children:Ce,activePaths:qe,showBetaBadge:et,defaultPath:Ze,badgeCount:rt})=>{if(Ee){const ct=Ze||qe[0];return e.jsxs(Oc,{delayDuration:0,children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"sm",className:zt("w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",$e(qe)&&"text-primary"),onClick:()=>me(ct),children:e.jsxs("div",{className:"relative",children:[e.jsx(We,{className:"h-4 w-4"}),rt!=null&&rt>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(Sc,{side:"right",className:"flex items-center gap-2",children:[Ge,et&&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"}),rt!=null&&rt>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:rt>9?"9+":rt})]})]})}return e.jsxs(E0,{open:Oe[Se],onOpenChange:()=>ze(Se),children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",$e(qe)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx(We,{className:"h-4 w-4"}),Ge,et&&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:[rt!=null&&rt>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:rt>9?"9+":rt}),e.jsx(Co,{className:zt("h-4 w-4 transition-transform duration-200",Oe[Se]&&"rotate-180")})]})]})}),e.jsx(M0,{className:"pl-4 space-y-1 mt-1",children:Ce})]})},we=({isMobile:Se=!1})=>{const Ge=Se?!1:Ee;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:zt("p-3 border-b border-sidebar-border",Ge?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[Ge?e.jsx("img",{src:DKt,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:LKt,alt:"LevelUp",className:"h-8 w-auto"}),!Se&&e.jsxs(Oc,{delayDuration:0,children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Me(!Ge),children:e.jsx(jl,{className:zt("h-4 w-4 transition-transform duration-300",Ge&&"rotate-180")})})}),e.jsx(Sc,{side:"right",children:Ge?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(ui,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:zt("p-3 space-y-1",Ge&&"flex flex-col items-center"),children:[Se&&_&&!b&&e.jsx("button",{type:"button",onClick:()=>me("/subscription"),className:zt("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(Ir,{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(ve,{path:"/dashboard",icon:LE,label:"Dashboard"}),e.jsx(ve,{path:"/apps",icon:Ey,label:"Apps & Tools"}),Ee?e.jsxs(Oc,{delayDuration:0,children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/levelup-u"),children:[e.jsx(ch,{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(Sc,{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(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/levelup-u"),children:[e.jsx(ch,{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(ve,{path:"/events",icon:xu,label:"Events"}),e.jsxs(Qe,{id:"agentos",label:"Agent OS",icon:eS,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(ve,{path:"/mission-control",icon:yi,label:"Mission Control"}),u("contacts")&&!Ge&&e.jsxs(E0,{open:Oe.contacts,onOpenChange:()=>ze("contacts"),children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",$e(["/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(Dr,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(Co,{className:zt("h-3.5 w-3.5 transition-transform duration-200",Oe.contacts&&"rotate-180")})]})}),e.jsxs(M0,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(ve,{path:"/mission-control/contacts",icon:Dr,label:"All Contacts"}),e.jsx(ve,{path:"/mission-control/relationship-scorecard",icon:xm,label:"Relationship Report"}),e.jsx(ve,{path:"/mission-control/sphere-gaps",icon:GF,label:"Sphere Gaps"}),e.jsx(ve,{path:"/mission-control/sent-emails",icon:hn,label:"Sent Emails"}),e.jsx(ve,{path:"/mission-control/connect-page",icon:Ul,label:"Connect Page"})]})]}),u("contacts")&&Ge&&e.jsx(ve,{path:"/mission-control/contacts",icon:Dr,label:"Contacts"}),u("contacts")&&e.jsx(ve,{path:"/mission-control/plans",icon:xu,label:"TouchPlans"}),u("pipeline")&&e.jsx(ve,{path:"/mission-control/pipeline",icon:i2,label:"Deal Pipeline"}),u("pipeline")&&e.jsx(ve,{path:"/mission-control/tasks",icon:zj,label:"Tasks"}),u("popbys")&&e.jsx(ve,{path:"/mission-control/popbys",icon:Di,label:"Popbys"}),u("videos")&&e.jsx(ve,{path:"/mission-control/video-library",icon:bn,label:"Video Library"}),u("scorecard")&&e.jsx(ve,{path:"/mission-control/scorecard",icon:Mo,label:"Scorecard"}),u("listings")&&e.jsx(ve,{path:"/mission-control/listings",icon:Ga,label:"Listing Exchange"}),e.jsx(ve,{path:"/mission-control/client-portals",icon:Ir,label:"Client Portals"}),e.jsx(ve,{path:"/mission-control/signals",icon:nP,label:"Signals"}),!Ge&&e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/mission-control/smart-drips")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/mission-control/smart-drips"),children:[e.jsx(zh,{className:"h-4 w-4"}),"Smart Drips",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),Ge&&e.jsx(ve,{path:"/mission-control/smart-drips",icon:zh,label:"Smart Drips"}),e.jsx(ve,{path:"/email-campaigns/templates",icon:Ks,label:"Email Templates"})]}),ae&&ne&&e.jsxs(Qe,{id:"website",label:"My Website",icon:Ql,activePaths:[`/admin/lead-sites/${ne.id}/edit`],defaultPath:`/admin/lead-sites/${ne.id}/edit`,children:[Ge?e.jsxs(Oc,{delayDuration:0,children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"sm",className:"w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(ue||"#","_blank"),children:e.jsx(Nn,{className:"h-4 w-4"})})}),e.jsx(Sc,{side:"right",children:"View Site"})]}):e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(ue||"#","_blank"),children:[e.jsx(Nn,{className:"h-4 w-4"}),"View Site",e.jsx(un,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsx(ve,{path:`/my-website/${ne.id}/edit`,icon:Ua,label:"Edit Website"}),e.jsx(ve,{path:"/my-website/mls-listings",icon:Pn,label:"MLS Listings"}),e.jsx(ve,{path:"/my-website/market-report",icon:Mo,label:"Market Reports"}),(ne==null?void 0:ne.mls_provider_id)&&e.jsx(ve,{path:"/mission-control/cma",icon:__,label:"CMA Reports"}),e.jsx(ve,{path:"/mission-control/website-activity",icon:xm,label:"Website Activity"}),e.jsx(ve,{path:"/m",icon:yg,label:"Mobile Command"})]}),e.jsxs(Qe,{id:"marketing",label:"Marketing",icon:fh,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps","/marketing-studio"],defaultPath:"/templates",children:[e.jsx(ve,{path:"/templates",icon:dl,label:"Templates"}),e.jsx(ve,{path:"/marketing-studio",icon:zo,label:"Marketing Studio"}),e.jsx(ve,{path:"/social-swag-2",icon:yg,label:"Social Swag"}),Ee?e.jsxs(Oc,{delayDuration:0,children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/newsletters"),children:[e.jsx(E1,{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(Sc,{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(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/newsletters"),children:[e.jsx(E1,{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(ve,{path:"/website-apps",icon:Ir,label:"Website Apps"})]}),e.jsxs(Qe,{id:"learning",label:"Learning",icon:vm,activePaths:["/academy","/toolbox"],defaultPath:"/academy",children:[e.jsx(ve,{path:"/academy",icon:ch,label:"Academy"}),e.jsx(ve,{path:"/toolbox",icon:A_,label:"Toolbox"})]}),e.jsxs(Qe,{id:"community",label:"Community",icon:Ui,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:B,children:[e.jsx(ve,{path:"/community",icon:Dr,label:"Community",badgeCount:B}),e.jsx(ve,{path:"/wishlist",icon:o2,label:"Wishlist",badgeCount:K}),!Ge&&e.jsxs(q,{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(un,{className:"h-4 w-4"}),"Facebook Group"]})]}),e.jsxs(Qe,{id:"goods",label:"The Goods",icon:lg,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[C&&!Ge&&e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",de.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/marketplace"),children:[e.jsx(lg,{className:"h-4 w-4"}),"Marketplace",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded-full bg-primary text-primary-foreground",children:"New"})]}),C&&Ge&&e.jsx(ve,{path:"/marketplace",icon:lg,label:"Marketplace"}),e.jsx(ve,{path:"/reward-store",icon:wo,label:"Reward Store"}),e.jsx(ve,{path:"/refer-friends",icon:Di,label:"Refer & Earn"})]}),e.jsxs(Qe,{id:"help",label:"Help & Services",icon:e_,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(ve,{path:"/support",icon:XI,label:"Support"}),e.jsx(ve,{path:"/additional-services",icon:Ir,label:"Additional Services"})]}),l&&e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(ve,{path:"/coaching",icon:ch,label:"Coaching"})}),e.jsx(hZt,{}),a&&e.jsxs(e.Fragment,{children:[!Ge&&e.jsx("div",{className:"pt-3 pb-1",children:e.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Admin"})}),Ge?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(ve,{path:"/admin",icon:Gc,label:"Admin Dashboard"})}):e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",de.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/admin"),children:[e.jsx(Gc,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!Ge&&e.jsx("div",{className:"pt-3 pb-1",children:e.jsx("p",{className:"px-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"My Brokerage"})}),Ge?e.jsxs("div",{className:"border-t border-sidebar-border mt-3 pt-3 space-y-1",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx(ve,{path:"/my-brokerage",icon:Ga,label:"My Brokerage"}),e.jsx(ve,{path:"/brokerage/help-board",icon:p1,label:"Help Board"}),e.jsx(ve,{path:"/brokerage-content",icon:vm,label:"Brokerage Content"})]}),Q&&!i&&e.jsx(ve,{path:"/my-team",icon:Dr,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(ve,{path:"/brokerage/dashboard",icon:Bo,label:"Manage Brokerages"}),e.jsx(ve,{path:"/brokerage/teams",icon:Dr,label:"Teams"}),e.jsx(ve,{path:"/brokerage/recruiting",icon:fh,label:"Recruiting"}),e.jsx(ve,{path:"/brokerage/vendors",icon:j_,label:"Vendors"}),e.jsx(ve,{path:"/brokerage-resources",icon:bm,label:"Brokerage Resources"})]})]}):e.jsxs(e.Fragment,{children:[o&&e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/my-brokerage")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/my-brokerage"),children:[e.jsx(Ga,{className:"h-4 w-4"}),"My Brokerage"]}),e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/brokerage/help-board")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/brokerage/help-board"),children:[e.jsx(p1,{className:"h-4 w-4"}),"Help Board"]}),e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/brokerage-content")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/brokerage-content"),children:[e.jsx(vm,{className:"h-4 w-4"}),"Brokerage Content"]})]}),Q&&!i&&e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/my-team")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/my-team"),children:[e.jsx(Dr,{className:"h-4 w-4"}),"My Team"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/brokerage/dashboard"),children:[e.jsx(Bo,{className:"h-4 w-4"}),"Manage Brokerages"]}),e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/brokerage/teams")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/brokerage/teams"),children:[e.jsx(Dr,{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(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/brokerage/recruiting")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/brokerage/recruiting"),children:[e.jsx(fh,{className:"h-4 w-4"}),"Recruiting"]}),e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/brokerage/vendors")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/brokerage/vendors"),children:[e.jsx(j_,{className:"h-4 w-4"}),"Vendors"]}),e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/brokerage-resources"),children:[e.jsx(bm,{className:"h-4 w-4"}),"Brokerage Resources"]})]})]})]})]})}),e.jsxs("div",{className:"p-3 border-t border-sidebar-border md:hidden",children:[e.jsxs(q,{variant:"ghost",size:"sm",className:zt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Le("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>me("/profile"),children:[e.jsx(qi,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:n,children:[e.jsx(OE,{className:"h-4 w-4"}),"Sign Out"]})]})]})};return e.jsx(J_,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[_&&b&&de.pathname!=="/subscription"&&e.jsx(OYt,{}),typeof document<"u"&&vx.createPortal(e.jsx("aside",{className:zt("hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto transition-[width] duration-300",Ee?"w-16":"w-56"),style:{top:`${x}px`,height:`calc(100vh - ${x}px)`},children:e.jsx(we,{})}),document.body),e.jsxs("div",{className:zt("flex-1 flex flex-col overflow-hidden transition-all duration-300",Ee?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${x}px)`,marginTop:`${x}px`},children:[e.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[e.jsxs(sw,{children:[e.jsx(mge,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(aS,{className:"h-5 w-5"})})}),e.jsx(U1,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(we,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:RKt,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(mze,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[_&&!b&&j&&e.jsx(RYt,{expiresAt:j,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(mze,{})}),A&&e.jsx(FYt,{hasUnseenBrief:D,onClick:R}),C&&e.jsxs(q,{variant:"ghost",size:"icon",className:"relative",onClick:()=>me("/marketplace/cart"),children:[e.jsx(lg,{className:"h-5 w-5"}),te>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs font-medium flex items-center justify-center",children:te>99?"99+":te})]}),e.jsx(lYt,{}),e.jsx(Eke,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",xe.split(" ")[0],"!"]}),e.jsxs(Gd,{children:[e.jsx(Wd,{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(Wn,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(Xa,{src:y||void 0}),e.jsx(Kn,{className:"bg-primary text-primary-foreground font-medium text-sm",children:Ve(xe)})]})})}),e.jsxs(Sd,{align:"end",className:"w-48",children:[e.jsxs(ti,{onClick:()=>me("/profile"),className:"cursor-pointer",children:[e.jsx(qi,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(ti,{onClick:()=>me("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(d2,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(ti,{onClick:()=>me("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(d2,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(z_,{}),e.jsxs(ti,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(OE,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(QYt,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),A&&e.jsx(YYt,{brief:A,open:E,onClose:F,onDismiss:O}),e.jsx(XYt,{}),e.jsx(eZt,{}),e.jsx(rZt,{})]})]})})};function hZt(){const{user:s}=Cs(),t=vc(),r=qr(),{data:n}=pt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await U.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(i||[]).length>0}});if(!n)return null;const a=t.pathname==="/my-coach";return e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsxs(q,{variant:"ghost",size:"sm",className:`w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground ${a?"bg-sidebar-accent text-sidebar-accent-foreground":""}`,onClick:()=>r("/my-coach"),children:[e.jsx(ch,{className:"h-4 w-4"}),"My Coach"]})})}const mZt=new Set(["jeremy@relevelup.com"]),gze="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",fZt=[{label:"Open ChatGPT",description:"You need ChatGPT Plus, Pro, or Team to connect MCP servers."},{label:"Go to Connected apps",description:"Settings → Connected apps → Add app (or Add MCP server)."},{label:"Paste the MCP URL",description:"Copy the URL below and paste it into the server URL field."},{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:"ChatGPT can now call LevelUp tools on your behalf."}];function pZt(){const[s,t]=k.useState(!1),{user:r}=Cs();if(!(!!(r!=null&&r.email)&&mZt.has(r.email.toLowerCase())))return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8 max-w-2xl 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(Ir,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"ChatGPT Integration"}),e.jsx("p",{className:"text-muted-foreground",children:"Coming soon"})]})]}),e.jsx(ke,{children:e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Coming soon"}),e.jsx(Ur,{children:"We're putting the finishing touches on the ChatGPT integration. It will be available to all agents shortly. Stay tuned!"})]})})]})});const a=async()=>{try{await navigator.clipboard.writeText(gze),t(!0),he.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{he.error("Could not copy URL")}};return e.jsx(ws,{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(eS,{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(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"LevelUp MCP server URL"}),e.jsx(Ur,{children:"Paste this URL into ChatGPT when it asks for an MCP server address."})]}),e.jsx(Pe,{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:gze}),e.jsx(q,{variant:"outline",size:"icon",onClick:a,"aria-label":"Copy MCP URL",children:s?e.jsx(Ti,{className:"h-4 w-4 text-green-600"}):e.jsx(si,{className:"h-4 w-4"})})]})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Quick steps"}),e.jsx(Ur,{children:"Share these steps with any agent who wants to connect their ChatGPT account."})]}),e.jsx(Pe,{children:e.jsx("ol",{className:"space-y-4",children:fZt.map((i,l)=>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:l+1}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:i.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i.description})]})]},l))})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{children:"Only basic tools are exposed today. More LevelUp actions will be added over time."})]})]})})}const xZt=()=>{const[s]=ic(),t=s.get("tier"),r=t==null?void 0:t.includes("brokerage");return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(ke,{className:"max-w-lg w-full",children:[e.jsxs(Pt,{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(Ti,{className:"w-10 h-10 text-green-500"})}),e.jsx(Dt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Ur,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-primary/10 border border-primary/20 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Ks,{className:"w-5 h-5"}),e.jsx("span",{className:"font-semibold",children:"Check your email to sign in"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We've sent you an email with a secure link to access your account. Click the link in your email to get started."})]}),r?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Create and name your brokerage"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"4."}),"Start inviting agents to join your team"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Start exploring templates, training videos, and more!"]})]}),e.jsx("p",{className:"text-sm text-green-600 font-medium mt-4",children:"🎉 Your 7-day free trial has started!"})]}),e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Didn't receive the email? Check your spam folder or contact support."})})]})]})})},gZt=()=>{const{user:s}=Cs(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(""),o=async m=>{var f;if(!(s!=null&&s.email)){he.error("Please sign in to upgrade");return}r(!0),a(m);try{const{data:x,error:y}=await U.functions.invoke("create-checkout",{body:{tier:m,email:s.email,name:((f=s.user_metadata)==null?void 0:f.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(y)throw y;if(x!=null&&x.url)window.open(x.url,"_blank","noopener,noreferrer"),he.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(x){console.error("Checkout error:",x),he.error(x.message||"Failed to start checkout. Please try again.")}finally{r(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],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(ws,{children:e.jsxs("div",{className:"container max-w-6xl py-8 px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Upgrade Your Membership"}),e.jsx("p",{className:"text-muted-foreground text-lg",children:"Choose the plan that's right for you and unlock the full power of LevelUp"})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(ce,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(Ne,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:m=>l(m.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-8",children:[e.jsxs(ke,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 right-0 bg-primary text-primary-foreground text-xs px-3 py-1 rounded-bl-lg font-medium",children:"Popular"}),e.jsxs(Pt,{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(Dr,{className:"h-7 w-7 text-primary"})}),e.jsx(Dt,{className:"text-xl",children:"Individual Agent"}),e.jsx(Ur,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((m,f)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(la,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},f))}),e.jsxs(q,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&n==="individual_agent"?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(ke,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(Pt,{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(Ga,{className:"h-7 w-7 text-amber-600"})}),e.jsx(Dt,{className:"text-xl",children:"Brokerage"}),e.jsx(Ur,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-amber-600",children:"$299"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((m,f)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(la,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},f))}),e.jsxs(q,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",size:"lg",onClick:()=>o("brokerage_under_25"),disabled:t,children:[t&&n==="brokerage_under_25"?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(ke,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Pt,{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(Ga,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Dt,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(Ur,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:u.map((m,f)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(la,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},f))}),e.jsxs(q,{variant:"outline",className:"w-full border-purple-500 text-purple-600 hover:bg-purple-50",size:"lg",onClick:()=>o("brokerage_over_25"),disabled:t,children:[t&&n==="brokerage_over_25"?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(ke,{className:"bg-muted/50",children:e.jsxs(Pe,{className:"py-6",children:[e.jsx("p",{className:"text-center font-medium mb-4",children:"Questions? We're here to help!"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(Mn,{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(Ks,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},yZt=()=>{const{user:s,loading:t,isBrokerageManager:r,brokerageId:n}=Cs(),a=qr(),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,u]=k.useState(!1);k.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),k.useEffect(()=>{!t&&s&&n&&a("/profile?setup=true")},[s,t,n,a]);const m=async()=>{if(!i.trim()){he.error("Please enter a brokerage name");return}const{data:f}=await U.auth.getSession(),x=f.session;if(!s||!x){he.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!x,userId:s==null?void 0:s.id});const{data:y,error:_}=await U.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),he.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(y){console.error("Error creating brokerage:",y),he.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(ke,{className:"max-w-lg w-full",children:[e.jsxs(Pt,{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(ls,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Dt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Ur,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Ti,{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(ls,{className:"w-5 h-5 animate-spin text-primary"}),e.jsx("span",{children:"Assigning you as manager..."})]}),e.jsx("p",{className:"text-center text-sm text-muted-foreground mt-4",children:"You'll be redirected to complete your profile setup in a moment."})]})]})}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(ke,{className:"max-w-lg w-full",children:[e.jsxs(Pt,{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(Ga,{className:"w-10 h-10 text-primary"})}),e.jsx(Dt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Ur,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(Ne,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:f=>l(f.target.value),onKeyDown:f=>f.key==="Enter"&&m()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Dr,{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(Ti,{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(Ti,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Ti,{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(Ti,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(q,{onClick:m,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(ci,{className:"w-4 h-4 ml-2"})]})]})]})})},yze=()=>{const s=qr(),[t,r]=k.useState("verifying"),[n,a]=k.useState("");k.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await U.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await U.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),r("already_claimed");return}console.log("User logged in successfully:",o.user.email),r("success");try{await U.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{r("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),r("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{className:"space-y-1 text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10",children:[t==="verifying"&&e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"}),t==="success"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),t==="already_claimed"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),t==="error"&&e.jsx("svg",{className:"h-8 w-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})]}),e.jsxs(Dt,{className:"text-2xl",children:[t==="verifying"&&"Claiming Your Account...",t==="success"&&"Account Claimed!",t==="already_claimed"&&"Account Already Claimed",t==="error"&&"Claim Failed"]}),e.jsxs(Ur,{children:[t==="verifying"&&"Please wait while we verify your account...",t==="success"&&"Redirecting you to complete your profile...",t==="already_claimed"&&"This account has already been set up. Please log in to access your dashboard.",t==="error"&&n]})]}),(t==="already_claimed"||t==="error")&&e.jsx(Pe,{children:e.jsx(q,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},vZt=()=>{const[s,t]=k.useState(!1),r=k.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),n=k.useMemo(()=>{if(!r)return!1;try{const i=new URL(r);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[r]);k.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!n||!r||(t(!0),window.location.href=r)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:jlt,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ke,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Pt,{className:"text-center",children:[e.jsx(Dt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(Ur,{className:"text-gray-600 pt-2",children:n?"Click the button below to continue resetting your password.":"This link is invalid or has expired. Please request a new password reset email."})]}),e.jsxs(Pe,{className:"space-y-4",children:[n?e.jsx(q,{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(q,{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."})]})]})]})})]})},bZt=()=>{const s=qr(),[t]=ic(),[r,n]=k.useState(t.get("code")||""),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,m]=k.useState(!1),[f,x]=k.useState(!1),[y,_]=k.useState(!1),[b,j]=k.useState(!1),[N,C]=k.useState(null),[A,E]=k.useState(null),[D,R]=k.useState(null),[F,O]=k.useState(null);k.useEffect(()=>{const Q=t.get("code");Q&&(n(Q),B(Q))},[t]);const B=async Q=>{_(!0);const{data:W,error:te}=await U.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",Q.toUpperCase().trim()).single();if(te||!W){he.error("Invalid invite code"),_(!1);return}if(!W.is_active){he.error("This invite code is no longer active"),_(!1);return}if(W.max_uses&&W.uses_count>=W.max_uses){he.error("This invite code has reached its maximum uses"),_(!1);return}if(W.expires_at&&new Date(W.expires_at){Q.preventDefault(),B(r)},Z=async Q=>{var W;if(Q.preventDefault(),!c.trim()){he.error("Please enter your name");return}if(l.length<6){he.error("Password must be at least 6 characters");return}x(!0);try{const te=`${window.location.origin}/`,{data:ne,error:ae}=await U.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:te,data:{name:c.trim()}}});if(ae){ae.message.includes("already registered")?he.error("This email is already registered. Please sign in instead."):he.error(ae.message);return}ne.user&&(await U.rpc("add_default_signup_tag",{user_id:ne.user.id}),A?await U.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,brokerageId:A}}):F?await U.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,trialDays:F}}):await U.functions.invoke("assign-brokerage",{body:{userId:ne.user.id,grandfathered:!0}}),N&&await U.from("invite_codes").update({uses_count:((W=(await U.from("invite_codes").select("uses_count").eq("id",N).single()).data)==null?void 0:W.uses_count)+1}).eq("id",N),he.success("Account created! You can now access the dashboard."),s("/dashboard"))}catch(te){console.error("Signup error:",te),he.error("An unexpected error occurred")}finally{x(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{className:"text-center",children:[e.jsx(Dt,{className:"text-2xl font-bold text-primary",children:D?`Join ${D}`:"Join LevelUp"}),e.jsx(Ur,{children:b?D?`Create your account to join ${D}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Pe,{children:b?e.jsxs("form",{onSubmit:Z,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"name",children:"Full Name"}),e.jsx(Ne,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:Q=>d(Q.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:Q=>i(Q.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:Q=>o(Q.target.value),required:!0,minLength:6}),e.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>m(!u),children:u?e.jsx(Wf,{className:"h-4 w-4"}):e.jsx(Nn,{className:"h-4 w-4"})})]})]}),e.jsx(q,{type:"submit",className:"w-full",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:K,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(Ne,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:r,onChange:Q=>n(Q.target.value),required:!0,autoFocus:!0})]}),e.jsx(q,{type:"submit",className:"w-full",disabled:y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},CB=()=>{const{user:s,isCoach:t}=Cs();return pt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:r,error:n}=await U.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return r}})},_Zt=()=>{const{data:s}=CB();return pt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await U.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(r)throw r;const n=t||[];if(n.length===0)return[];const a=n.map(o=>o.agent_id),{data:i}=await U.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return n.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},wZt=()=>{const{user:s}=Cs();return pt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await U.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(r)throw r;const n=(t||[])[0];if(!n)return null;const{data:a}=await U.from("coaches").select("*").eq("id",n.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await U.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...n,coach:a,coachProfile:i}}})},jZt=s=>pt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await U.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(r)throw r;if(!t)return null;const{data:n}=await U.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:n}}}),xct=s=>pt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await U.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(r)throw r;return t||[]}}),gct=s=>pt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await U.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(r)throw r;return t||[]}}),NZt=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function kZt(){const s=qr(),{data:t,isLoading:r}=CB(),{data:n=[],isLoading:a}=_Zt();if(r)return e.jsx(ws,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(ws,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(ch,{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."})]})});NZt.map(l=>({...l,items:n.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=n.filter(l=>l.status==="active").length;return e.jsx(ws,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(Ir,{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(v_e,{icon:ch,label:"Active agents",value:i}),e.jsx(v_e,{icon:xu,label:"This month",value:"—"}),e.jsx(v_e,{icon:ld,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(q,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):n.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No agents assigned yet. An admin or you can invite agents to get started."})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(l=>{var o,c,d,u;return e.jsx(ke,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Pe,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Wn,{className:"h-14 w-14",children:[e.jsx(Xa,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(Kn,{children:(((c=l.agent)==null?void 0:c.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h3",{className:"font-semibold truncate",children:((d=l.agent)==null?void 0:d.name)||"Unknown"}),e.jsx(ci,{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(Xe,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",Nl(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function v_e({icon:s,label:t,value:r}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-white/15 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:r}),e.jsx("div",{className:"text-xs text-white/70 mt-1",children:t})]})]})}function yct({assignmentId:s}){const{user:t}=Cs(),r=is(),[n,a]=k.useState(""),[i,l]=k.useState(!1),o=k.useRef(null),{data:c=[]}=pt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:m}=await U.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(m)throw m;return u||[]}});k.useEffect(()=>{if(!s)return;const u=U.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>r.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{U.removeChannel(u)}},[s,r]),k.useEffect(()=>{var u;(u=o.current)==null||u.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const u=n.trim();if(!u||!t)return;l(!0);const{error:m}=await U.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),m||a("")};return e.jsxs(ke,{className:"flex flex-col h-[60vh] min-h-[400px]",children:[e.jsx("div",{ref:o,className:"flex-1 overflow-y-auto p-4 space-y-3",children:c.length===0?e.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"No messages yet. Say hi 👋"}):c.map(u=>{const m=u.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:zt("flex gap-2",m?"justify-end":"justify-start"),children:[!m&&e.jsx(Wn,{className:"h-8 w-8 mt-1",children:e.jsx(Kn,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:zt("max-w-[75%] rounded-2xl px-3 py-2 text-sm",m?"bg-[#406E71] text-white rounded-br-sm":"bg-muted rounded-bl-sm"),children:[e.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.body}),e.jsx("p",{className:zt("text-[10px] mt-1",m?"text-white/70":"text-muted-foreground"),children:Nl(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Pe,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(pr,{value:n,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(q,{onClick:d,disabled:i||!n.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(hn,{className:"h-4 w-4"})})]})})]})}var xEe="Progress",gEe=100,[SZt,Wnr]=bu(xEe),[CZt,TZt]=SZt(xEe),vct=k.forwardRef((s,t)=>{const{__scopeProgress:r,value:n=null,max:a,getValueLabel:i=EZt,...l}=s;(a||a===0)&&!vze(a)&&console.error(AZt(`${a}`,"Progress"));const o=vze(a)?a:gEe;n!==null&&!bze(n,o)&&console.error(MZt(`${n}`,"Progress"));const c=bze(n,o)?n:null,d=Mme(c)?i(c,o):void 0;return e.jsx(CZt,{scope:r,value:c,max:o,children:e.jsx(Yn.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":Mme(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":wct(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});vct.displayName=xEe;var bct="ProgressIndicator",_ct=k.forwardRef((s,t)=>{const{__scopeProgress:r,...n}=s,a=TZt(bct,r);return e.jsx(Yn.div,{"data-state":wct(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...n,ref:t})});_ct.displayName=bct;function EZt(s,t){return`${Math.round(s/t*100)}%`}function wct(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function Mme(s){return typeof s=="number"}function vze(s){return Mme(s)&&!isNaN(s)&&s>0}function bze(s,t){return Mme(s)&&!isNaN(s)&&s<=t&&s>=0}function AZt(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${gEe}\`.`}function MZt(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 ${gEe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var jct=vct,IZt=_ct;const ki=k.forwardRef(({className:s,value:t,...r},n)=>e.jsx(jct,{ref:n,className:zt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...r,children:e.jsx(IZt,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));ki.displayName=jct.displayName;function Nct({agentUserId:s}){const t=new Date().getFullYear(),r=`${t}-01-01`,n=`${t}-12-31`,{data:a=[]}=pt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:_,error:b}=await U.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",r).lte("close_date",n);if(b)throw b;return _||[]}}),{data:i}=pt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:_}=await U.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((_,b)=>_+(Number(b.sale_price)||0),0),d=l.reduce((_,b)=>_+(Number(b.commission_amount)||0),0),u=i,m=(u==null?void 0:u.transactions_goal)||0,f=(u==null?void 0:u.volume_goal)||0,x=(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(Wo,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(b_e,{icon:Uc,label:"Transactions",value:o.toString(),goal:m,current:o,suffix:m?`/ ${m}`:""}),e.jsx(b_e,{icon:Wo,label:"Volume",value:y(c),goal:f,current:c,suffix:f?`of ${y(f)}`:""}),e.jsx(b_e,{icon:Xl,label:"GCI",value:y(d),goal:x,current:d,suffix:x?`of ${y(x)}`:""})]}),o===0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function b_e({icon:s,label:t,value:r,goal:n,current:a,suffix:i}){const l=n>0?Math.min(100,a/n*100):0;return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-2",children:[e.jsx(s,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs uppercase tracking-wider",children:t})]}),e.jsx("div",{className:"text-2xl font-bold",children:r}),n>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(ki,{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 kct({assignmentId:s,canEdit:t}){const r=is(),[n,a]=k.useState(!1),[i,l]=k.useState(null),{data:o=[]}=pt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>r.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Hu,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(q,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const u=Number(d.target_value||0),m=Number(d.current_value||0),f=u>0?Math.min(100,m/u*100):0;return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:d.title}),e.jsx(Xe,{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(q,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(Ua,{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:[m.toLocaleString()," / ",u.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[f.toFixed(0),"%"]})]}),e.jsx(ki,{value:f})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",As(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(PZt,{open:n,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function PZt({open:s,onOpenChange:t,assignmentId:r,goal:n,onSaved:a}){var A,E;const[i,l]=k.useState((n==null?void 0:n.title)||""),[o,c]=k.useState((n==null?void 0:n.description)||""),[d,u]=k.useState((n==null?void 0:n.target_metric)||""),[m,f]=k.useState(((A=n==null?void 0:n.target_value)==null?void 0:A.toString())||""),[x,y]=k.useState(((E=n==null?void 0:n.current_value)==null?void 0:E.toString())||"0"),[_,b]=k.useState((n==null?void 0:n.due_date)||""),[j,N]=k.useState(!1);k.useState(()=>{var D,R;l((n==null?void 0:n.title)||""),c((n==null?void 0:n.description)||""),u((n==null?void 0:n.target_metric)||""),f(((D=n==null?void 0:n.target_value)==null?void 0:D.toString())||""),y(((R=n==null?void 0:n.current_value)==null?void 0:R.toString())||"0"),b((n==null?void 0:n.due_date)||"")});const C=async()=>{if(!i.trim())return;N(!0);const D={assignment_id:r,title:i,description:o||null,target_metric:d||null,target_value:m?Number(m):null,current_value:x?Number(x):0,due_date:_||null},{error:R}=n!=null&&n.id?await U.from("coaching_goals").update(D).eq("id",n.id):await U.from("coaching_goals").insert(D);if(N(!1),R)return he.error(R.message);he.success(n!=null&&n.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:n!=null&&n.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ne,{placeholder:"Title",value:i,onChange:D=>l(D.target.value)}),e.jsx(pr,{placeholder:"Description (optional)",rows:2,value:o,onChange:D=>c(D.target.value)}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Metric"}),e.jsx(Ne,{placeholder:"transactions",value:d,onChange:D=>u(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(Ne,{type:"number",value:m,onChange:D=>f(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(Ne,{type:"number",value:x,onChange:D=>y(D.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(Ne,{type:"date",value:_,onChange:D=>b(D.target.value)})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{onClick:C,disabled:j,children:n!=null&&n.id?"Save":"Create"})]})]})})}function Sct({assignmentId:s}){const t=is(),{user:r}=Cs(),n=k.useRef(null),[a,i]=k.useState(!1),{data:l=[]}=pt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:m,error:f}=await U.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(f)throw f;return m||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async m=>{var x;const f=(x=m.target.files)==null?void 0:x[0];if(!(!f||!r)){i(!0);try{const y=`${s}/${Date.now()}-${f.name}`,{error:_}=await U.storage.from("coaching-files").upload(y,f);if(_)throw _;const{error:b}=await U.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:r.id,file_url:y,file_name:f.name,file_size_bytes:f.size,mime_type:f.type});if(b)throw b;he.success("File uploaded"),o()}catch(y){he.error(y.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}}},d=async m=>{const{data:f,error:x}=await U.storage.from("coaching-files").createSignedUrl(m.file_url,60);if(x||!f)return he.error("Could not get download link");window.open(f.signedUrl,"_blank")},u=async m=>{confirm("Delete this file?")&&(await U.storage.from("coaching-files").remove([m.file_url]),await U.from("coaching_shared_files").delete().eq("id",m.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs(q,{size:"sm",onClick:()=>{var m;return(m=n.current)==null?void 0:m.click()},disabled:a,children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:n,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(m=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-muted flex items-center justify-center",children:e.jsx(En,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:m.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.file_size_bytes?`${(m.file_size_bytes/1024).toFixed(0)} KB · `:"",As(new Date(m.created_at),"PP")]})]}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>d(m),children:e.jsx(li,{className:"h-4 w-4"})}),m.uploaded_by===(r==null?void 0:r.id)&&e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>u(m),children:e.jsx(zr,{className:"h-4 w-4"})})]})},m.id))})]})}function LZt(){var f,x,y,_;const{id:s}=xo(),t=qr(),r=is(),{data:n,isLoading:a}=jZt(s),{data:i=[]}=xct(s),{data:l=[]}=gct(s),[o,c]=k.useState(!1),[d,u]=k.useState(!1);if(a)return e.jsx(ws,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!n)return e.jsx(ws,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const m=n;return e.jsxs(ws,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Pe,{className:"pt-0 -mt-12 pb-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 md:items-end",children:[e.jsxs(Wn,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(Xa,{src:((f=m.agent)==null?void 0:f.avatar_url)||void 0}),e.jsx(Kn,{className:"text-2xl",children:(((x=m.agent)==null?void 0:x.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((y=m.agent)==null?void 0:y.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(_=m.agent)==null?void 0:_.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Xe,{variant:"secondary",className:"capitalize",children:(m.pipeline_stage||"active").replace("_"," ")}),e.jsx(Xe,{variant:"outline",className:"capitalize",children:m.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(DZt,{value:m.pipeline_stage||"active",onChange:async b=>{await U.from("coaching_assignments").update({pipeline_stage:b}).eq("id",m.id),r.invalidateQueries({queryKey:["coaching-assignment",m.id]}),r.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsxs(ta,{defaultValue:"sessions",children:[e.jsxs(ea,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(rs,{value:"sessions",children:[e.jsx(vn,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(rs,{value:"actions",children:[e.jsx(l2,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(rs,{value:"goals",children:[e.jsx(Hu,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(rs,{value:"kpis",children:[e.jsx(Wo,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(rs,{value:"messages",children:[e.jsx(Ui,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(rs,{value:"files",children:[e.jsx(Kf,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(rs,{value:"notes",children:[e.jsx(En,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(fs,{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(q,{size:"sm",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(b=>e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:As(new Date(b.scheduled_at),"PPp")}),e.jsx(Xe,{variant:"outline",className:"capitalize",children:b.status}),b.template&&e.jsx(Xe,{variant:"secondary",children:b.template})]}),b.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:b.summary}),b.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Gc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:b.private_notes})]})]})})})},b.id))})]}),e.jsxs(fs,{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(q,{size:"sm",onClick:()=>u(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(b=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-3 flex items-center gap-3",children:[e.jsx(Ri,{checked:b.status==="done",onCheckedChange:async j=>{await U.from("coaching_action_items").update({status:j?"done":"open",completed_at:j?new Date().toISOString():null}).eq("id",b.id),r.invalidateQueries({queryKey:["coaching-action-items",m.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:b.status==="done"?"line-through text-muted-foreground":"font-medium",children:b.title}),b.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]}),b.due_date&&e.jsx(Xe,{variant:"outline",children:As(new Date(b.due_date),"MMM d")}),e.jsx(Xe,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))})]}),e.jsx(fs,{value:"goals",children:e.jsx(kct,{assignmentId:m.id,canEdit:!0})}),e.jsx(fs,{value:"kpis",children:m.agent_id&&e.jsx(Nct,{agentUserId:m.agent_id})}),e.jsx(fs,{value:"messages",children:e.jsx(yct,{assignmentId:m.id})}),e.jsx(fs,{value:"files",children:e.jsx(Sct,{assignmentId:m.id})}),e.jsx(fs,{value:"notes",className:"space-y-4",children:e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(RZt,{open:o,onOpenChange:c,assignmentId:m.id,onSaved:()=>r.invalidateQueries({queryKey:["coaching-sessions",m.id]})}),e.jsx(OZt,{open:d,onOpenChange:u,assignmentId:m.id,onSaved:()=>r.invalidateQueries({queryKey:["coaching-action-items",m.id]})})]})}function DZt({value:s,onChange:t}){return e.jsxs(Ds,{value:s,onValueChange:t,children:[e.jsx(Ps,{className:"w-40",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"onboarding",children:"Onboarding"}),e.jsx(lt,{value:"active",children:"Active"}),e.jsx(lt,{value:"thriving",children:"Thriving"}),e.jsx(lt,{value:"at_risk",children:"At Risk"}),e.jsx(lt,{value:"graduated",children:"Graduated"})]})]})}function RZt({open:s,onOpenChange:t,assignmentId:r,onSaved:n}){const[a,i]=k.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=k.useState(60),[c,d]=k.useState("weekly_1on1"),[u,m]=k.useState(""),[f,x]=k.useState(""),[y,_]=k.useState(!1),[b,j]=k.useState(!0),[N,C]=k.useState(null),[A,E]=k.useState(!1),D=async()=>{E(!0);const{data:F,error:O}=await U.functions.invoke("coaching-prep-brief",{body:{assignmentId:r}});if(E(!1),O||F!=null&&F.error)return he.error((F==null?void 0:F.error)||(O==null?void 0:O.message)||"Failed to generate brief");C(F.brief||"No brief returned.")},R=async()=>{_(!0);const{data:F,error:O}=await U.from("coaching_sessions").insert({assignment_id:r,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:f,status:"completed"}).select("id").maybeSingle();if(O)return _(!1),he.error(O.message);if(he.success("Session saved"),b&&u.trim()&&(F!=null&&F.id)){const{error:B}=await U.functions.invoke("coaching-send-recap",{body:{sessionId:F.id}});B?he.error("Saved, but recap email failed: "+B.message):he.success("Recap emailed to agent")}_(!1),n==null||n(),t(!1),m(""),x(""),C(null)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(bs,{children:"New Session"}),e.jsxs(q,{size:"sm",variant:"outline",onClick:D,disabled:A,children:[A?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ir,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[N&&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(Ir,{className:"h-3 w-3"})," AI Brief"]}),N]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(Ne,{type:"datetime-local",value:a,onChange:F=>i(F.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(Ne,{type:"number",value:l,onChange:F=>o(Number(F.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(Ds,{value:c,onValueChange:d,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(lt,{value:"grow",children:"GROW Model"}),e.jsx(lt,{value:"goal_review",children:"Goal Review"}),e.jsx(lt,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(pr,{rows:4,value:u,onChange:F=>m(F.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(pr,{rows:3,value:f,onChange:F=>x(F.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(Ri,{checked:b,onCheckedChange:F=>j(!!F)}),e.jsx(hn,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:R,disabled:y,children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function OZt({open:s,onOpenChange:t,assignmentId:r,onSaved:n}){const[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,m]=k.useState("medium"),[f,x]=k.useState(!1),y=async()=>{if(!a.trim())return;x(!0);const{error:_}=await U.from("coaching_action_items").insert({assignment_id:r,title:a,description:l||null,due_date:c||null,priority:u});if(x(!1),_)return he.error(_.message);he.success("Action item added"),n==null||n(),t(!1),i(""),o(""),d("")};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ne,{placeholder:"Title",value:a,onChange:_=>i(_.target.value)}),e.jsx(pr,{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(Ne,{type:"date",value:c,onChange:_=>d(_.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(Ds,{value:u,onValueChange:m,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"low",children:"Low"}),e.jsx(lt,{value:"medium",children:"Medium"}),e.jsx(lt,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{onClick:y,disabled:f,children:"Add"})]})]})})}function Pke({value:s,size:t=16,onChange:r}){return e.jsx("div",{className:"flex items-center gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(n),disabled:!r,className:r?"cursor-pointer":"cursor-default",children:e.jsx(fa,{style:{width:t,height:t},className:n<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},n))})}function FZt({coachId:s}){const[t,r]=k.useState([]),[n,a]=k.useState(!0);k.useEffect(()=>{(async()=>{const{data:l}=await U.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(m=>m.agent_id),{data:d}=await U.from("profiles").select("id, name, avatar_url").in("id",c),u=new Map((d||[]).map(m=>[m.id,m]));o.forEach(m=>m.profile=u.get(m.agent_id))}r(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return n||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Pke,{value:Math.round(i)}),e.jsxs("span",{children:[i.toFixed(1)," · ",t.length," review",t.length===1?"":"s"]})]})]}),e.jsx("div",{className:"space-y-3",children:t.map(l=>{var o,c,d;return e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Wn,{className:"h-9 w-9",children:[e.jsx(Xa,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(Kn,{children:(((c=l.profile)==null?void 0:c.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:((d=l.profile)==null?void 0:d.name)||"Agent"}),e.jsx(Pke,{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 zZt({coachId:s,assignmentId:t}){const{user:r}=Cs(),[n,a]=k.useState(null),[i,l]=k.useState(0),[o,c]=k.useState(""),[d,u]=k.useState(""),[m,f]=k.useState(!1);k.useEffect(()=>{r&&(async()=>{const{data:y}=await U.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",r.id).maybeSingle();y&&(a(y),l(y.rating),c(y.title||""),u(y.body||""))})()},[r,s]);const x=async()=>{if(!r)return;if(!i)return he.error("Pick a rating");f(!0);const y={coach_id:s,agent_id:r.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:_}=n?await U.from("coaching_reviews").update(y).eq("id",n.id):await U.from("coaching_reviews").insert(y);if(f(!1),_)return he.error(_.message);he.success("Thanks for your review!"),a({...y,id:n==null?void 0:n.id})};return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:n?"Your review":"Leave a review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Help other agents find a great coach."})]}),e.jsx(Pke,{value:i,size:28,onChange:l}),e.jsx(Ne,{placeholder:"Title (optional)",value:o,onChange:y=>c(y.target.value)}),e.jsx(pr,{rows:4,placeholder:"What was your experience like?",value:d,onChange:y=>u(y.target.value)}),e.jsx(q,{onClick:x,disabled:m,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:m?"Saving…":n?"Update review":"Submit review"})]})})}function BZt(){var m,f,x,y,_,b;const{user:s}=Cs(),{data:t,isLoading:r,refetch:n}=wZt(),a=is(),i=t==null?void 0:t.id,{data:l=[]}=xct(i),{data:o=[]}=gct(i);if(k.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&U.functions.invoke("coaching-verify-checkout").then(()=>{n(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[n,a]),r)return e.jsx(ws,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(ws,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(ch,{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(ws,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(ke,{className:"overflow-hidden",children:e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs(Wn,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(Xa,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(Kn,{className:"text-2xl bg-white/20 text-white",children:(((f=c.coachProfile)==null?void 0:f.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(Ir,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((x=c.coachProfile)==null?void 0:x.name)||"Your Coach"}),((y=c.coach)==null?void 0:y.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((_=c.coach)==null?void 0:_.is_certified)&&e.jsx(Xe,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(Xe,{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(__e,{icon:l2,label:"Open action items",value:d.length}),e.jsx(__e,{icon:Hu,label:"Completed",value:u}),e.jsx(__e,{icon:vn,label:"Sessions",value:l.length})]}),((b=c.coach)==null?void 0:b.id)&&e.jsx(zZt,{coachId:c.coach.id,assignmentId:i}),e.jsxs(ta,{defaultValue:"actions",children:[e.jsxs(ea,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(rs,{value:"actions",children:[e.jsx(l2,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(rs,{value:"sessions",children:[e.jsx(vn,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(rs,{value:"goals",children:[e.jsx(Hu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(rs,{value:"kpis",children:[e.jsx(Wo,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(rs,{value:"messages",children:[e.jsx(Ui,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(rs,{value:"files",children:[e.jsx(Kf,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(fs,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(j=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-3 flex items-center gap-3",children:[e.jsx(Ri,{checked:j.status==="done",onCheckedChange:async N=>{await U.from("coaching_action_items").update({status:N?"done":"open",completed_at:N?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(Xe,{variant:"outline",children:As(new Date(j.due_date),"MMM d")}),e.jsx(Xe,{variant:"secondary",className:"capitalize",children:j.priority})]})},j.id))}),e.jsx(fs,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(j=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:As(new Date(j.scheduled_at),"PPp")}),e.jsx(Xe,{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(fs,{value:"goals",children:e.jsx(kct,{assignmentId:i,canEdit:!1})}),e.jsx(fs,{value:"kpis",children:s&&e.jsx(Nct,{agentUserId:s.id})}),e.jsx(fs,{value:"messages",children:e.jsx(yct,{assignmentId:i})}),e.jsx(fs,{value:"files",children:e.jsx(Sct,{assignmentId:i})})]})]})})}function __e({icon:s,label:t,value:r}){return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:r}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}function $Zt(){const s=is(),[t,r]=k.useState(""),[n,a]=k.useState([]),[i,l]=k.useState(null),{data:o=[],isLoading:c}=pt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:m,error:f}=await U.from("coaches").select("*").order("created_at",{ascending:!1});if(f)throw f;if(!(m!=null&&m.length))return[];const x=m.map(b=>b.user_id),{data:y}=await U.from("profiles").select("id, name, email, avatar_url").in("id",x),_=new Map((y||[]).map(b=>[b.id,b]));return m.map(b=>({...b,profile:_.get(b.user_id)}))}});k.useEffect(()=>{const m=t.trim();if(m.length<2){a([]);return}const f=setTimeout(async()=>{const{data:x}=await U.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${m}%,name.ilike.%${m}%`).limit(10);a(x||[])},250);return()=>clearTimeout(f)},[t]);const d=async m=>{const{error:f}=await U.functions.invoke("manage-user-roles",{body:{userId:m.id,role:"coach",action:"add"}});if(f)return he.error(f.message);const{error:x}=await U.from("coaches").insert({user_id:m.id});if(x&&!String(x.message).includes("duplicate"))return he.error(x.message);he.success(`${m.name||m.email} is now a coach`),r(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(m,f)=>{const{error:x}=await U.from("coaches").update({is_certified:f}).eq("id",m);if(x)return he.error(x.message);he.success(f?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(ws,{title:"Coaching Admin",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ch,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsx(UZt,{}),e.jsx(VZt,{}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsx(Ne,{placeholder:"Search by user email or name…",value:t,onChange:m=>r(m.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:n.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):n.map(m=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:m.name||m.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:m.email})]}),e.jsxs(q,{size:"sm",onClick:()=>d(m),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},m.id))})]})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Coaches"}),c?e.jsx("div",{children:"Loading…"}):o.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(m=>{var f,x,y;return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((f=m.profile)==null?void 0:f.name)||((x=m.profile)==null?void 0:x.email)||m.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(y=m.profile)==null?void 0:y.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[m.is_certified&&e.jsxs(Xe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"Certified"]}),m.accepting_clients&&e.jsx(Xe,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>l(m.id),children:[e.jsx(xl,{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(Rr,{checked:m.is_certified,onCheckedChange:_=>u(m.id,_)})]})]})},m.id)})})]})]}),e.jsx(qZt,{coachId:i,onClose:()=>l(null)})]})}function UZt(){const[s,t]=k.useState("1500"),[r,n]=k.useState(!1),[a,i]=k.useState(!1);k.useEffect(()=>{(async()=>{const{data:c}=await U.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return he.error("Enter a value between 0 and 5000 bps (0–50%)");n(!0);const{error:d}=await U.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(n(!1),d)return he.error(d.message);he.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(UE,{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(ce,{children:"Fee (bps)"}),e.jsx(Ne,{type:"number",value:s,onChange:c=>t(c.target.value),min:0,max:5e3}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["= ",o,"%"]})]}),e.jsx(q,{onClick:l,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:r?"Saving…":"Save"})]})]})})}function qZt({coachId:s,onClose:t}){const[r,n]=k.useState(""),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=is();k.useEffect(()=>{if(!s){n(""),i([]);return}},[s]),k.useEffect(()=>{const u=r.trim();if(u.length<2){i([]);return}o(!0);const m=setTimeout(async()=>{const{data:f}=await U.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(f||[]),o(!1)},250);return()=>clearTimeout(m)},[r]);const d=async u=>{const{error:m}=await U.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(m)return he.error(m.message);he.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(vs,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Assign Agent"})}),e.jsx(Ne,{placeholder:"Search agents by name or email…",value:r,onChange:u=>n(u.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:r.trim().length<2?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Type at least 2 characters to search…"}):l?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Searching…"}):a.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No agents found"}):a.map(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(fn,{children:e.jsx(q,{variant:"outline",onClick:t,children:"Close"})})]})})}function VZt(){const s=is(),[t,r]=k.useState("pending"),[n,a]=k.useState(null),{data:i=[],isLoading:l}=pt({queryKey:["coach-applications",t],queryFn:async()=>{let u=U.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:m,error:f}=await u;if(f)throw f;return m||[]}}),{data:o=0}=pt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await U.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,m)=>{const{error:f}=await U.from("coach_applications").update({status:m,reviewed_at:new Date().toISOString()}).eq("id",u);if(f)return he.error(f.message);he.success(`Marked ${m}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(Xe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(la,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(Xe,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx($r,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(Xe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(jn,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(ke,{children:[e.jsxs(Pe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(n2,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(Xe,{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(q,{size:"sm",variant:t===u?"default":"outline",onClick:()=>r(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(Ks,{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(vs,{open:!!n,onOpenChange:u=>!u&&a(null),children:e.jsx(ys,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:n&&e.jsxs(e.Fragment,{children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-3",children:[n.full_name,d(n.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(N6,{icon:Ks,label:"Email",value:n.email,link:`mailto:${n.email}`}),n.phone&&e.jsx(N6,{icon:Mn,label:"Phone",value:n.phone,link:`tel:${n.phone}`}),n.brokerage&&e.jsx(N6,{label:"Brokerage",value:n.brokerage}),n.years_experience&&e.jsx(N6,{label:"Years",value:n.years_experience}),n.website_url&&e.jsx(N6,{icon:un,label:"Website",value:n.website_url,link:n.website_url}),n.linkedin_url&&e.jsx(N6,{icon:un,label:"LinkedIn",value:n.linkedin_url,link:n.linkedin_url})]}),n.specialties&&e.jsx(w_e,{label:"Specialties",children:n.specialties}),e.jsx(w_e,{label:"Why they want to coach",children:n.why_coach}),n.results_story&&e.jsx(w_e,{label:"Results story",children:n.results_story}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(pr,{defaultValue:n.admin_notes||"",rows:3,onBlur:async u=>{const m=u.target.value;m!==(n.admin_notes||"")&&(await U.from("coach_applications").update({admin_notes:m}).eq("id",n.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(fn,{className:"gap-2 flex-wrap",children:[n.status!=="rejected"&&e.jsxs(q,{variant:"outline",onClick:()=>c(n.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx($r,{className:"h-4 w-4 mr-1"})," Reject"]}),n.status!=="pending"&&e.jsxs(q,{variant:"outline",onClick:()=>c(n.id,"pending"),children:[e.jsx(jn,{className:"h-4 w-4 mr-1"})," Move to pending"]}),n.status!=="approved"&&e.jsxs(q,{onClick:()=>c(n.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(la,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function N6({icon:s,label:t,value:r,link:n}){const a=e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s&&e.jsx(s,{className:"h-3.5 w-3.5"}),r]});return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase text-muted-foreground tracking-wide",children:t}),e.jsx("div",{className:"text-sm",children:n?e.jsx("a",{href:n,target:"_blank",rel:"noreferrer",className:"text-[#406E71] hover:underline break-all",children:a}):a})]})}function w_e({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 HZt(){const s=qr(),{data:t}=CB(),r=is(),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),{data:d,refetch:u}=pt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b}=await U.functions.invoke("coach-stripe-status");return b}}),{data:m=[]}=pt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b}=await U.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return b||[]}});k.useEffect(()=>{const b=new URLSearchParams(window.location.search);(b.get("onboarded")||b.get("refresh"))&&u()},[u]);const f=async()=>{var C,A;a(!0);const{data:b,error:j}=await U.functions.invoke("coach-stripe-connect");a(!1);let N=b==null?void 0:b.error;if(!N&&j)try{const E=await((A=(C=j==null?void 0:j.context)==null?void 0:C.json)==null?void 0:A.call(C));N=(E==null?void 0:E.error)||j.message}catch{N=j.message}if(N)return he.error(N,{duration:1e4});b!=null&&b.url&&(window.location.href=b.url)},x=d||{},y=!!(t!=null&&t.use_platform_stripe),_=y||x.connected&&x.charges_enabled;return e.jsx(ws,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(S0,{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(Xe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(qn,{className:"h-3 w-3"})," ",y?"Using LevelUp billing":"Connected"]}):x.connected?e.jsxs(Xe,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(go,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(Xe,{variant:"outline",children:"Not connected"})]}),!y&&e.jsxs(q,{onClick:f,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[_?"Update Stripe details":x.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(un,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages"}),e.jsxs(q,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!_,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!_&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:m.map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[b.name,b.is_active&&b.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(b.price_cents/100).toFixed(0)," / ",b.billing_interval,!b.is_active&&" · Inactive"]})]}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{c(b),l(!0)},children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:async()=>{confirm("Delete this package?")&&(await U.from("coaching_packages").delete().eq("id",b.id),r.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(zr,{className:"h-4 w-4"})})]},b.id))})]})}),e.jsx(GZt,{open:i,onOpenChange:l,coachId:t==null?void 0:t.id,pkg:o,onSaved:()=>r.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]})})]})})}function GZt({open:s,onOpenChange:t,coachId:r,pkg:n,onSaved:a}){const[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[m,f]=k.useState("month"),[x,y]=k.useState(!0),[_,b]=k.useState(!0),[j,N]=k.useState(!1);k.useEffect(()=>{s&&(l((n==null?void 0:n.name)||""),c((n==null?void 0:n.description)||""),u(n?(n.price_cents/100).toString():""),f((n==null?void 0:n.billing_interval)||"month"),y((n==null?void 0:n.is_active)??!0),b((n==null?void 0:n.accepting_clients)??!0))},[s,n]);const C=async()=>{if(!i.trim()||!d)return he.error("Name and price required");N(!0);const A={coach_id:r,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:m,is_active:x,accepting_clients:_},{error:E}=n!=null&&n.id?await U.from("coaching_packages").update(A).eq("id",n.id):await U.from("coaching_packages").insert(A);if(N(!1),E)return he.error(E.message);he.success("Saved"),a==null||a(),t(!1)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:n!=null&&n.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ne,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:A=>l(A.target.value)}),e.jsx(pr,{rows:3,placeholder:"What's included",value:o,onChange:A=>c(A.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(Ne,{type:"number",value:d,onChange:A=>u(A.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(Ds,{value:m,onValueChange:f,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"month",children:"Monthly"}),e.jsx(lt,{value:"year",children:"Yearly"}),e.jsx(lt,{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:x,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=>b(A.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Accepting new clients"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Uncheck if you're booked full — visitors will still see the package but can't sign up."})]})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{onClick:C,disabled:j,children:n!=null&&n.id?"Save":"Create"})]})]})})}function _ze({kind:s,value:t,onChange:r}){const n=k.useRef(null),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),u=k.useRef(null),m=k.useRef(null),f=k.useRef(null),x=k.useRef([]),[y,_]=k.useState(!1),b=s==="photo"?"image/*":"video/*",j=s==="photo"?10*1024*1024:200*1024*1024,N=async(F,O)=>{var te;const{data:B}=await U.auth.getUser(),K=(te=B.user)==null?void 0:te.id;if(!K)return he.error("Not signed in");if(F.size>j)return he.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const Z=`${K}/${s}-${Date.now()}.${O}`,{error:Q}=await U.storage.from("coach-media").upload(Z,F,{upsert:!0,contentType:F.type||(s==="photo"?"image/jpeg":"video/webm")});if(Q)return i(!1),he.error(Q.message);const{data:W}=await U.storage.from("coach-media").createSignedUrl(Z,60*60*24*365*10);i(!1),W!=null&&W.signedUrl&&(r(W.signedUrl),he.success("Uploaded"),d(null))},C=async F=>{const O=F.name.split(".").pop()||(s==="photo"?"jpg":"webm");await N(F,O)},A=async()=>{try{const F=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});m.current=F,_(!0),setTimeout(()=>{u.current&&(u.current.srcObject=F,u.current.play())},50);const O=new MediaRecorder(F,{mimeType:"video/webm"});x.current=[],O.ondataavailable=B=>B.data.size>0&&x.current.push(B.data),O.onstop=()=>{const B=new Blob(x.current,{type:"video/webm"});d(B),F.getTracks().forEach(K=>K.stop())},f.current=O,O.start(),o(!0)}catch(F){he.error(F.message||"Could not access camera")}},E=()=>{var F;(F=f.current)==null||F.stop(),o(!1)},D=()=>{var F;(F=m.current)==null||F.getTracks().forEach(O=>O.stop()),_(!1),o(!1),d(null)},R=async()=>{c&&(await N(c,"webm"),D())};return k.useEffect(()=>()=>{var F;return(F=m.current)==null?void 0:F.getTracks().forEach(O=>O.stop())},[]),e.jsxs("div",{className:"space-y-2",children:[t&&e.jsx("div",{className:"rounded-lg overflow-hidden border bg-muted/30",children:s==="photo"?e.jsx("img",{src:t,alt:"Profile",className:"w-32 h-32 object-cover"}):e.jsx("video",{src:t,controls:!0,className:"w-full max-h-64"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:n,type:"file",accept:b,className:"hidden",onChange:F=>{var B;const O=(B=F.target.files)==null?void 0:B[0];O&&C(O),F.target.value=""}}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var F;return(F=n.current)==null?void 0:F.click()},children:[a?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ka,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:A,disabled:a||y,children:[e.jsx(Tp,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(""),children:[e.jsx(zr,{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(q,{type:"button",size:"sm",onClick:E,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(C0,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(q,{type:"button",size:"sm",onClick:()=>{var F;return(F=f.current)==null?void 0:F.start()},children:[e.jsx(bn,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(q,{type:"button",size:"sm",onClick:R,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(q,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),A()},children:"Re-record"})]}),e.jsx(q,{type:"button",size:"sm",variant:"ghost",onClick:D,children:"Cancel"})]})]})]})}function WZt(){const s=qr(),{data:t,isLoading:r}=CB(),n=is(),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,m]=k.useState(""),[f,x]=k.useState(""),[y,_]=k.useState(!1),[b,j]=k.useState([]),[N,C]=k.useState(""),[A,E]=k.useState(!1);k.useEffect(()=>{if(!t)return;const B=t;i(B.slug||""),o(B.headline||""),d(B.bio||""),m(B.photo_url||""),x(B.intro_video_url||""),_(!!B.accepting_clients),j(B.specialties||[])},[t]);const D=async()=>{if(!t)return;E(!0);const{error:B}=await U.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:f||null,accepting_clients:y,specialties:b}).eq("id",t.id);if(E(!1),B)return he.error(B.message);he.success("Profile saved"),n.invalidateQueries({queryKey:["my-coach-profile"]})},R=()=>{const B=N.trim();if(B){if(b.includes(B))return C("");j([...b,B]),C("")}};if(r)return e.jsx(ws,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(ws,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const F=t,O=F.slug?`${window.location.origin}/coaches/${F.slug}`:null;return e.jsx(ws,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[O&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>window.open(O,"_blank"),children:[e.jsx(un,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(q,{onClick:D,disabled:A,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," ",A?"Saving…":"Save"]})]})]}),F.is_certified&&e.jsxs("div",{className:"rounded-lg border border-yellow-300/50 bg-yellow-50 dark:bg-yellow-950/20 px-4 py-3 text-sm",children:["✨ ",e.jsx("strong",{children:"LevelUp Certified"})," — Your profile displays a verified badge."]}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Accepting new clients"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When off, you're hidden from the public directory."})]}),e.jsx(Rr,{checked:y,onCheckedChange:_})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Public URL slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"/coaches/"}),e.jsx(Ne,{value:a,onChange:B=>i(B.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Headline"}),e.jsx(Ne,{value:l,onChange:B=>o(B.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Bio"}),e.jsx(pr,{rows:6,value:c,onChange:B=>d(B.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(ce,{children:"Profile photo"}),e.jsx(_ze,{kind:"photo",value:u,onChange:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Intro video"}),e.jsx(_ze,{kind:"video",value:f,onChange:x})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:b.map(B=>e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[B,e.jsx("button",{onClick:()=>j(b.filter(K=>K!==B)),children:e.jsx($r,{className:"h-3 w-3"})})]},B))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:N,onChange:B=>C(B.target.value),placeholder:"Add a specialty…",onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),R())}}),e.jsx(q,{type:"button",variant:"outline",onClick:R,children:e.jsx(Ys,{className:"h-4 w-4"})})]})]})]})}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages & Stripe"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your monetized packages on the Billing page."})]}),e.jsx(q,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(KZt,{coachId:F.id})]})})}function KZt({coachId:s}){const[t,r]=k.useState("");is();const{data:n=[],refetch:a}=pt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await U.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return he.error("Email required");const{error:d}=await U.from("coaching_invites").insert({coach_id:s,email:c});if(d)return he.error(d.message);r(""),he.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),he.success("Link copied")},o=async c=>{confirm("Revoke this invite?")&&(await U.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(tl,{className:"h-5 w-5"})," Invite agents"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a magic link to onboard agents directly."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"agent@email.com",value:t,onChange:c=>r(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(q,{onClick:i,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.map(c=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:c.email}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.status," · expires ",new Date(c.expires_at).toLocaleDateString()]})]}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(si,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(zr,{className:"h-4 w-4"})})]},c.id)),n.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"No invites yet."})]})]})})}const wq=[{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 YZt(){const s=qr(),t=is(),{data:r,isLoading:n}=CB(),[a,i]=k.useState("pending"),[l,o]=k.useState(""),[c,d]=k.useState(null),[u,m]=k.useState(!1),[f,x]=k.useState(""),[y,_]=k.useState(!1),[b,j]=k.useState(""),{data:N=[],isLoading:C}=pt({queryKey:["coaching-waitlist",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:B,error:K}=await U.from("coaching_waitlist").select("*").eq("coach_id",r.id).order("created_at",{ascending:!1});if(K)throw K;return B||[]}}),A=k.useMemo(()=>N.filter(B=>{if(a!=="all"&&B.status!==a)return!1;if(l){const K=l.toLowerCase();return(B.name||"").toLowerCase().includes(K)||(B.email||"").toLowerCase().includes(K)||(B.brokerage||"").toLowerCase().includes(K)}return!0}),[N,a,l]),E=k.useMemo(()=>{const B={all:N.length};for(const K of wq)B[K.value]=0;for(const K of N)B[K.status]=(B[K.status]||0)+1;return B},[N]),D=async(B,K)=>{const{error:Z}=await U.from("coaching_waitlist").update(K).eq("id",B);if(Z)return he.error(Z.message);t.invalidateQueries({queryKey:["coaching-waitlist",r==null?void 0:r.id]}),(c==null?void 0:c.id)===B&&d(Q=>({...Q,...K}))},R=async B=>{if(!confirm("Remove this person from the waitlist?"))return;const{error:K}=await U.from("coaching_waitlist").delete().eq("id",B);if(K)return he.error(K.message);he.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",r==null?void 0:r.id]}),d(null)},F=async()=>{if(!c)return;const{data:B,error:K}=await U.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:f}});if(K||B!=null&&B.error)return he.error((B==null?void 0:B.error)||(K==null?void 0:K.message)||"Could not send invite");he.success(`Invite sent to ${c.name}`),m(!1),x(""),t.invalidateQueries({queryKey:["coaching-waitlist",r==null?void 0:r.id]})},O=async()=>{if(!r)return;const{data:B,error:K}=await U.functions.invoke("coaching-waitlist-invite",{body:{coachId:r.id,notifyAll:!0,message:b}});if(K||B!=null&&B.error)return he.error((B==null?void 0:B.error)||(K==null?void 0:K.message)||"Could not notify");he.success(`Notified ${(B==null?void 0:B.count)||0} agents`),_(!1),j(""),t.invalidateQueries({queryKey:["coaching-waitlist",r==null?void 0:r.id]})};return n?e.jsx(ws,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):r?e.jsxs(ws,{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(q,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(Aa,{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(k1,{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(q,{variant:"outline",onClick:()=>_(!0),disabled:!E.pending,title:E.pending?"":"No pending applicants",children:[e.jsx(JI,{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,")"]}),wq.map(B=>e.jsxs("button",{onClick:()=>i(B.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===B.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[B.label," (",E[B.value]||0,")"]},B.value))]}),e.jsx(Ne,{placeholder:"Search by name, email, brokerage…",value:l,onChange:B=>o(B.target.value),className:"max-w-md"}),C?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):A.length===0?e.jsx(ke,{children:e.jsx(Pe,{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(B=>{const K=wq.find(Z=>Z.value===B.status);return e.jsx(ke,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(B),children:e.jsxs(Pe,{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:B.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:B.email}),B.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:B.brokerage})]}),e.jsx(Xe,{className:(K==null?void 0:K.tone)||"",children:(K==null?void 0:K.label)||B.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",Nl(new Date(B.created_at),{addSuffix:!0})]}),B.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",B.preferred_package]})]})]})},B.id)})})]}),e.jsx(vs,{open:!!c,onOpenChange:B=>!B&&d(null),children:e.jsx(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:c.name}),e.jsxs(an,{children:["Joined ",Nl(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(VR,{label:"Email",value:c.email}),e.jsx(VR,{label:"Phone",value:c.phone}),e.jsx(VR,{label:"Brokerage",value:c.brokerage}),e.jsx(VR,{label:"Years",value:c.years_in_business}),e.jsx(VR,{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 ",Nl(new Date(c.invited_at),{addSuffix:!0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Status"}),e.jsxs(Ds,{value:c.status,onValueChange:B=>D(c.id,{status:B}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:wq.map(B=>e.jsx(lt,{value:B.value,children:B.label},B.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(pr,{rows:3,defaultValue:c.coach_notes||"",onBlur:B=>{B.target.value!==(c.coach_notes||"")&&D(c.id,{coach_notes:B.target.value})}})]})]}),e.jsxs(fn,{className:"flex-wrap gap-2",children:[e.jsxs(q,{variant:"outline",className:"text-destructive",onClick:()=>R(c.id),children:[e.jsx(zr,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx(q,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(Ks,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(q,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{x(""),m(!0)},children:[e.jsx(hn,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(vs,{open:u,onOpenChange:m,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Invite to subscribe"}),e.jsxs(an,{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(pr,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:f,onChange:B=>x(B.target.value)})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsxs(q,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:F,children:[e.jsx(hn,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(vs,{open:y,onOpenChange:_,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Notify all pending applicants"}),e.jsx(an,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(pr,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:b,onChange:B=>j(B.target.value)}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsxs(q,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:O,children:[e.jsx(JI,{className:"h-4 w-4 mr-1"})," Send to ",E.pending||0," agents"]})]})]})})]}):e.jsx(ws,{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 VR({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 ZZt(){const{data:s=[],isLoading:t}=pt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:r,error:n}=await U.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(n)throw n;const a=(r||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await U.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(r||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(Ir,{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(qn,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wo,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-4 w-4 text-yellow-300"})," Real, measurable results"]})]})]}),e.jsx("svg",{className:"block w-full text-white",viewBox:"0 0 1440 60",preserveAspectRatio:"none","aria-hidden":!0,children:e.jsx("path",{fill:"currentColor",d:"M0,40 C360,80 1080,0 1440,40 L1440,60 L0,60 Z"})})]}),e.jsxs("section",{className:"max-w-6xl mx-auto px-4 py-16 md:py-20",children:[t?e.jsx("div",{className:"text-center text-muted-foreground",children:"Loading coaches…"}):s.length===0?e.jsx("div",{className:"text-center text-muted-foreground",children:"No coaches available yet. Check back soon."}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:s.map(r=>{var i,l;const n=((i=r.profile)==null?void 0:i.name)||"Coach",a=r.photo_url||((l=r.profile)==null?void 0:l.avatar_url);return e.jsx(Vn,{to:`/coaches/${r.slug||r.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:n,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:n.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[r.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(Ir,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${r.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.accepting_clients?"bg-white":"bg-amber-500"}`}),r.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:n}),r.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:r.headline}),r.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:r.bio}),r.specialties&&r.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:r.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(ci,{className:"h-4 w-4"})})]})]})]})})},r.id)})}),e.jsxs("div",{className:"mt-20 rounded-3xl bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white p-10 md:p-14 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"18px 18px"}}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-yellow-300/15 blur-3xl"}),e.jsxs("div",{className:"relative md:flex items-center gap-10",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 border border-white/15 text-[11px] uppercase tracking-[0.18em] font-semibold mb-5",children:[e.jsx(Ir,{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(qn,{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(qn,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(qn,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(Vn,{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(ci,{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 XZt=tw({name:ho().trim().min(1,"Name required").max(120),email:ho().trim().email("Invalid email").max(255),phone:ho().trim().max(40).optional().or(tf("")),brokerage:ho().trim().max(160).optional().or(tf("")),years_in_business:ho().max(40).optional().or(tf("")),biggest_challenge:ho().trim().max(1e3).optional().or(tf("")),preferred_package:ho().max(120).optional().or(tf("")),message:ho().trim().max(1500).optional().or(tf(""))});function QZt({open:s,onOpenChange:t,coachId:r,coachName:n,packages:a=[]}){const{user:i}=Cs(),[l,o]=k.useState(!1),[c,d]=k.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(f,x)=>d(y=>({...y,[f]:x})),m=async()=>{var y;const f=XZt.safeParse(c);if(!f.success){he.error(((y=f.error.issues[0])==null?void 0:y.message)||"Please check your entries");return}o(!0);const{error:x}=await U.from("coaching_waitlist").insert({coach_id:r,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),x){he.error(x.message||"Could not join waitlist");return}he.success(`You're on the waitlist${n?` for ${n}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{children:["Join the waitlist",n?` — ${n}`:""]}),e.jsx(an,{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(ce,{children:"Name *"}),e.jsx(Ne,{value:c.name,onChange:f=>u("name",f.target.value)})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Email *"}),e.jsx(Ne,{type:"email",value:c.email,onChange:f=>u("email",f.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Phone"}),e.jsx(Ne,{value:c.phone,onChange:f=>u("phone",f.target.value)})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Brokerage"}),e.jsx(Ne,{value:c.brokerage,onChange:f=>u("brokerage",f.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Years in business"}),e.jsxs(Ds,{value:c.years_in_business,onValueChange:f=>u("years_in_business",f),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select…"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(lt,{value:"1-3 years",children:"1-3 years"}),e.jsx(lt,{value:"4-7 years",children:"4-7 years"}),e.jsx(lt,{value:"8-15 years",children:"8-15 years"}),e.jsx(lt,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(ce,{children:"Preferred package"}),e.jsxs(Ds,{value:c.preferred_package,onValueChange:f=>u("preferred_package",f),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Any"})}),e.jsx(Ls,{children:a.map(f=>e.jsx(lt,{value:f.name,children:f.name},f.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Biggest challenge right now"}),e.jsx(pr,{rows:2,value:c.biggest_challenge,onChange:f=>u("biggest_challenge",f.target.value)})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Anything else?"}),e.jsx(pr,{rows:2,value:c.message,onChange:f=>u("message",f.target.value)})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx(q,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:m,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function JZt(){var _;const{slug:s}=xo(),t=qr(),{user:r}=Cs(),[n,a]=k.useState(null),[i,l]=k.useState(!1),{data:o,isLoading:c}=pt({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const b=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),j=U.from("coaches").select("*"),{data:N}=b?await j.eq("id",s).maybeSingle():await j.eq("slug",s).maybeSingle();if(!N)return null;const[{data:C},{data:A}]=await Promise.all([U.from("profiles").select("id, name, avatar_url").eq("id",N.user_id).maybeSingle(),U.from("coaching_packages").select("*").eq("coach_id",N.id).eq("is_active",!0).order("sort_order")]);return{coach:N,profile:C,packages:A||[]}}}),d=async b=>{if(!r){he.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(b);const{data:j,error:N}=await U.functions.invoke("create-coaching-checkout",{body:{packageId:b}});if(a(null),N||j!=null&&j.error){he.error((j==null?void 0:j.error)||(N==null?void 0:N.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:m,packages:f}=o,x=u,y=(b,j)=>{const N=(b/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return j==="one_time"?N:`${N} / ${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(q,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(Aa,{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(Wn,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(Xa,{src:x.photo_url||(m==null?void 0:m.avatar_url)}),e.jsx(Kn,{className:"text-3xl bg-white/20",children:((m==null?void 0:m.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[x.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(Ir,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(m==null?void 0:m.name)||"Coach"}),x.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:x.headline}),((_=x.specialties)==null?void 0:_.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:x.specialties.map(b=>e.jsx(Xe,{className:"bg-white/15 text-white border-white/20",children:b},b))})]})]})]})}),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:[x.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:x.intro_video_url,controls:!0,className:"w-full h-full"})}),x.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:x.bio})]}),e.jsx(FZt,{coachId:x.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"}),f.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):f.map(b=>{const j=b.accepting_clients===!1;return e.jsx(ke,{className:`border-2 transition-colors ${j?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Pe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:b.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"})]}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:b.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:y(b.price_cents,b.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(q,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(k1,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(q,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(b.id),disabled:n===b.id,children:[n===b.id?"Loading…":"Get Started",e.jsx(la,{className:"h-4 w-4 ml-1"})]})]})},b.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."}),e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(k1,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(QZt,{open:i,onOpenChange:l,coachId:x.id,coachName:m==null?void 0:m.name,packages:f.map(b=>({id:b.id,name:b.name}))})]})}const eXt=tw({full_name:ho().trim().min(2,"Please enter your full name").max(100),email:ho().trim().email("Enter a valid email").max(255),phone:ho().trim().max(40).optional().or(tf("")),brokerage:ho().trim().max(150).optional().or(tf("")),years_experience:ho().trim().max(40).optional().or(tf("")),specialties:ho().trim().max(500).optional().or(tf("")),why_coach:ho().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:ho().trim().max(2e3).optional().or(tf("")),website_url:ho().trim().max(300).optional().or(tf("")),linkedin_url:ho().trim().max(300).optional().or(tf(""))});function tXt(){const s=qr(),[t,r]=k.useState(!1),[n,a]=k.useState(!1),[i,l]=k.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,u)=>l(m=>({...m,[d]:u})),c=async d=>{var f;d.preventDefault();const u=eXt.safeParse(i);if(!u.success){const x=(f=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:f[0];return he.error(x||"Please check the form and try again")}r(!0);const{error:m}=await U.from("coach_applications").insert(u.data);if(r(!1),m)return he.error(m.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return n?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(qn,{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(q,{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(Vn,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(Aa,{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(Ir,{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(Dr,{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(Wo,{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(Uc,{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(qn,{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(wo,{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(fa,{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(Db,{label:"Full name *",children:e.jsx(Ne,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(Db,{label:"Email *",children:e.jsx(Ne,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(Db,{label:"Phone",children:e.jsx(Ne,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(Db,{label:"Current brokerage",children:e.jsx(Ne,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(Db,{label:"Years in real estate",children:e.jsx(Ne,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(Db,{label:"Coaching specialties",children:e.jsx(Ne,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(Db,{label:"Website",children:e.jsx(Ne,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(Db,{label:"LinkedIn",children:e.jsx(Ne,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(Db,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(pr,{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(Db,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(pr,{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(q,{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 Db({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const sXt="/assets/testimonial-avatar-1-BsCQFauB.jpg",rXt="/assets/testimonial-avatar-2-B6VPVc2t.jpg",nXt="/assets/testimonial-avatar-3-GuEFwYUE.jpg",aXt="/assets/testimonial-avatar-4-98iKMtkB.jpg",iXt="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",oXt=[sXt,rXt,nXt,aXt,iXt],lXt=tw({name:ho().trim().min(2,"Name must be at least 2 characters").max(100),email:ho().trim().email("Please enter a valid email address").max(255),phone:ho().trim().min(10,"Please enter a valid phone number").max(20).optional().or(tf("")),brokerage:ho().trim().max(200).optional().or(tf(""))}),cXt=[{icon:Ff,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:dl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:vn,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:gc,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:En,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Di,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],dXt=[{icon:Dr,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Ir,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Mn,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:_m,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Ma,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Mo,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:yi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:zh,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],uXt=[{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."}],hXt=()=>{const s=qr(),[t,r]=k.useState(!1),[n,a]=k.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=k.useState({}),o=async c=>{var u,m;c.preventDefault(),l({});const d=lXt.safeParse(n);if(!d.success){const f={};d.error.issues.forEach(x=>{x.path[0]&&(f[x.path[0]]=x.message)}),l(f);return}r(!0);try{const f=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:x,error:y}=await U.functions.invoke("create-trial-signup",{body:{name:n.name.trim(),email:n.email.trim().toLowerCase(),phone:((u=n.phone)==null?void 0:u.trim())||void 0,brokerage:((m=n.brokerage)==null?void 0:m.trim())||void 0,referral_code:f}});if(y){console.error("Trial signup error:",y),he.error(y.message||"Something went wrong. Please try again.");return}if(x!=null&&x.error){he.error(x.error);return}he.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),s("/trial/success")}catch(f){console.error("Trial signup error:",f),he.error("Something went wrong. Please try again.")}finally{r(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:"Start Your Free 7-Day Trial | LevelUp Dashboard"}),e.jsx("meta",{name:"description",content:"Take LevelUp for a free 7-day test drive. No credit card required. The all-in-one platform for real estate agents and brokerages."}),e.jsx("meta",{property:"og:title",content:"Start Your Free 7-Day Trial | LevelUp"}),e.jsx("meta",{property:"og:description",content:"Take LevelUp for a free 7-day test drive. No credit card required."}),e.jsx("meta",{property:"og:type",content:"website"})]}),e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:Sme,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(q,{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(q,{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(Ir,{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(qn,{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(qn,{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:oXt.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(fa,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},c))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]})]}),e.jsx("div",{className:"lg:pl-8",children:e.jsx(ke,{className:"bg-white shadow-2xl border-0",children:e.jsxs(Pe,{className:"p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-[#4a6b6d] mb-4",children:e.jsx(C_,{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(ce,{htmlFor:"name",children:"Full Name *"}),e.jsx(Ne,{id:"name",type:"text",placeholder:"John Smith",value:n.name,onChange:c=>a({...n,name:c.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"email",children:"Email Address *"}),e.jsx(Ne,{id:"email",type:"email",placeholder:"john@example.com",value:n.email,onChange:c=>a({...n,email:c.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"phone",children:"Phone Number"}),e.jsx(Ne,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:n.phone,onChange:c=>a({...n,phone:c.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(Ne,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:n.brokerage,onChange:c=>a({...n,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(q,{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(ls,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(ci,{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:cXt.map((c,d)=>e.jsxs(ke,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Pt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(c.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Dt,{className:"text-xl font-sans",children:c.title})]}),e.jsx(Pe,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:c.description})})]},d))})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(Ir,{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:dXt.map((c,d)=>e.jsxs(ke,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Pt,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(c.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Dt,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(Pe,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:c.description})})]},d))})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold mb-4 font-sans",children:"Loved by Top Producers"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what agents are saying about LevelUp"})]}),e.jsx("div",{className:"grid md:grid-cols-3 gap-8 max-w-5xl mx-auto",children:uXt.map((c,d)=>e.jsx(ke,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Pe,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(u=>e.jsx(fa,{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(Oh,{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(zh,{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(Dr,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Expert Support"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Real estate pros"})]})]})]})})}),e.jsx("section",{id:"free-trial",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs(ke,{className:"bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] border-0 shadow-2xl overflow-hidden relative",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs(Pe,{className:"p-12 text-center relative",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-4 font-sans",children:"Ready to Level Up Your Business?"}),e.jsx("p",{className:"text-xl text-white/80 mb-8 max-w-2xl mx-auto",children:"Join thousands of successful agents. Start your free 7-day trial today."}),e.jsxs(q,{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(ci,{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:ome,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."})]})})})]})]})},mXt=()=>{const s=qr();return e.jsxs(e.Fragment,{children:[e.jsx(Yo,{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:Sme,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(q,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})}),e.jsxs("section",{className:"relative pt-24 pb-12 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden flex-1 flex items-center",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsx("div",{className:"flex justify-center",children:e.jsx(ke,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Pe,{className:"p-8 md:p-12 text-center",children:[e.jsxs("div",{className:"relative inline-block mb-8",children:[e.jsx("div",{className:"w-24 h-24 rounded-full bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] flex items-center justify-center",children:e.jsx(qn,{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(ph,{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(Ks,{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(q,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(ci,{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:ome,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},fXt=tw({viewerName:ho().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:ho().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:ho().max(20,"Phone must be less than 20 characters").optional(),message:ho().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function pXt({shareToken:s,agentName:t,hasContact:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),d=Tge({resolver:Ege(fXt),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async m=>{a(!0),c(null);try{const{data:f,error:x}=await U.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:m.viewerName,viewerEmail:m.viewerEmail,viewerPhone:m.viewerPhone||void 0,message:m.message}});if(x)throw new Error(x.message);if(!(f!=null&&f.success))throw new Error((f==null?void 0:f.error)||"Failed to send reply");l(!0)}catch(f){console.error("Failed to submit reply:",f),c(f.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(ke,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Pe,{className:"py-8 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/20 mb-4",children:e.jsx(qn,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Message Sent!"}),e.jsxs("p",{className:"text-muted-foreground",children:[t?`${t} will`:"They'll"," get back to you soon."]})]})}):e.jsxs(ke,{children:[e.jsxs(Pt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(gc,{className:"h-5 w-5 text-primary"}),e.jsx(Dt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Ur,{children:r?`Have a question or want to connect? Send ${t||"them"} a message.`:`Interested? Share your info and ${t||"your agent"} will be in touch.`})]}),e.jsx(Pe,{children:e.jsx(Age,{...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(au,{control:d.control,name:"viewerName",render:({field:m})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Your Name *"}),e.jsx($d,{children:e.jsx(Ne,{placeholder:"John Smith",...m})}),e.jsx(wx,{})]})}),e.jsx(au,{control:d.control,name:"viewerEmail",render:({field:m})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Email *"}),e.jsx($d,{children:e.jsx(Ne,{type:"email",placeholder:"john@example.com",...m})}),e.jsx(wx,{})]})})]}),!r&&e.jsx(au,{control:d.control,name:"viewerPhone",render:({field:m})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Phone (optional)"}),e.jsx($d,{children:e.jsx(Ne,{type:"tel",placeholder:"(555) 123-4567",...m})}),e.jsx(wx,{})]})}),e.jsx(au,{control:d.control,name:"message",render:({field:m})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Message *"}),e.jsx($d,{children:e.jsx(pr,{placeholder:r?"Thanks for the video! I had a question about...":"I'm interested in learning more about...",className:"min-h-[100px] resize-none",...m})}),e.jsx(wx,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(q,{type:"submit",className:"w-full gap-2",disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const xXt=()=>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(fa,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(fa,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(fa,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(fa,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(fa,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(r2,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),gXt=()=>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(Ir,{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(fa,{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(Ir,{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(fa,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(fa,{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(r2,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),yXt=()=>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(b1,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(b1,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(b1,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(b1,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(yi,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(yi,{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(yi,{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"})]}),vXt=()=>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(Uc,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(fa,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Uc,{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(fa,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(fa,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),bXt=()=>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(b1,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(b1,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(GI,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),_Xt=()=>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(IE,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(IE,{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(Ir,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(Ir,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),wXt=()=>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(uS,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(uS,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(uS,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(_1,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(_1,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(_1,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(_1,{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(fa,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),jXt=()=>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(yi,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(yi,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),NXt=()=>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(fa,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(fa,{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(fa,{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(fa,{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(Ir,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(ph,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(ph,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),kXt=()=>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(fa,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(Ir,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(Ir,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),SXt=()=>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(Wj,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(Wj,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(Wj,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(Wj,{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"})]})]})]}),CXt=()=>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(fa,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(fa,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Uc,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Uc,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(r2,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),TXt=()=>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(_m,{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(ph,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Di,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),EXt=()=>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(yi,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(yi,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(yi,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(yi,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(yi,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(yi,{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(yi,{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(yi,{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"})]}),AXt=()=>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(f2,{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(f2,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(Ir,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(f2,{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"})]}),MXt=()=>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(Pn,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(Pn,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(gg,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(gg,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(yi,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(yi,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(Ir,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(ph,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),IXt=()=>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(ph,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(ph,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(gg,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(Pn,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(Ir,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(Ir,{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"})]}),PXt=()=>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(gg,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(gg,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(gg,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(Pn,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(ph,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(Ir,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(fa,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),LXt=()=>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(Pn,{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(gg,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(yi,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(Ir,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(w_,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),wze=()=>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"})]}),DXt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(yi,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(yi,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(yi,{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(yi,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),RXt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(w_,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(Ir,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(Pn,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),OXt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(EE,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(tP,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(EE,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),HR=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Ir,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(ph,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(Ir,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),jze=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Pn,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(Ir,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(Pn,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),Lke=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(Ir,{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(yi,{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(DXt,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(pF,{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(HR,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(EE,{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(OXt,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(Mo,{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(Dr,{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(HR,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Uc,{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(wze,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(Ma,{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(jze,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(tP,{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(HR,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(_m,{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(TXt,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(yi,{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(EXt,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(f2,{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(AXt,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(fa,{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(NXt,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(GI,{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(bXt,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(b1,{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(yXt,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Uc,{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(vXt,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(r2,{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(xXt,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(ld,{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(gXt,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Uc,{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(CXt,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(IE,{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(_Xt,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(yi,{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(jXt,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(uS,{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(wXt,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(Ir,{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(kXt,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(Wj,{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(SXt,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(Pn,{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(MXt,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(ph,{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(IXt,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(vn,{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(jze,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(Xl,{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(HR,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(E_,{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(w_,{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(RXt,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(gg,{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(PXt,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(Pn,{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(LXt,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(wm,{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(HR,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Uc,{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(wze,{})}],FXt=[{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 zXt(s){return Lke.filter(t=>t.category===s)}function bP(s){return Lke.find(t=>t.id===s)||Lke[0]}function Nze(){const{shareToken:s,recipientToken:t}=xo(),[r,n]=k.useState(null),[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!0),[u,m]=k.useState(null),[f,x]=k.useState(!0),y=k.useRef(null),_=k.useRef(0),b=k.useRef(0),j=(()=>{const Z=new URLSearchParams(window.location.search);return t||Z.get("rt")||null})(),N=k.useCallback((Z,Q=!1)=>{if(!j||Z<=0)return;const W=Math.max(1,Math.round(Z));if(W<=b.current)return;const ne=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(j)}&e=watch&ws=${W}`;Q&&navigator.sendBeacon?navigator.sendBeacon(ne):fetch(ne,{method:"GET",keepalive:Q}).catch(()=>{}),b.current=Math.max(b.current,W)},[j]);k.useEffect(()=>{var ue;if(!f||!(r!=null&&r.playback_url)||!j)return;let Z=!1;const Q=()=>{_.current>0&&N(_.current,!0)},W=()=>{document.visibilityState==="hidden"&&Q()},te=()=>{Q()},ne=()=>{var de;if(Z||!y.current||!((de=window.playerjs)!=null&&de.Player))return;const me=new window.playerjs.Player(y.current);me.on("timeupdate",fe=>{const je=Math.floor(Number((fe==null?void 0:fe.seconds)??0));!Number.isFinite(je)||je<=0||(_.current=Math.max(_.current,je))}),me.on("pause",()=>{_.current>0&&N(_.current)}),me.on("ended",()=>{_.current>0&&N(_.current,!0)})},ae=document.querySelector('script[data-bunny-playerjs="true"]');if((ue=window.playerjs)!=null&&ue.Player)ne();else if(ae)ae.addEventListener("load",ne,{once:!0});else{const me=document.createElement("script");me.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",me.async=!0,me.defer=!0,me.dataset.bunnyPlayerjs="true",me.onload=ne,document.body.appendChild(me)}return document.addEventListener("visibilitychange",W),window.addEventListener("beforeunload",te),()=>{Z=!0,document.removeEventListener("visibilitychange",W),window.removeEventListener("beforeunload",te),Q()}},[f,r==null?void 0:r.playback_url,j,N]),k.useEffect(()=>{_.current=0,b.current=0},[j,s]),k.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(ne=>{document.querySelectorAll(ne).forEach(ae=>{ae.style.display="none"})})};Z();const Q=[setTimeout(Z,500),setTimeout(Z,1500),setTimeout(Z,3e3)],W=new MutationObserver(Z);return W.observe(document.body,{childList:!0,subtree:!0}),()=>{Q.forEach(clearTimeout),W.disconnect()}},[]),k.useEffect(()=>{(async()=>{if(!s){m("Invalid share link"),d(!1);return}const{data:Q,error:W}=await U.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(W||!Q){m("Video not found or has been removed"),d(!1);return}n(Q);try{await U.rpc("log_video_view",{p_video_id:Q.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(te){console.warn("Failed to log video view:",te)}if(Q.owner_user_id){const{data:te}=await U.from("profiles").select("id, name, email, phone").eq("id",Q.owner_user_id).single();if(te){i(te);try{const{data:ne}=await U.storage.from("avatars").list(`${Q.owner_user_id}`);if(ne&&ne.length>0){const{data:ae}=U.storage.from("avatars").getPublicUrl(`${Q.owner_user_id}/${ne[0].name}`);o(ae.publicUrl)}}catch{}}}d(!1)})()},[s]);const C=Z=>{if(!Z)return"0:00";const Q=Math.floor(Z/60),W=Z%60;return`${Q}:${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 Q=Z.split(" ");return Q.length>=2?`${Q[0][0]}${Q[1][0]}`.toUpperCase():Z.substring(0,2).toUpperCase()},D=bP((r==null?void 0:r.page_template)||"default"),R=(r==null?void 0:r.recipient_name)||null,F=D.headerText(R),B=`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(ls,{className:"h-8 w-8 animate-spin text-primary"})});if(u||!r)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(ke,{className:"max-w-md w-full",children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(bn,{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 K=D.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{children:[e.jsx("title",{children:F}),e.jsx("meta",{name:"description",content:D.subText}),e.jsx("meta",{property:"og:title",content:F}),e.jsx("meta",{property:"og:description",content:D.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:B}),r.preview_url&&e.jsx("meta",{property:"og:image",content:r.preview_url}),!r.preview_url&&r.thumbnail_url&&e.jsx("meta",{property:"og:image",content:r.thumbnail_url}),r.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:r.playback_url}),e.jsx("meta",{property:"og:video:type",content:"text/html"}),e.jsx("meta",{property:"og:video:width",content:"1280"}),e.jsx("meta",{property:"og:video:height",content:"720"})]}),e.jsx("meta",{name:"twitter:card",content:"player"}),e.jsx("meta",{name:"twitter:title",content:F}),e.jsx("meta",{name:"twitter:description",content:D.subText}),r.preview_url&&e.jsx("meta",{name:"twitter:image",content:r.preview_url}),r.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{name:"twitter:player",content:r.playback_url}),e.jsx("meta",{name:"twitter:player:width",content:"1280"}),e.jsx("meta",{name:"twitter:player:height",content:"720"})]})]}),e.jsxs("div",{className:zt("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",D.gradientClasses),children:[K&&D.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[K&&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:zt("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",D.accentColor==="primary"&&"bg-primary/10 text-primary",D.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",D.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",D.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",D.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",D.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",D.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",D.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",D.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",D.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",D.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",D.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",D.accentColor==="sky"&&"bg-sky-100 text-sky-600 dark:bg-sky-900/50 dark:text-sky-400"),children:e.jsx("div",{className:"scale-150",children:D.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:F}),e.jsx("p",{className:"text-muted-foreground",children:D.subText})]}),a&&e.jsxs("div",{className:"flex items-center gap-4 p-4 bg-card/90 backdrop-blur-sm rounded-lg border shadow-sm",children:[e.jsxs(Wn,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(Xa,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(Kn,{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:K?"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(q,{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(Mn,{className:"h-4 w-4"})})}),a.email&&e.jsx(q,{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(Ks,{className:"h-4 w-4"})})})]})]}),e.jsx(ke,{className:"overflow-hidden shadow-lg",children:f&&r.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:y,src:A(r.playback_url),title:r.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>x(!0),children:[r.preview_url||r.thumbnail_url?e.jsx("img",{src:r.preview_url||r.thumbnail_url||"",alt:r.title?`${r.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:Z=>{var W;Z.currentTarget.style.display="none";const Q=(W=Z.currentTarget.parentElement)==null?void 0:W.querySelector(".video-fallback");Q&&(Q.style.display="flex")}}):null,e.jsx("div",{className:"video-fallback w-full h-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5",style:{display:r.preview_url||r.thumbnail_url?"none":"flex"},children:e.jsx(bn,{className:"h-16 w-16 text-primary/50"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/40 transition-colors",children:e.jsx("div",{className:"w-20 h-20 rounded-full bg-white/90 flex items-center justify-center shadow-lg transform group-hover:scale-105 transition-transform",children:e.jsx(Al,{className:"h-10 w-10 text-primary ml-1"})})}),r.duration_seconds&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:C(r.duration_seconds)})]})}),!K&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:f?"Enjoy the video!":"Click to play the video"})]}),!f&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(q,{size:"lg",onClick:()=>x(!0),className:"gap-2",children:[e.jsx(Al,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(pXt,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!r.contact_id})]})]})]})}function BXt(){return k.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(pAt,{})}function $Xt(){const{token:s}=xo();return k.useEffect(()=>{if(!s)return;const t=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/video-og-image?token=${s}`;window.location.replace(t)},[s]),e.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(ls,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const UXt={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},qXt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function VXt(){var je;const[s]=ic(),t=s.get("r"),r=s.get("m"),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!0),[d,u]=k.useState(0),[m,f]=k.useState(!1),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState(""),[E,D]=k.useState("tour"),[R,F]=k.useState(!1),[O,B]=k.useState(!1),K=async()=>{if(!x.trim()||!_.trim()){he.error("Please enter your name and email");return}F(!0);try{const Ee=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:r,name:x.trim(),email:_.trim(),phone:j.trim()||null,message:C.trim()||null,intent:E})}),Me=await Ee.json();if(!Ee.ok||!(Me!=null&&Me.success))throw new Error((Me==null?void 0:Me.error)||"Could not send");B(!0),he.success("Sent! The agent will be in touch shortly.")}catch(xe){he.error((xe==null?void 0:xe.message)||"Could not send")}finally{F(!1)}};if(k.useEffect(()=>{if(!t||!r){l("Invalid link"),c(!1);return}const xe=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(r)}`;fetch(xe).then(Ee=>Ee.json()).then(Ee=>{Ee.error?l("This private listing link is no longer valid."):a({listing:Ee.listing,agent:Ee.agent})}).catch(()=>l("Unable to load listing.")).finally(()=>c(!1))},[t,r]),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||!n)return e.jsxs(e.Fragment,{children:[e.jsx(Yo,{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:Q}=n,W=(je=Z.photos)!=null&&je.length?Z.photos:[],te=W[0],ne=UXt[Z.status]||Z.status,ae=(Q==null?void 0:Q.sender_name)||(Q==null?void 0:Q.name)||"Your Agent",ue=(Q==null?void 0:Q.sender_email)||null,me=encodeURIComponent(`Interested in ${Z.address}`),de=encodeURIComponent(`Hi ${ae}, I'd love to learn more about ${Z.address}, ${Z.city}. Thanks!`),fe=Q!=null&&Q.booking_slug?`https://dashboard.relevelup.com/book/${Q.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{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 ",ae]})]}),e.jsxs("div",{className:"relative",children:[te?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),f(!0)},children:e.jsx("img",{src:te,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(Xe,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:ne})}),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(ke,{className:"shadow-xl border-slate-200",children:e.jsxs(Pe,{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(Ma,{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:qXt(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(k0,{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(of,{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(C0,{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((xe,Ee)=>e.jsx("button",{type:"button",onClick:()=>{u(Ee),f(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:xe,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},Ee))})]})]})}),e.jsxs(ke,{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:[ae," will get back to you personally."]})]}),e.jsx(Pe,{className:"p-6 sm:p-8",children:O?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(qn,{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:[ae," just got your request and will reach out shortly."]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"tour",label:"Private tour"},{id:"info",label:"More info"},{id:"offer",label:"Make an offer"}].map(xe=>e.jsx("button",{type:"button",onClick:()=>D(xe.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${E===xe.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:xe.label},xe.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(Ne,{id:"pl-name",value:x,onChange:xe=>y(xe.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pl-email",children:"Email *"}),e.jsx(Ne,{id:"pl-email",type:"email",value:_,onChange:xe=>b(xe.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(Ne,{id:"pl-phone",value:j,onChange:xe=>N(xe.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(pr,{id:"pl-msg",value:C,onChange:xe=>A(xe.target.value),placeholder:`I'd love to see ${Z.address}…`,rows:4,maxLength:2e3})]}),e.jsx(q,{onClick:K,disabled:R,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:R?"Sending…":"Send to "+ae.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(ke,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Pe,{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:[Q!=null&&Q.avatar_url?e.jsx("img",{src:Q.avatar_url,alt:ae,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:ae.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:ae}),(Q==null?void 0:Q.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:Q.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:[ue&&e.jsx(q,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${ue}?subject=${me}&body=${de}`,children:[e.jsx(Ks,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(Q==null?void 0:Q.phone)&&e.jsx(q,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${Q.phone}`,children:[e.jsx(Mn,{className:"h-4 w-4 mr-1.5"}),Q.phone]})}),fe&&e.jsx(q,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:fe,target:"_blank",rel:"noreferrer",children:[e.jsx(Xy,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),m&&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:()=>f(!1),"aria-label":"Close",children:e.jsx($r,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(xe=>(xe-1+W.length)%W.length),"aria-label":"Previous",children:e.jsx(jl,{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(xe=>(xe+1)%W.length),"aria-label":"Next",children:e.jsx(Ia,{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 HXt(){var i;const{slug:s}=xo(),{data:t,isLoading:r,error:n}=Wnt(s);if(k.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),k.useEffect(()=>{t!=null&&t.id&&ll(t.id,"card_view")},[t==null?void 0:t.id]),r)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(dr,{className:"h-28 w-28 rounded-full"}),e.jsx(dr,{className:"h-6 w-48"}),e.jsx(dr,{className:"h-4 w-36"})]}),e.jsx(dr,{className:"h-12 w-full"}),e.jsx(dr,{className:"h-12 w-full"})]})});if(n||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(Yo,{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(rTe,{card:t})]})}const GXt="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",WXt="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",KXt="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",YXt="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",ZXt="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",XXt="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",Zue={"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:XXt},"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:GXt},"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:WXt},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:KXt},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:YXt},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:ZXt}},QXt=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function Cct(s){return s&&s in Zue?Zue[s]:Zue["minimal-mono"]}function JXt(s,t){const r=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":r,"--c-accent-text":s.accentText,"--c-heading-font":s.headingFont,"--c-body-font":s.bodyFont}}function Tct({slugOverride:s}={}){var Xs;const{slug:t}=xo(),r=s||t,[n]=ic(),a=n.get("t"),[i,l]=k.useState(!0),[o,c]=k.useState(null),[d,u]=k.useState(null),m=k.useRef(null),f=k.useRef(null),[x,y]=k.useState(null),[_,b]=k.useState(null),[j,N]=k.useState(!1),[C,A]=k.useState(!1),[E,D]=k.useState(0),[R,F]=k.useState(!1),[O,B]=k.useState(""),[K,Z]=k.useState(""),[Q,W]=k.useState(""),[te,ne]=k.useState(""),[ae,ue]=k.useState(""),[me,de]=k.useState(""),[fe,je]=k.useState(""),[xe,Ee]=k.useState(""),[Me,Oe]=k.useState(""),[Ie,ze]=k.useState(""),[Ve,Le]=k.useState(""),[$e,ve]=k.useState(""),[Qe,we]=k.useState(""),[nt,Se]=k.useState([]),[Ge,We]=k.useState([]),[Ce,qe]=k.useState(""),[et,Ze]=k.useState(""),[rt,ct]=k.useState(""),[vt,kt]=k.useState([]);k.useEffect(()=>{St()},[r,a]);const St=async()=>{if(!r)return;l(!0);const{data:js,error:$s}=await U.from("contact_intake_pages").select("*").eq("slug",r).eq("is_active",!0).maybeSingle();if($s||!js){F(!0),l(!1);return}u(js),f.current=js;const{data:Js}=await U.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",js.user_id).single();if(Js){let or;if(Js.brokerage_id){const{data:Gr}=await U.from("brokerages").select("name").eq("id",Js.brokerage_id).single();or=(Gr==null?void 0:Gr.name)||void 0}let Er=Js.avatar_url||null;if(!Er){const{data:Gr}=U.storage.from("avatars").getPublicUrl(`${js.user_id}/avatar.jpg`);Gr!=null&&Gr.publicUrl&&(Er=`${Gr.publicUrl}?t=${Date.now()}`)}const Sr={...Js,avatar_url:Er,brokerage_name:or};c(Sr),m.current=Sr}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",js.id);const{data:or,error:Er}=await U.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:js.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:or,resolveErr:Er}),!Er&&(or!=null&&or.contact_id)){b(or.contact_id);const Sr=or.contact;Sr&&(y(Sr),B(Sr.first_name||""),Z(Sr.last_name||""),W(Sr.email||""),ne(Sr.phone||""),ue(Sr.address||""),de(Sr.city||""),je(Sr.state||""),Ee(Sr.zip||""),Oe(Sr.birthday||""),ze(Sr.home_anniversary||""))}}catch(or){console.error("Failed to resolve token:",or)}l(!1)},Yt=async()=>{var js,$s;if(!O.trim()){he.error("Please enter your first name");return}if(!r){he.error("Invalid page. Please refresh.");return}A(!0);try{let Js=(js=f.current)==null?void 0:js.id,or=($s=f.current)==null?void 0:$s.user_id;if(!Js||!or){const{data:Gr}=await U.from("contact_intake_pages").select("id, user_id").eq("slug",r).eq("is_active",!0).maybeSingle();if(!Gr){he.error("This page is no longer active. Please contact the agent directly."),A(!1);return}Js=Gr.id,or=Gr.user_id}const Er={intake_page_id:Js,agent_user_id:or,existing_contact_id:_,first_name:O.trim(),last_name:K.trim()||null,email:Q.trim()||null,phone:te.trim()||null,address:ae.trim()||null,city:me.trim()||null,state:fe.trim()||null,zip:xe.trim()||null,birthday:Me||null,home_anniversary:Ie||null,real_estate_interest:Ve||null,message:$e.trim()||null,life_events:{spouse_name:Qe.trim()||null,kids:nt.filter(Gr=>Gr.name.trim()),pets:Ge.filter(Gr=>Gr.name.trim()),favorite_spots:Ce.trim()||null,dream_neighborhood:et.trim()||null,wedding_anniversary:rt||null},referrals:vt.filter(Gr=>Gr.name.trim()&&Gr.contact.trim())},{error:Sr}=await U.from("contact_intake_submissions").insert(Er);if(console.log("[ConnectPage] Insert result:",{error:Sr}),Sr)throw Sr;a&&await U.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Gr=[O.trim(),K.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:or,contactName:Gr,contactEmail:Q.trim()||null,contactPhone:te.trim()||null,slug:r})})}catch(Gr){console.warn("Connect page notification failed (non-blocking):",Gr)}N(!0)}catch(Js){console.error(Js),he.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(ls,{className:"h-8 w-8 animate-spin text-slate-400"})});if(R)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(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(Yo,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Zr.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(Zr.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(qn,{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(yi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const es=!!a&&!!x,zs=(d==null?void 0:d.show_little_things)??!0,sr=[{title:es?"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:O,onChange:js=>B(js.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:K,onChange:js=>Z(js.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:Q,onChange:js=>W(js.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:te,onChange:js=>ne(js.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:ae,onChange:js=>ue(js.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:me,onChange:js=>de(js.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:fe,onChange:js=>je(js.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),e.jsx("input",{type:"text",value:xe,onChange:js=>Ee(js.target.value),placeholder:"78701",className:"connect-input"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),e.jsx("input",{type:"date",value:Me,onChange:js=>Oe(js.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:Ie,onChange:js=>ze(js.target.value),className:"connect-input"})]})]})]})},...zs?[{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:Qe,onChange:js=>we(js.target.value),placeholder:"Alex",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),e.jsx("input",{type:"date",value:rt,onChange:js=>ct(js.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:()=>Se(js=>[...js,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(Ys,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[nt.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),nt.map((js,$s)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:js.name,onChange:Js=>Se(or=>or.map((Er,Sr)=>Sr===$s?{...Er,name:Js.target.value}:Er)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:js.age,onChange:Js=>Se(or=>or.map((Er,Sr)=>Sr===$s?{...Er,age:Js.target.value}:Er)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Se(Js=>Js.filter((or,Er)=>Er!==$s)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx($r,{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:()=>We(js=>[...js,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(Ys,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Ge.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Ge.map((js,$s)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:js.name,onChange:Js=>We(or=>or.map((Er,Sr)=>Sr===$s?{...Er,name:Js.target.value}:Er)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:js.kind,onChange:Js=>We(or=>or.map((Er,Sr)=>Sr===$s?{...Er,kind:Js.target.value}:Er)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>We(Js=>Js.filter((or,Er)=>Er!==$s)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx($r,{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:Ce,onChange:js=>qe(js.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:et,onChange:js=>Ze(js.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."})]}),vt.length<3&&e.jsxs("button",{type:"button",onClick:()=>kt(js=>[...js,{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(Ys,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:vt.map((js,$s)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:js.name,onChange:Js=>kt(or=>or.map((Er,Sr)=>Sr===$s?{...Er,name:Js.target.value}:Er)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:js.contact,onChange:Js=>kt(or=>or.map((Er,Sr)=>Sr===$s?{...Er,contact:Js.target.value}:Er)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>kt(Js=>Js.filter((or,Er)=>Er!==$s)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx($r,{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(js=>e.jsxs("button",{type:"button",onClick:()=>Le(Ve===js.value?"":js.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Ve===js.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:js.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:js.desc})]},js.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:$e,onChange:js=>ve(js.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],ms=sr.length,gt=Cct(d==null?void 0:d.theme),Ut=JXt(gt,(d==null?void 0:d.accent_color)||null),ht=(d==null?void 0:d.cover_image_url)||gt.defaultCover,Jt=(d==null?void 0:d.headline)||"Let's stay connected",Ms=(d==null?void 0:d.subheadline)||(o!=null&&o.brokerage_name?`${o==null?void 0:o.name} · ${o.brokerage_name}`:(o==null?void 0:o.name)||""),ts=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:Ut,children:[e.jsxs(Yo,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${Jt} — ${(o==null?void 0:o.name)||"your agent"}`}),ht&&e.jsx("meta",{property:"og:image",content:ht}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Jt}),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(Zr.img,{src:ht,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(Zr.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:gt.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Jt}),Ms&&e.jsx(Zr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:Ms})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(Zr.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:gt.accent,color:gt.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Xs=o==null?void 0:o.name)==null?void 0:Xs.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(Mn,{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(Ks,{className:"h-4 w-4"})})]})]}),e.jsx(Zr.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(d==null?void 0:d.welcome_message)||"I'd love to stay in touch — just a few quick details."}),e.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:ms}).map((js,$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(Zr.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:ts?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(tEe,{mode:"wait",children:e.jsxs(Zr.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(Ir,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:sr[E].title})]}),sr[E].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:sr[E].subtitle})]}),sr[E].fields]},E)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[E>0?e.jsx("button",{type:"button",onClick:()=>D(js=>js-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&&!O.trim()){he.error("Please enter your first name");return}D(js=>js+1)},className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>Yt(),disabled:C,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:C?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),E>0&&ED(js=>js+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(yi,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const M8=()=>({trackEngagement:k.useCallback(async(t,r,n,a="view")=>{try{const{data:{user:i}}=await U.auth.getUser();if(!i)return;await U.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:r,resource_title:n,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function GR({banners:s,autoPlayInterval:t=5e3,className:r}){const[n,a]=k.useState(0),[i,l]=k.useState(!1),{trackEngagement:o}=M8(),c=k.useCallback(x=>{o("newsletter",x.id,x.title,"click_link")},[o]),d=k.useCallback(()=>{a(x=>(x+1)%s.length)},[s.length]),u=k.useCallback(()=>{a(x=>(x-1+s.length)%s.length)},[s.length]),m=k.useCallback(x=>{a(x)},[]);if(k.useEffect(()=>{if(s.length<=1||i)return;const x=setInterval(d,t);return()=>clearInterval(x)},[s.length,i,t,d]),!s||s.length===0)return null;const f=s[n];return e.jsxs("div",{className:zt("relative w-full overflow-hidden rounded-xl",r),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[e.jsx("img",{src:f.image_url,alt:f.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"ghost",size:"icon",className:zt("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(jl,{className:"h-6 w-6"})}),e.jsx(q,{variant:"ghost",size:"icon",className:zt("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(Ia,{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((x,y)=>e.jsx("button",{onClick:()=>m(y),className:zt("w-2 h-2 rounded-full transition-all duration-300",y===n?"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:f.title}),f.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:f.description})]}),f.link_url&&e.jsx("a",{href:f.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(f),children:e.jsx(q,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:f.link_text||"Learn More"})})]})]})}function eQt(s){return"EST"}function D9(s){const r=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),n=eQt();return`${r} ${n}`}function _P(s){const t=new Date,r=new Date(s),n=vI(r,-15),a=vI(r,30);return t>a?"ended":d1(t,{start:r,end:a})?"live":d1(t,{start:n,end:r})?"starting_soon":"upcoming"}function yEe(s){const t=_P(s);return t==="starting_soon"||t==="live"}const kze=yEe,tQt=({events:s,registrations:t,onNavigateToEvents:r})=>{const[n,a]=k.useState(new Date);k.useEffect(()=>{const x=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(x)},[]);const i=s.filter(x=>yEe(x.event_date));if(i.length===0)return null;const l=i[0],o=_P(l.event_date),c=t.find(x=>x.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,m=o==="live",f=m?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${f.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${f.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 ${f.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${f.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${f.text} font-bold text-sm uppercase tracking-wider`,children:m?e.jsxs(e.Fragment,{children:[e.jsx(h2,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(jn,{className:"h-4 w-4"}),"Starting Soon"]})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg text-foreground line-clamp-1",children:l.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m?`Started at ${D9(new Date(l.event_date))}`:`Starts at ${D9(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs(q,{onClick:()=>window.open(d,"_blank"),className:`${f.button} text-white gap-2`,children:[e.jsx(un,{className:"h-4 w-4"}),m?"Join Now":"Join When Live"]}):e.jsxs(q,{variant:"outline",onClick:r,className:`${f.outlineButton} gap-2`,children:[e.jsx(Dr,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function Cm(){const{user:s}=Cs(),{data:t,isLoading:r}=pt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:m,error:f}=await U.from("gmail_integrations").select("*").maybeSingle();if(f)throw f;return m}}),{data:n,isLoading:a}=pt({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:m}=await U.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return m}}),i=!!(t!=null&&t.is_active),l=(t==null?void 0:t.gmail_email)||null,o=!!(n!=null&&n.email),c=(n==null?void 0:n.email)||null;return{isGmailConnected:i,gmailEmail:l,hasVerifiedSes:o,sesEmail:c,canSendEmail:i||o,sendMethod:i?"gmail":o?"mass_email":"none",isLoading:r||a}}function sQt(){const{user:s}=Cs(),{isGmailConnected:t,hasVerifiedSes:r,isLoading:n}=Cm(),[a,i]=k.useState(!1),[l,o]=k.useState(!1);k.useEffect(()=>{s!=null&&s.id&&U.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}=pt({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[j,N,C,A,E]=await Promise.all([U.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),U.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),U.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),U.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),U.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle()]),D=j.data,R=!!(D!=null&&D.avatar_url&&(D!=null&&D.phone)&&(D!=null&&D.bio)),F=N.count||0,O=(C.count||0)>0,B=A.count||0;return{profile:D,profileComplete:R,contactsCount:F,contactsComplete:F>=5,eventsRegistered:O,communityComplete:B>0,nextOnboardingEvent:E.data||null}}}),u=t||r,m=[{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)}],f=m.filter(j=>j.complete).length,x=m.length;return{steps:m,completedCount:f,totalCount:x,allComplete:f===x,dismissed:a,dismiss:async()=>{s!=null&&s.id&&(i(!0),await U.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(i(!1),await U.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:c,isGmailConnected:t,hasVerifiedSes:r,loading:d||n||!l}}const rQt={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:qi,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:Ks,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:Dr,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:vn,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:Ui,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"}};function nQt(){var _,b;const s=qr(),{user:t}=Cs(),{steps:r,completedCount:n,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=sQt(),[u,m]=k.useState(!0);if(d||l||i)return null;const f=(((_=c==null?void 0:c.profile)==null?void 0:_.name)||((b=t==null?void 0:t.user_metadata)==null?void 0:b.name)||"there").split(" ")[0],x=n/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 N=c==null?void 0:c.nextOnboardingEvent;if(!N){s("/events");return}if(!(t!=null&&t.id))return;const{error:C}=await U.from("event_registrations").insert({user_id:t.id,event_id:N.id});C&&!String(C.message).toLowerCase().includes("duplicate")?(he.error("Could not register — opening events page."),s("/events")):he.success(`You're registered for ${N.title}!`);break}case"community":s("/community");break}};return e.jsxs(ke,{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($r,{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(Ir,{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, ",f,"! 👋"]}),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:[n," of ",a," complete"]}),e.jsxs("span",{children:[a-n," steps left"]})]}),e.jsx(ki,{value:x,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(q,{onClick:()=>m(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(ci,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>m(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(pg,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(Co,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Pe,{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:r.map(j=>{const N=rQt[j.id],C=N.icon;return e.jsx("div",{className:zt("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:zt("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":N.accent),children:j.complete?e.jsx(qn,{className:"h-5 w-5"}):e.jsx(C,{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:zt("font-semibold text-sm",j.complete&&"text-muted-foreground line-through"),children:N.title})}),e.jsx("p",{className:zt("text-xs text-muted-foreground mt-1 leading-relaxed",j.complete&&"line-through"),children:N.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(q,{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:[N.cta," ",e.jsx(ci,{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 H0=()=>pt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await U.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),Lp=s=>{const t=xa(),r=1e3,n=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+r-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=U.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");return await n(a)},enabled:!!t})},aQt=s=>pt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:r}=await U.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(r)throw r;return t},enabled:!!s}),Ect=()=>{const s=xa();return pt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:r}=await U.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(r)throw r;const n={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{n[l.relationship_type_id]=(n[l.relationship_type_id]||0)+1})}),n},enabled:!!s})},Dge=()=>{const s=is(),t=xa();return Mt({mutationFn:async r=>{const{tagIds:n,...a}=r,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,spouse_birthday:a.spouse_birthday||null,owner_user_id:t},{data:l,error:o}=await U.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(n&&n.length>0){const{error:c}=await U.from("innercircle_contact_tags").insert(n.map(d=>({contact_id:l.id,relationship_type_id:d})));if(c)throw c}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Dn({title:"Contact created successfully"})},onError:r=>{Dn({title:"Error creating contact",description:r.message,variant:"destructive"})}})},vEe=()=>{const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{tagIds:n,tags:a,...i}=r,l={...i,birthday:i.birthday||null,home_anniversary:i.home_anniversary||null,spouse_birthday:i.spouse_birthday||null},{data:o,error:c}=await U.from("innercircle_contacts").update(l).eq("id",t).select().single();if(c)throw c;if(n!==void 0&&(await U.from("innercircle_contact_tags").delete().eq("contact_id",t),n.length>0)){const{error:d}=await U.from("innercircle_contact_tags").insert(n.map(u=>({contact_id:t,relationship_type_id:u})));if(d)throw d}return o},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Dn({title:"Contact updated successfully"})},onError:t=>{Dn({title:"Error updating contact",description:t.message,variant:"destructive"})}})},Act=()=>{const s=is();return Mt({mutationFn:async({contactId:t,spouseContactId:r})=>{if(r){const{error:n}=await U.from("innercircle_contacts").update({spouse_contact_id:r}).eq("id",t);if(n)throw n;const{error:a}=await U.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",r);if(a)throw a}else{const{data:n}=await U.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=n==null?void 0:n.spouse_contact_id,{error:i}=await U.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await U.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),Dn({title:"Spouse link updated"})},onError:t=>{Dn({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},bEe=()=>{const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("innercircle_contacts").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Dn({title:"Contact deleted successfully"})},onError:t=>{Dn({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},TB=()=>pt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await U.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),iQt=s=>pt({queryKey:["action-scripts",s],queryFn:async()=>{let t=U.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await t;if(n)throw n;return r}}),oQt=()=>pt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await U.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),lQt=()=>{const s=is(),t=xa();return Mt({mutationFn:async({name:r,description:n})=>{const{data:a,error:i}=await U.from("touchpoint_plans").insert({name:r,description:n,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dn({title:"Plan created successfully"})},onError:r=>{Dn({title:"Error creating plan",description:r.message,variant:"destructive"})}})},cQt=()=>{const s=is(),t=xa();return Mt({mutationFn:async({sourcePlanId:r,newName:n})=>{const{data:a,error:i}=await U.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",r).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await U.from("touchpoint_plans").insert({name:n,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(u=>({plan_id:l.id,month_number:u.month_number,action_type_id:u.action_type_id,default_script_id:u.default_script_id,notes:u.notes})),{error:d}=await U.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dn({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:r=>{Dn({title:"Error duplicating plan",description:r.message,variant:"destructive"})}})},dQt=()=>{const s=is();return Mt({mutationFn:async({id:t,name:r,description:n})=>{const{data:a,error:i}=await U.from("touchpoint_plans").update({name:r,description:n}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dn({title:"Plan updated successfully"})}})},uQt=()=>{const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("touchpoint_plans").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dn({title:"Plan deleted successfully"})}})},hQt=()=>{const s=is();return Mt({mutationFn:async({planId:t,items:r})=>{if(await U.from("touchpoint_plan_items").delete().eq("plan_id",t),r.length>0){const{error:n}=await U.from("touchpoint_plan_items").insert(r.map(a=>({plan_id:t,month_number:a.month_number,action_type_id:a.action_type_id,default_script_id:a.default_script_id||null,notes:a.notes})));if(n)throw n}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Dn({title:"Plan schedule updated"})}})},mQt=()=>{const s=is();return Mt({mutationFn:async({actionTypeId:t,title:r,scriptBody:n,emailSubject:a,tone:i})=>{const{data:{user:l}}=await U.auth.getUser(),{data:o,error:c}=await U.from("action_scripts").insert({action_type_id:t,title:r,script_body:n,email_subject:a||null,tone:i||null,active:!0,user_id:l==null?void 0:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["action-scripts"]}),Dn({title:"Script created successfully"})},onError:t=>{Dn({title:"Error creating script",description:t.message,variant:"destructive"})}})},fQt=()=>{const s=xa();return pt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:r}=await U.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return t},enabled:!!s})},pQt=()=>{const s=is(),t=xa();return Mt({mutationFn:async({planId:r,relationshipTypeId:n,active:a})=>{const{data:i}=await U.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(i){const{error:l}=await U.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await U.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:r,relationship_type_id:n,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),Dn({title:"Plan enrollment updated"})}})},EB=(s=7)=>{const t=xa();return pt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-s);const{data:n,error:a}=await U.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",r.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return n},enabled:!!t})},Mct=()=>{const s=xa();return pt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(r)throw r;const n={};return t==null||t.forEach(a=>{n[a.contact_id]||(n[a.contact_id]=a.completed_at)}),n},enabled:!!s})},xQt=(s=90)=>{const{data:t}=Lp(),{data:r}=Mct();if(!t||!r)return{contacts:[],count:0};const n=new Date;n.setDate(n.getDate()-s);const a=t.filter(i=>{const l=r[i.id];return l?new Date(l){const s=is(),t=xa();return Mt({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await U.from("contact_touch_logs").insert({owner_user_id:t,contact_id:r,action_type_id:n,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(r,n)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Dn({title:"Action completed!"});try{const[l,o]=await Promise.all([U.from("innercircle_contacts").select("email").eq("id",n.contactId).single(),U.from("action_types").select("name").eq("id",n.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";/pop[\s-]?by/i.test(d)&&U.from("popby_logs").insert({owner_user_id:t,contact_id:n.contactId,notes:n.notes??null,completed_at:n.completedAt||r.completed_at}).then(()=>{s.invalidateQueries({queryKey:["popby-logs"]})}),c&&U.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:n.notes||null,touch_date:n.completedAt||r.completed_at}}).catch(()=>{})}catch{}}})},Ict="agentos_weekly_touch_goal",Sze=20,Ime=()=>{if(typeof window>"u")return Sze;const s=localStorage.getItem(Ict);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return Sze},Pct=s=>{localStorage.setItem(Ict,s.toString())},_Ee=()=>{const{data:s}=EB(7),t=new Date;t.setHours(0,0,0,0);const r=new Date(t);r.setDate(t.getDate()-t.getDay());const n=(s==null?void 0:s.filter(l=>new Date(l.completed_at)>=r).length)||0;let a=0;if(s&&s.length>0){const l=new Set(s.map(c=>new Date(c.completed_at).toDateString()));let o=new Date(t);for(;l.has(o.toDateString());)a++,o.setDate(o.getDate()-1)}const i=Ime();return{actionsThisWeek:n,weeklyGoal:i,streak:a,progress:Math.min(n/i*100,100)}},gQt=()=>{const s=xa();return pt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(r)throw r;return t},enabled:!!s})},yQt=()=>{const s=is();return xa(),Mt({mutationFn:async()=>{var c;const{data:t}=await U.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:r}=await U.auth.getUser(),n=(c=r==null?void 0:r.user)==null?void 0:c.id;if(!n)return;const{data:a}=await U.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",n);if(!a)return;const{data:i}=await U.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const m=t.find(f=>f.relationship_type_id===u.relationship_type_id);m&&!l.has(`${d.id}-${m.plan_id}`)&&o.push({contact_id:d.id,plan_id:m.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await U.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&Dn({title:`${t} contact(s) enrolled in plans`})}})},Lct=()=>{const s=xa(),{data:t}=gQt(),{data:r}=EB(30);return pt({queryKey:["today-actions",s,t==null?void 0:t.length,r==null?void 0:r.length],queryFn:async()=>{var y;if(!t||t.length===0)return[];const{data:n}=await U.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((n==null?void 0:n.map(_=>_.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((r==null?void 0:r.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 b=new Date(_.cycle_start_date),N=Math.floor((i.getTime()-b.getTime())/(30.44*24*60*60*1e3))%12+1,C=_.plan.items.find(A=>A.month_number===N);if(C&&C.action_type){const A=`${_.contact_id}-${C.action_type_id}`;if(!c.has(A)){const{data:E}=await U.from("relationship_types").select("name").eq("id",_.relationship_type_id).single();l.push({contact:_.contact,actionType:C.action_type,script:C.default_script||void 0,planName:_.plan.name,relationshipTypeName:(E==null?void 0:E.name)||"",monthNumber:N})}}}const d=5,u=i.getDate(),m=l.sort((_,b)=>_.contact.first_name.localeCompare(b.contact.first_name)),f=(u-1)%Math.max(1,m.length);return[...m.slice(f),...m.slice(0,f)].slice(0,d)},enabled:!!s&&!!t})};function vQt(){const s=qr(),{data:t,isLoading:r}=Lct(),{data:n}=Lp(),a=_Ee(),[i,l]=k.useState(Ime()),[o,c]=k.useState(""),[d,u]=k.useState(!1);k.useEffect(()=>{l(Ime())},[]);const m=()=>{const D=parseInt(o,10);if(isNaN(D)||D<1){Dn({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(D),Pct(D),u(!1),Dn({title:"Goal updated",description:`Weekly touch goal set to ${D}`})},f=()=>{c(i.toString()),u(!0)},x=Ax(new Date),y=Dc(x,7),_=D=>{if(!D)return null;const R=D.split(/[-/T]/);if(R.length<3)return null;const F=parseInt(R[1],10)-1,O=parseInt(R[2],10);return isNaN(F)||isNaN(O)?null:new Date(x.getFullYear(),F,O)},b=(n==null?void 0:n.map(D=>{const R=_(D.birthday),F=_(D.home_anniversary),O=[];return R&&R>=x&&R<=y&&O.push({contact:D,type:"birthday",date:R,isToday:pc(R,x)}),F&&F>=x&&F<=y&&O.push({contact:D,type:"anniversary",date:F,isToday:pc(F,x)}),O}).flat().sort((D,R)=>D.date.getTime()-R.date.getTime()).slice(0,3))||[],j=(n==null?void 0:n.filter(D=>{const R=_(D.birthday),F=_(D.home_anniversary);return R&&pc(R,x)||F&&pc(F,x)}).length)||0,N=(t==null?void 0:t.length)||0,C=j+N,A=(a==null?void 0:a.actionsThisWeek)||0,E=(a==null?void 0:a.streak)||0;return r?e.jsx(ke,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-primary/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-primary/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-primary/10 rounded w-1/2"})]})]})})}):e.jsxs(ke,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[e.jsxs(Pt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:E>0&&e.jsxs(Xe,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(ld,{className:"h-3 w-3"}),E," day streak"]})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[C>0?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary font-medium",children:[C," tasks"]})," for today"]}):"No tasks for today",A>0&&e.jsxs("span",{className:"ml-2",children:["• ",e.jsx("span",{className:"text-emerald-600 font-medium",children:A})," touches this week"]})]})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(q,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(xl,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(q,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control")},children:[e.jsx(Mn,{className:"h-3.5 w-3.5"}),"Log Touch"]}),e.jsxs(q,{size:"sm",variant:"outline",className:"gap-1.5 border-emerald-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",onClick:D=>{D.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(q,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(Ma,{className:"h-3.5 w-3.5"}),"Pop-by Map"]}),e.jsxs(q,{size:"sm",variant:"outline",className:"gap-1.5 border-purple-200 text-purple-700 hover:bg-purple-50 hover:text-purple-800",onClick:D=>{D.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(i2,{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(Hu,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(vs,{open:d,onOpenChange:u,children:[e.jsx(Yi,{asChild:!0,children:e.jsx("button",{onClick:f,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(Bo,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(ys,{className:"sm:max-w-[360px]",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Set Weekly Goal"}),e.jsx(an,{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(ce,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),e.jsx(Ne,{id:"weekly-goal",type:"number",min:"1",value:o,onChange:D=>c(D.target.value),placeholder:"20",onKeyDown:D=>{D.key==="Enter"&&m()}})]}),e.jsx(q,{onClick:m,className:"w-full",children:"Save Goal"})]})]})]})]}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-primary",children:A}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",i," touches"]})]})]}),e.jsx(ki,{value:Math.min(A/i*100,100),className:"h-2 bg-muted [&>div]:bg-primary"}),A>=i&&e.jsxs("p",{className:"text-xs text-emerald-600 mt-1.5 flex items-center gap-1",children:[e.jsx("span",{children:"🎉"})," Goal achieved! Keep the momentum going."]}),A0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:[i-A," more to hit your weekly goal"]})]}),b.length>0&&e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(_m,{className:"h-4 w-4 text-pink-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Upcoming Milestones"})]}),e.jsx("div",{className:"space-y-2",children:b.map((D,R)=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${D.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:F=>{F.stopPropagation(),s(`/mission-control/contacts/${D.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[D.type==="birthday"?e.jsx(_m,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(Pn,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[D.contact.first_name," ",D.contact.last_name]}),D.isToday&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-pink-500/20 text-pink-600",children:"Today!"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:D.isToday?D.type==="birthday"?"🎂":"🏠":As(D.date,"EEE, MMM d")}),e.jsx(Ia,{className:"h-3 w-3"})]})]},`${D.contact.id}-${D.type}-${R}`))})]}),e.jsxs(q,{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(ci,{className:"h-4 w-4"})]})]})]})}function bQt(s){return pt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(r)throw r;return t},enabled:!!s})}function _Qt(s,t){return pt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let r=U.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(r=r.eq("category_id",t));const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!s})}function wQt(s,t=4){return pt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:r,error:n}=await U.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(n)throw n;return r},enabled:!!s})}function jQt(s){const t=is();return Mt({mutationFn:async r=>{const{data:n,error:a}=await U.from("brokerage_content").insert(r).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function NQt(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("brokerage_content").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function kQt(s){const t=is();return Mt({mutationFn:async r=>{const{data:n,error:a}=await U.from("brokerage_content_categories").insert({...r,brokerage_id:s}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function SQt(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("brokerage_content_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function CQt(s){const t=is();return Mt({mutationFn:async()=>{const r=[{name:"Events",icon:"📅",sort_order:0,is_default:!0,brokerage_id:s},{name:"Videos",icon:"🎥",sort_order:1,is_default:!0,brokerage_id:s},{name:"Documents",icon:"📄",sort_order:2,is_default:!0,brokerage_id:s},{name:"Resources",icon:"🔗",sort_order:3,is_default:!0,brokerage_id:s},{name:"Graphics",icon:"🎨",sort_order:4,is_default:!0,brokerage_id:s}],{error:n}=await U.from("brokerage_content_categories").upsert(r,{onConflict:"brokerage_id,name"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const TQt={video:Al,pdf:En,link:Ul,event:vn,graphic:dl},EQt={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 AQt(s){if(!s)return null;try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}function MQt(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 IQt({item:s}){const t=qr(),r=TQt[s.content_type]||Ul,n=EQt[s.content_type]||"",[a,i]=k.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?AQt(s.url):null);k.useEffect(()=>{l||!s.url||s.content_type!=="video"||!MQt(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(c=>c.ok?c.json():null).then(c=>{c!=null&&c.thumbnail_url&&i(c.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,l]);const o=l||a;return e.jsxs(ke,{className:"group cursor-pointer overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",onClick:()=>t(`/brokerage-content/${s.id}`),children:[o?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:o,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/20 flex items-center justify-center",children:e.jsx(r,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(Pe,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(Xe,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${n}`,children:[e.jsx(r,{className:"h-3 w-3 mr-0.5"}),s.content_type]})}),e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:s.title}),s.content_type==="event"&&s.event_date&&e.jsx("p",{className:"text-xs text-primary mt-1 font-medium",children:As(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function PQt(){const{brokerageId:s}=Cs(),t=qr(),{data:r=[],isLoading:n}=wQt(s,4);return!s||n||r.length===0?null:e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ci,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:r.map(a=>e.jsx(IQt,{item:a},a.id))})]})}const Dct=()=>pt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await U.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),Rct=s=>{const{user:t,brokerageId:r}=Cs();return pt({queryKey:["listings",s,r],queryFn:async()=>{let n=U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0);s!=null&&s.status&&(n=n.eq("status",s.status)),s!=null&&s.propertyType&&(n=n.eq("property_type",s.propertyType)),s!=null&&s.city&&(n=n.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(n=n.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(n=n.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(n=n.eq("open_to_referrals",!0));const{data:a,error:i}=await n;if(i)throw i;let l=a||[];if(r){const{data:o}=await U.from("profiles").select("id").eq("brokerage_id",r);if(o&&o.length>0){const c=o.map(m=>m.id);let d=U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const m=new Set(l.map(x=>x.id)),f=u.filter(x=>!m.has(x.id));l=[...l,...f]}}}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}})},Oct=()=>{const{user:s}=Cs();return pt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})},wEe=s=>{const{user:t}=Cs();return pt({queryKey:["listing",s],queryFn:async()=>{const{data:r,error:n}=await U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(n)throw n;return t&&await U.from("listing_views").insert({listing_id:s,viewer_id:t.id}),r},enabled:!!s})},LQt=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("listings").insert({...r,agent_id:t.id}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},DQt=()=>{const s=is();return Mt({mutationFn:async({agentId:t,...r})=>{const{data:n,error:a}=await U.from("listings").insert({...r,agent_id:t}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},RQt=()=>{const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("listings").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},Fct=()=>{const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("listings").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},OQt=()=>{const s=is();return Mt({mutationFn:async({listingId:t,photoUrl:r,isPrimary:n=!1})=>{const{data:a,error:i}=await U.from("listing_photos").insert({listing_id:t,photo_url:r,is_primary:n}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},FQt=()=>{const s=is();return Mt({mutationFn:async({photoId:t,listingId:r})=>{const{error:n}=await U.from("listing_photos").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},zQt=()=>{const s=is();return Mt({mutationFn:async({photos:t})=>{var i;const r=t.map(l=>U.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(r)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},BQt=()=>{const s=is();return Mt({mutationFn:async({photoId:t,listingId:r})=>{const{error:n}=await U.from("listing_photos").update({is_primary:!1}).eq("listing_id",r);if(n)throw n;const{error:a}=await U.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},$Qt=()=>{const{user:s}=Cs();return pt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(r)throw r;return t},enabled:!!s})},zct=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n}=await U.from("listing_saves").select("id").eq("listing_id",r).eq("agent_id",t.id).maybeSingle();return n?(await U.from("listing_saves").delete().eq("id",n.id),{saved:!1}):(await U.from("listing_saves").insert({listing_id:r,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},Bct=s=>{const{user:t}=Cs();return pt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:r}=await U.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!r},enabled:!!t&&!!s})},UQt=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n}=await U.from("listing_follows").select("id").eq("listing_id",r).eq("agent_id",t.id).maybeSingle();return n?(await U.from("listing_follows").delete().eq("id",n.id),{following:!1}):(await U.from("listing_follows").insert({listing_id:r,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},qQt=s=>{const{user:t}=Cs();return pt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:r}=await U.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!r},enabled:!!t&&!!s})},VQt=()=>{const{user:s}=Cs();return Mt({mutationFn:async({listingId:t,shareType:r})=>{if(!s)throw new Error("Not authenticated");const{error:n}=await U.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:r});if(n)throw n}})},HQt=()=>{const{user:s}=Cs();return pt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,r]=await Promise.all([U.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),U.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:r.data||[]}},enabled:!!s})},GQt=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async({listingId:r,listingAgentId:n,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await U.from("listing_referrals").insert({listing_id:r,sender_agent_id:t.id,listing_agent_id:n,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},WQt=()=>pt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await U.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const r=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:n}=await U.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;n==null||n.forEach(l=>{var c;const o=a.get(l.agent_id);o?o.count++:a.set(l.agent_id,{name:((c=l.agent)==null?void 0:c.name)||"Unknown",count:1})});const i=Array.from(a.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10);return{topSharers:r,topListers:i}}}),KQt=()=>{const{user:s,brokerageId:t}=Cs();return pt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:r}=await U.from("profiles").select("id").eq("brokerage_id",t);if(!r||r.length===0)return[];const n=r.map(l=>l.id),{data:a,error:i}=await U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",n).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},$ct=({className:s,variant:t="default"})=>e.jsx(Xe,{variant:"outline",className:zt("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"}),YQt={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"},ZQt={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function XQt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function QQt(){const s=qr(),{data:t,isLoading:r}=Dct(),{data:n,isLoading:a}=Rct({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(n==null?void 0:n.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=r||a;return!d&&!t?null:d?e.jsx(ke,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-emerald-500/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-emerald-500/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-emerald-500/10 rounded w-1/2"})]})]})})}):e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Listing Exchange"}),e.jsx($ct,{})]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ci,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Pn,{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(q,{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 f,x;const m=((f=u.photos)==null?void 0:f.find(y=>y.is_primary))||((x=u.photos)==null?void 0:x[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:[m!=null&&m.photo_url?e.jsx("img",{src:m.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(Pn,{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(Xe,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(fa,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(Xe,{className:`text-[10px] px-1.5 py-0.5 ${YQt[u.status]}`,children:ZQt[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:XQt(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 Uct(s=10,t){return pt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:r}=await U.from("user_roles").select("user_id").eq("role","admin"),n=new Set((r==null?void 0:r.map(f=>f.user_id))||[]);let a=null;if(t){const{data:f}=await U.from("profiles").select("id").eq("brokerage_id",t);a=new Set((f==null?void 0:f.map(x=>x.id))||[])}const{data:i,error:l}=await U.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+n.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(f=>!n.has(f.user_id));a&&(o=o.filter(f=>a.has(f.user_id)));const c=o.slice(0,s),d=c.map(f=>f.user_id),{data:u}=await U.from("profiles").select("id, name").in("id",d),m=new Map((u==null?void 0:u.map(f=>[f.id,{name:f.name}]))||[]);return c.map(f=>({user_id:f.user_id,total_points:f.total_points,total_events_attended:f.total_events_attended,current_streak:f.current_streak,profile:m.get(f.user_id)||null}))}})}function qct(s){return pt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(r&&r.code!=="PGRST116")throw r;return t},enabled:!!s})}function Vct(s){return pt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Hct(s,t){return pt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:r}=await U.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!r)return null;const{data:n}=await U.from("user_roles").select("user_id").eq("role","admin"),a=new Set((n==null?void 0:n.map(c=>c.user_id))||[]),{data:i,error:l}=await U.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",r.total_points);if(l)throw l;let o=(i==null?void 0:i.filter(c=>!a.has(c.user_id)))||[];if(t){const{data:c}=await U.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function JQt(){const{user:s,brokerageId:t,isAdmin:r}=Cs();qr();const n=!!t,[a,i]=k.useState("brokerage"),l=()=>{if(r)return null;if(n)return a==="global"?null:t},{data:o,isLoading:c}=Uct(5,l()),{data:d}=qct(s==null?void 0:s.id),{data:u}=Hct(s==null?void 0:s.id,l()),{data:m}=Vct(s==null?void 0:s.id),f=r||n,x=()=>r?"Agent Leaderboard":n?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(wo,{className:"h-4 w-4 text-yellow-500"}),x()]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-2",children:[...Array(f?5:3)].map((_,b)=>e.jsx(dr,{className:"h-10 w-full"},b))})})]});const y=_=>_===0?e.jsx(wo,{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(f){const _=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"pb-2",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(wo,{className:"h-4 w-4 text-yellow-500"}),x()]}),!r&&n&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(q,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(q,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Pe,{children:[!r&&d&&e.jsx("div",{className:"mb-3 p-2 rounded-lg bg-primary/5 border border-primary/10",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Your Rank:"}),e.jsxs("span",{className:"font-bold text-primary",children:["#",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((b,j)=>{var N,C,A;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${b.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":j===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:y(j)}),e.jsx(Wn,{className:"h-6 w-6",children:e.jsx(Kn,{className:"text-xs",children:((C=(N=b.profile)==null?void 0:N.name)==null?void 0:C.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((A=b.profile)==null?void 0:A.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:b.total_points})]},b.user_id)}),_.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(Vn,{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(Di,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Ia,{className:"h-4 w-4"})]})]})]})}return e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(wo,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Pe,{children:d?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:d.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Points"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:d.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events Attended"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ld,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Current Streak"})]}),e.jsxs("span",{className:"font-bold text-orange-500",children:[d.current_streak," 🔥"]})]}),m&&m.length>0&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[e.jsx(Uc,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Badges"})]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[m.slice(0,4).map(_=>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)),m.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",m.length-4," more"]})]})]}),e.jsxs(Vn,{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(Di,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Ia,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(fa,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(Vn,{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(Di,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(Ia,{className:"h-4 w-4"})]})]})})]})}const I8=()=>pt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await U.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),jEe=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{const{data:n}=await U.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",r.trim()),a=(n||[]).find(o=>o.name.toLowerCase()===r.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await U.from("lead_sources").insert({name:r,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),he.success("Lead source added")},onError:r=>{he.error("Failed to add lead source"),console.error(r)}})},eJt=()=>{const s=is();return Mt({mutationFn:async({id:t,name:r})=>{const{error:n}=await U.from("lead_sources").update({name:r}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),he.success("Lead source updated")},onError:t=>{he.error(t.message||"Failed to update lead source")}})},tJt=()=>{const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("lead_sources").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),he.success("Lead source removed")},onError:t=>{he.error(t.message||"Failed to remove lead source")}})},NEe=(s,t)=>{const{user:r,isAdmin:n}=Cs(),a=n&&t?t:r==null?void 0:r.id;return pt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},kEe=s=>{const{user:t,isAdmin:r}=Cs(),n=r&&s?s:t==null?void 0:t.id;return pt({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:a,error:i}=await U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",n).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!n})},Oge=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{const{data:n,error:a}=await U.from("scorecard_transactions").insert({...r,owner_user_id:t.id}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),he.success("Transaction added")},onError:r=>{he.error("Failed to add transaction"),console.error(r)}})},sJt=()=>{const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("scorecard_transactions").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),he.success("Transaction updated")},onError:t=>{he.error("Failed to update transaction"),console.error(t)}})},rJt=()=>{const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("scorecard_transactions").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),he.success("Transaction deleted")},onError:t=>{he.error("Failed to delete transaction"),console.error(t)}})},Gct=(s,t)=>{const{user:r,isAdmin:n}=Cs(),a=n&&t?t:r==null?void 0:r.id;return pt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await U.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},nJt=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{const{data:n,error:a}=await U.from("scorecard_goals").upsert({...r,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return n},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["scorecard-goals",n.year]}),he.success("Goals saved")},onError:r=>{he.error("Failed to save goals"),console.error(r)}})},Fge=()=>{const{user:s}=Cs();return pt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t},enabled:!!(s!=null&&s.id)})},aJt=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{const{data:n,error:a}=await U.from("scorecard_settings").upsert({...r,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),he.success("Settings saved")},onError:r=>{he.error("Failed to save settings"),console.error(r)}})},Wct=(s,t)=>{const{data:r,isLoading:n}=NEe(s,t),{data:a,isLoading:i}=kEe(t),{data:l}=Fge(),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,m=d.filter(E=>E.transaction_type==="seller").length,f=d.reduce((E,D)=>E+Number(D.sale_price),0),x=d.reduce((E,D)=>E+(Number(D.commission_amount)||0),0),y=d.reduce((E,D)=>{const R=Number(D.commission_amount)||0;if(!R)return E;let F=R;return D.brokerage_split_pct&&(F-=R*(D.brokerage_split_pct/100)),D.team_split_pct&&(F-=R*(D.team_split_pct/100)),D.franchise_fee_pct&&(F-=R*(D.franchise_fee_pct/100)),D.referral_fee_pct&&(F-=R*(D.referral_fee_pct/100)),D.transaction_fee&&(F-=D.transaction_fee),E+Math.max(0,F)},0),_={};d.forEach(E=>{var R;const D=((R=E.lead_source)==null?void 0:R.name)||"Unknown";_[D]=(_[D]||0)+1});const b=Object.entries(_).map(([E,D])=>({name:E,count:D})).sort((E,D)=>D.count-E.count),j=b[0]||null,N={};d.forEach(E=>{const D=El(E.close_date).toLocaleString("default",{month:"short"});N[D]=(N[D]||0)+1});const A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(E=>({month:E,count:N[E]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:m,totalVolume:f,averagePrice:d.length>0?f/d.length:0,totalCommission:o?x:0,totalNetToAgent:o?y:0,topLeadSource:j,transactionsByMonth:A,leadSourceBreakdown:b}};return{yearStats:c(r),lifetimeStats:c(a),isLoading:n||i,showCommission:o}},iJt=()=>{const{isAdmin:s}=Cs();return pt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:r}=await U.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(r)throw r;const n=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await U.from("profiles").select("id, name, email").in("id",n);if(i)throw i;return a},enabled:s})},nk={recency:40,touchpoints:30,transactions:20,referrals:10},Cze={warm:70,cooling:40};function oJt(s){return s===null?0:s<=14?nk.recency:s<=30?nk.recency*.85:s<=60?nk.recency*.65:s<=90?nk.recency*.4:s<=180?nk.recency*.2:nk.recency*.05}function lJt(s){const t=Math.min(s/12,1);return Math.round(nk.touchpoints*t)}function cJt(s){return s?nk.transactions:0}function dJt(){return 0}function uJt(s){return s>=Cze.warm?"warm":s>=Cze.cooling?"cooling":"at-risk"}function zge(){const{data:s,isLoading:t}=Lp(),{data:r}=Mct(),{data:n}=EB(365),{data:a}=kEe(),i=k.useMemo(()=>{if(!s)return[];const o=new Date,c=YT(o,12),d={};n==null||n.forEach(m=>{new Date(m.completed_at)>=c&&(d[m.contact_id]=(d[m.contact_id]||0)+1)});const u=new Set((a==null?void 0:a.filter(m=>m.contact_id).map(m=>m.contact_id))||[]);return s.map(m=>{const f=(r==null?void 0:r[m.id])||null,x=f?lv(o,new Date(f)):null,y=d[m.id]||0,_=u.has(m.id),b=oJt(x),j=lJt(y),N=cJt(_),C=dJt(),A=Math.round(b+j+N+C),E={score:A,status:uJt(A),breakdown:{recency:Math.round(b),touchpoints:Math.round(j),transactions:Math.round(N),referrals:Math.round(C)},lastTouchDate:f,daysSinceTouch:x,touchCountLast12Months:y,hasTransaction:_};return{...m,relationshipScore:E}})},[s,r,n,a]),l=k.useMemo(()=>{const o=i.filter(f=>f.relationshipScore.status==="warm").length,c=i.filter(f=>f.relationshipScore.status==="cooling").length,d=i.filter(f=>f.relationshipScore.status==="at-risk").length,u=i.length,m=u>0?Math.round(i.reduce((f,x)=>f+x.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:m}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function Kct(){const s=qr(),{stats:t,contactsWithScores:r,isLoading:n}=zge();if(n)return e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(dr,{className:"h-5 w-40"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx(dr,{className:"h-20 w-full"}),e.jsx(dr,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx(q,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/mission-control/contacts?new=true"),children:"Add Your First Contact"})]})]});const a=Math.round(t.warm/t.total*100),i=Math.round(t.cooling/t.total*100),l=Math.round(t.atRisk/t.total*100),o=r.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Wo,{className:"h-5 w-5 text-emerald-500"}),"Relationship Health"]}),e.jsx("span",{className:"text-2xl font-bold",children:t.averageScore})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Average score across ",t.total," contacts"]})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-emerald-500"}),e.jsx("span",{children:"Warm"})]}),e.jsxs("span",{className:"font-medium",children:[t.warm," (",a,"%)"]})]}),e.jsx(ki,{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(ki,{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(ki,{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(E_,{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(Ia,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(q,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(Ia,{className:"h-4 w-4 ml-1"})]})]})]})}const hJt=()=>{var ne;const{user:s,isAdmin:t}=Cs(),r=qr(),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState([]),[d,u]=k.useState([]),[m,f]=k.useState([]),[x,y]=k.useState([]),[_,b]=k.useState(new Set),[j,N]=k.useState([]),[C,A]=k.useState([]),[E,D]=k.useState([]),[R,F]=k.useState(null),[O,B]=k.useState(!0);k.useEffect(()=>{K()},[s]);const K=async()=>{var ae,ue,me,de,fe;try{const[je,xe,Ee,Me,Oe,Ie,ze,Ve,Le,$e,ve]=await Promise.all([U.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),U.from("app_tiles").select("*").order("name"),U.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),U.from("events").select("*").order("event_date",{ascending:!0}),U.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),U.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),U.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),U.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(ae=ve.data)!=null&&ae.name&&F(ve.data.name);const Qe=((ue=je.data)==null?void 0:ue.map(Ce=>Ce.tag))||[],we=new Set(((me=Ee.data)==null?void 0:me.map(Ce=>Ce.app_id))||[]);b(we);const Se=(((de=xe.data)==null?void 0:de.filter(Ce=>!Ce.required_tags||Ce.required_tags.length===0?!0:Ce.required_tags.some(qe=>Qe.includes(qe))))||[]).sort((Ce,qe)=>Ce.name==="LevelUp Members Portal"?-1:qe.name==="LevelUp Members Portal"?1:0);a(Se.slice(0,6));const Ge=((fe=Me.data)==null?void 0:fe.filter(Ce=>_P(Ce.event_date)!=="ended"))||[];l(Ge.slice(0,4)),N(Oe.data||[]),c(Ie.data||[]),u(ze.data||[]),f(Ve.data||[]),y(Le.data||[]);const We=$e.data||[];A(We.filter(Ce=>Ce.placement==="top")),D(We.filter(Ce=>Ce.placement==="between"))}catch(je){console.error("Error loading dashboard:",je),he.error("Failed to load dashboard data")}finally{B(!1)}},Z=async ae=>{var me;const ue=window.open("about:blank","_blank");try{await U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:ae.app_id,app_name:ae.name,user_agent:navigator.userAgent});const{data:de,error:fe}=await U.functions.invoke("sso-launch",{body:{app_id:ae.app_id}});if(fe)throw fe;de!=null&&de.redirect_url?ue&&!ue.closed?(ue.location.href=de.redirect_url,(me=ue.focus)==null||me.call(ue)):window.location.assign(de.redirect_url):(ue==null||ue.close(),he.error("Launch link unavailable"))}catch(de){ue==null||ue.close(),console.error("Error launching app:",de),he.error("Failed to launch app")}},Q=ae=>j==null?void 0:j.some(ue=>ue.event_id===ae),W=ae=>{const ue=j==null?void 0:j.find(me=>me.event_id===ae);return ue==null?void 0:ue.zoom_join_url};if(O)return e.jsx(ws,{title:"Dashboard",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading your dashboard..."})]})})});const te=ae=>E.filter(ue=>ue.section_after===ae);return e.jsxs(ws,{title:"Dashboard",children:[e.jsx(tQt,{events:i,registrations:j,onNavigateToEvents:()=>r("/events")}),C.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(GR,{banners:C})}),e.jsx(nQt,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(R||((ne=s==null?void 0:s.user_metadata)==null?void 0:ne.name)||"there").split(" ")[0],"!"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Are you ready to LevelUp today?"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 mb-8",children:[e.jsx(vQt,{}),e.jsx(Kct,{}),e.jsx(JQt,{})]}),e.jsx(PQt,{}),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(q,{variant:"ghost",size:"sm",onClick:()=>r("/events"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ci,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(vn,{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(ae=>{const ue=Q(ae.id),me=W(ae.id)||ae.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 ${kze(ae.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>r("/events"),children:[kze(ae.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(h2,{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(ae.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(ae.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:ae.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(ae.event_date))," at ",D9(new Date(ae.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:ue?e.jsxs(q,{size:"sm",variant:"default",className:"gap-1",onClick:de=>{de.stopPropagation(),window.open(me,"_blank")},children:[e.jsx(un,{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(Ia,{className:"h-4 w-4"})]})})]},ae.id)})})]}),te("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(GR,{banners:te("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(q,{variant:"ghost",size:"sm",onClick:()=>r("/academy"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ci,{className:"h-4 w-4"})]})]}),m.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ff,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No academy videos available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:m.map(ae=>e.jsxs("div",{onClick:()=>r(`/academy/${ae.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:[ae.thumbnail_url?e.jsx("img",{src:ae.thumbnail_url,alt:ae.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(Ff,{className:"h-8 w-8 text-muted-foreground/50"})}),ae.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:ae.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:ae.title})})]},ae.id))})]}),te("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(GR,{banners:te("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(q,{variant:"ghost",size:"sm",onClick:()=>r("/toolbox"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ci,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Kf,{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(ae=>e.jsxs("div",{onClick:()=>r(`/toolbox/${ae.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:ae.featured_image_url?e.jsx("img",{src:ae.featured_image_url,alt:ae.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(Kf,{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:ae.name})})]},ae.id))})]}),te("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(GR,{banners:te("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(q,{variant:"ghost",size:"sm",onClick:()=>r("/templates"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ci,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(t2,{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(ae=>e.jsxs("div",{onClick:()=>r("/templates"),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsx("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden",children:ae.preview_image_url?e.jsx("img",{src:ae.preview_image_url,alt:ae.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(t2,{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:ae.name})})]},ae.id))})]}),te("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(GR,{banners:te("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx(QQt,{})}),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(q,{variant:"ghost",size:"sm",onClick:()=>r("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ci,{className:"h-4 w-4"})]})]}),n.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Zy,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No apps available"})]})})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:n.map(ae=>{const ue=_.has(ae.id);return e.jsxs("div",{onClick:()=>Z(ae),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:ae.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:ae.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ae.description})]}),ue&&e.jsx(Zy,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},ae.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(q,{variant:"ghost",size:"sm",onClick:()=>r("/additional-services"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ci,{className:"h-4 w-4"})]})]}),x.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ir,{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:x.map(ae=>e.jsxs("div",{onClick:()=>window.open(ae.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:ae.preview_image_url?e.jsx("img",{src:ae.preview_image_url,alt:ae.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(Ir,{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:ae.name}),ae.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:ae.description})]})]},ae.id))})]})]})};var Yct="AlertDialog",[mJt,Knr]=bu(Yct,[mrt]),O2=mrt(),Zct=s=>{const{__scopeAlertDialog:t,...r}=s,n=O2(t);return e.jsx(Gxe,{...n,...r,modal:!0})};Zct.displayName=Yct;var fJt="AlertDialogTrigger",Xct=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=O2(r);return e.jsx(K5e,{...a,...n,ref:t})});Xct.displayName=fJt;var pJt="AlertDialogPortal",Qct=s=>{const{__scopeAlertDialog:t,...r}=s,n=O2(t);return e.jsx(Wxe,{...n,...r})};Qct.displayName=pJt;var xJt="AlertDialogOverlay",Jct=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=O2(r);return e.jsx(w8,{...a,...n,ref:t})});Jct.displayName=xJt;var wP="AlertDialogContent",[gJt,yJt]=mJt(wP),vJt=AJe("AlertDialogContent"),edt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,children:n,...a}=s,i=O2(r),l=k.useRef(null),o=_i(t,l),c=k.useRef(null);return e.jsx(u8t,{contentName:wP,titleName:tdt,docsSlug:"alert-dialog",children:e.jsx(gJt,{scope:r,cancelRef:c,children:e.jsxs(j8,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:dn(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(vJt,{children:n}),e.jsx(_Jt,{contentRef:l})]})})})});edt.displayName=wP;var tdt="AlertDialogTitle",sdt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=O2(r);return e.jsx(fB,{...a,...n,ref:t})});sdt.displayName=tdt;var rdt="AlertDialogDescription",ndt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=O2(r);return e.jsx(pB,{...a,...n,ref:t})});ndt.displayName=rdt;var bJt="AlertDialogAction",adt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=O2(r);return e.jsx(xB,{...a,...n,ref:t})});adt.displayName=bJt;var idt="AlertDialogCancel",odt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,{cancelRef:a}=yJt(idt,r),i=O2(r),l=_i(t,a);return e.jsx(xB,{...i,...n,ref:l})});odt.displayName=idt;var _Jt=({contentRef:s})=>{const t=`\`${wP}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${wP}\` by passing a \`${rdt}\` 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 \`${wP}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return k.useEffect(()=>{var n;document.getElementById((n=s.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},wJt=Zct,jJt=Xct,NJt=Qct,ldt=Jct,cdt=edt,ddt=adt,udt=odt,hdt=sdt,mdt=ndt;const el=wJt,hh=jJt,kJt=NJt,fdt=k.forwardRef(({className:s,...t},r)=>e.jsx(ldt,{className:zt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...t,ref:r}));fdt.displayName=ldt.displayName;const $o=k.forwardRef(({className:s,...t},r)=>e.jsxs(kJt,{children:[e.jsx(fdt,{}),e.jsx(cdt,{ref:r,className:zt("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})]}));$o.displayName=cdt.displayName;const Uo=({className:s,...t})=>e.jsx("div",{className:zt("flex flex-col space-y-2 text-center sm:text-left",s),...t});Uo.displayName="AlertDialogHeader";const qo=({className:s,...t})=>e.jsx("div",{className:zt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});qo.displayName="AlertDialogFooter";const Vo=k.forwardRef(({className:s,...t},r)=>e.jsx(hdt,{ref:r,className:zt("text-lg font-semibold",s),...t}));Vo.displayName=hdt.displayName;const Ho=k.forwardRef(({className:s,...t},r)=>e.jsx(mdt,{ref:r,className:zt("text-sm text-muted-foreground",s),...t}));Ho.displayName=mdt.displayName;const Oo=k.forwardRef(({className:s,...t},r)=>e.jsx(ddt,{ref:r,className:zt(lL(),s),...t}));Oo.displayName=ddt.displayName;const Go=k.forwardRef(({className:s,...t},r)=>e.jsx(udt,{ref:r,className:zt(lL({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));Go.displayName=udt.displayName;const SJt=[{key:"contacts",label:"Contacts",icon:Mn,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:LE,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:Kf,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:bn,description:"View and upload videos"},{key:"listings",label:"Listings",icon:Pn,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:k1,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:Ma,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:S0,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:vm,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:Jy,description:"Create and manage smart presentations"}];function CJt(){var R;const{user:s}=Cs(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(null),[m,f]=k.useState({email:"",name:"",password:""}),[x,y]=k.useState("create"),[_,b]=k.useState(!1),[j,N]=k.useState(null);k.useEffect(()=>{s&&C()},[s]);const C=async()=>{if(s){a(!0);try{const{data:F,error:O}=await U.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(O)throw O;if(F&&F.length>0){const B=F.map(Q=>Q.assistant_id),{data:K}=await U.from("profiles").select("id, name, email").in("id",B),Z=F.map(Q=>{const W=K==null?void 0:K.find(te=>te.id===Q.assistant_id);return{...Q,permissions:Q.permissions,assistant_profile:W?{name:W.name||"",email:W.email||""}:void 0}});r(Z)}else r([])}catch(F){console.error("Error loading assistants:",F)}finally{a(!1)}}},A=async()=>{if(s){if(x==="link"){if(!m.email.trim()){he.error("Please enter the assistant's email");return}b(!0);try{const{data:{session:F}}=await U.auth.getSession();if(!F)throw new Error("Not authenticated");const{data:O,error:B}=await U.from("profiles").select("id, name, email").eq("email",m.email.trim().toLowerCase()).single();if(B||!O){he.error("No account found with that email. Try creating a new assistant instead.");return}const{data:K}=await U.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",O.id);if(K&&K.length>0){he.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 ${F.access_token}`},body:JSON.stringify({userId:O.id,role:"assistant",action:"add",agentId:s.id})}),Q=await Z.json();if(!Z.ok)throw new Error(Q.error||"Failed to assign assistant role");const{error:W}=await U.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:O.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;he.success(`${O.name||O.email} linked as your assistant`),l(!1),f({email:"",name:"",password:""}),C()}catch(F){console.error("Error linking assistant:",F),he.error(F.message||"Failed to link assistant")}finally{b(!1)}return}if(!m.email.trim()||!m.name.trim()||!m.password.trim()){he.error("Please fill in all fields");return}if(m.password.length<6){he.error("Password must be at least 6 characters");return}b(!0);try{const{data:{session:F}}=await U.auth.getSession();if(!F)throw new Error("Not authenticated");const O=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${F.access_token}`},body:JSON.stringify({email:m.email.trim(),password:m.password,name:m.name.trim(),purpose:"assistant"})}),B=await O.json();if(!O.ok)throw new Error(B.error||"Failed to create assistant account");const K=B.userId||B.id;if(!K)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 ${F.access_token}`},body:JSON.stringify({userId:K,role:"assistant",action:"add",agentId:s.id})}),Q=await Z.json();if(!Z.ok)throw new Error(Q.error||"Failed to assign assistant role");const{error:W}=await U.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:K,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;he.success(`Assistant account created for ${m.name.trim()}`),l(!1),f({email:"",name:"",password:""}),C()}catch(F){console.error("Error adding assistant:",F),he.error(F.message||"Failed to add assistant")}finally{b(!1)}}},E=async()=>{if(!(!d||!s))try{const{data:{session:F}}=await U.auth.getSession();if(!F)throw new Error("Not authenticated");const{error:O}=await U.from("agent_assistant_assignments").delete().eq("id",d.id);if(O)throw O;const{data:B}=await U.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!B||B.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${F.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),he.success("Assistant removed"),c(!1),u(null),C()}catch(F){console.error("Error removing assistant:",F),he.error(F.message||"Failed to remove assistant")}},D=async(F,O,B)=>{N(F);try{const K=t.find(W=>W.id===F);if(!K)return;const Z={...K.permissions,[O]:B},{error:Q}=await U.from("agent_assistant_assignments").update({permissions:Z}).eq("id",F);if(Q)throw Q;r(W=>W.map(te=>te.id===F?{...te,permissions:Z}:te))}catch(K){console.error("Error updating permissions:",K),he.error("Failed to update permissions")}finally{N(null)}};return n?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Ur,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(q,{size:"sm",onClick:()=>{y("create"),l(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Pe,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No assistant assigned. Add one to help manage your contacts, deals, and more."}):e.jsx("div",{className:"space-y-4",children:t.map(F=>{var O,B,K,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(Wn,{className:"h-10 w-10",children:e.jsx(Kn,{children:((B=(O=F.assistant_profile)==null?void 0:O.name)==null?void 0:B.split(" ").map(Q=>Q[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((K=F.assistant_profile)==null?void 0:K.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((Z=F.assistant_profile)==null?void 0:Z.email)||""})]}),e.jsxs(Xe,{variant:"secondary",className:"ml-2",children:[e.jsx(Oh,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(q,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(F),c(!0)},children:e.jsx(zr,{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:SJt.map(Q=>{const W=Q.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:Q.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Q.description})]})]}),e.jsx(Rr,{checked:F.permissions[Q.key]||!1,onCheckedChange:te=>D(F.id,Q.key,te),disabled:j===F.id})]},Q.key)})})]})]},F.id)})})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Add Assistant"}),e.jsx(an,{children:x==="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(q,{variant:x==="create"?"default":"outline",size:"sm",onClick:()=>y("create"),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(q,{variant:x==="link"?"default":"outline",size:"sm",onClick:()=>y("link"),children:[e.jsx(tl,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[x==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"assistant-name",children:"Name"}),e.jsx(Ne,{id:"assistant-name",value:m.name,onChange:F=>f({...m,name:F.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"assistant-email",children:"Email"}),e.jsx(Ne,{id:"assistant-email",type:"email",value:m.email,onChange:F=>f({...m,email:F.target.value}),placeholder:"assistant@email.com"})]}),x==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(Ne,{id:"assistant-password",type:"password",value:m.password,onChange:F=>f({...m,password:F.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(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(q,{onClick:A,disabled:_,children:[_&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),x==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(el,{open:o,onOpenChange:c,children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Remove Assistant?"}),e.jsxs(Ho,{children:["This will remove ",(R=d==null?void 0:d.assistant_profile)==null?void 0:R.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:E,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function Lf(s){this.content=s}Lf.prototype={constructor:Lf,find:function(s){for(var t=0;t>1}};Lf.from=function(s){if(s instanceof Lf)return s;var t=[];if(s)for(var r in s)t.push(r,s[r]);return new Lf(t)};function pdt(s,t,r){for(let n=0;;n++){if(n==s.childCount||n==t.childCount)return s.childCount==t.childCount?null:r;let a=s.child(n),i=t.child(n);if(a==i){r+=a.nodeSize;continue}if(!a.sameMarkup(i))return r;if(a.isText&&a.text!=i.text){for(let l=0;a.text[l]==i.text[l];l++)r++;return r}if(a.content.size||i.content.size){let l=pdt(a.content,i.content,r+1);if(l!=null)return l}r+=a.nodeSize}}function xdt(s,t,r,n){for(let a=s.childCount,i=t.childCount;;){if(a==0||i==0)return a==i?null:{a:r,b:n};let l=s.child(--a),o=t.child(--i),c=l.nodeSize;if(l==o){r-=c,n-=c;continue}if(!l.sameMarkup(o))return{a:r,b:n};if(l.isText&&l.text!=o.text){let d=0,u=Math.min(l.text.length,o.text.length);for(;dt&&n(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,r-u),n,a+u)}o=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,r,n,a){let i="",l=!0;return this.nodesBetween(t,r,(o,c)=>{let d=o.isText?o.text.slice(Math.max(t,c)-c,r-c):o.isLeaf?a?typeof a=="function"?a(o):a:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&d||o.isTextblock)&&n&&(l?l=!1:i+=n),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let r=this.lastChild,n=t.firstChild,a=this.content.slice(),i=0;for(r.isText&&r.sameMarkup(n)&&(a[a.length-1]=r.withText(r.text+n.text),i=1);it)for(let i=0,l=0;lt&&((lr)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,r-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,r-l-1))),n.push(o),a+=o.nodeSize),l=c}return new dx(n,a)}cutByIndex(t,r){return t==r?dx.empty:t==0&&r==this.content.length?this:new dx(this.content.slice(t,r))}replaceChild(t,r){let n=this.content[t];if(n==r)return this;let a=this.content.slice(),i=this.size+r.nodeSize-n.nodeSize;return a[t]=r,new 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 r=0;rthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let r=0,n=0;;r++){let a=this.child(r),i=n+a.nodeSize;if(i>=t)return i==t?jq(r+1,i):jq(r,n);n=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,r){if(!r)return dx.empty;if(!Array.isArray(r))throw new RangeError("Invalid input for Fragment.fromJSON");return new dx(r.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return dx.empty;let r,n=0;for(let a=0;athis.type.rank&&(r||(r=t.slice(0,a)),r.push(this),n=!0),r&&r.push(i)}}return r||(r=t.slice()),n||r.push(this),r}removeFromSet(t){for(let r=0;rn.type.rank-a.type.rank),r}};$c.none=[];class Lme extends Error{}class pa{constructor(t,r,n){this.content=t,this.openStart=r,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,r){let n=ydt(this.content,t+this.openStart,r);return n&&new pa(n,this.openStart,this.openEnd)}removeBetween(t,r){return new pa(gdt(this.content,t+this.openStart,r+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,r){if(!r)return pa.empty;let n=r.openStart||0,a=r.openEnd||0;if(typeof n!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new pa(Rn.fromJSON(t,r.content),n,a)}static maxOpen(t,r=!0){let n=0,a=0;for(let i=t.firstChild;i&&!i.isLeaf&&(r||!i.type.spec.isolating);i=i.firstChild)n++;for(let i=t.lastChild;i&&!i.isLeaf&&(r||!i.type.spec.isolating);i=i.lastChild)a++;return new pa(t,n,a)}}pa.empty=new pa(Rn.empty,0,0);function gdt(s,t,r){let{index:n,offset:a}=s.findIndex(t),i=s.maybeChild(n),{index:l,offset:o}=s.findIndex(r);if(a==t||i.isText){if(o!=r&&!s.child(l).isText)throw new RangeError("Removing non-flat range");return s.cut(0,t).append(s.cut(r))}if(n!=l)throw new RangeError("Removing non-flat range");return s.replaceChild(n,i.copy(gdt(i.content,t-a-1,r-a-1)))}function ydt(s,t,r,n){let{index:a,offset:i}=s.findIndex(t),l=s.maybeChild(a);if(i==t||l.isText)return n&&!n.canReplace(a,a,r)?null:s.cut(0,t).append(r).append(s.cut(t));let o=ydt(l.content,t-i-1,r,l);return o&&s.replaceChild(a,l.copy(o))}function TJt(s,t,r){if(r.openStart>s.depth)throw new Lme("Inserted content deeper than insertion position");if(s.depth-r.openStart!=t.depth-r.openEnd)throw new Lme("Inconsistent open depths");return vdt(s,t,r,0)}function vdt(s,t,r,n){let a=s.index(n),i=s.node(n);if(a==t.index(n)&&n=0&&s.isText&&s.sameMarkup(t[r])?t[r]=s.withText(t[r].text+s.text):t.push(s)}function _7(s,t,r,n){let a=(t||s).node(r),i=0,l=t?t.index(r):a.childCount;s&&(i=s.index(r),s.depth>r?i++:s.textOffset&&(ZE(s.nodeAfter,n),i++));for(let o=i;oa&&Rke(s,t,a+1),l=n.depth>a&&Rke(r,n,a+1),o=[];return _7(null,s,a,o),i&&l&&t.index(a)==r.index(a)?(bdt(i,l),ZE(XE(i,_dt(s,t,r,n,a+1)),o)):(i&&ZE(XE(i,Dme(s,t,a+1)),o),_7(t,r,a,o),l&&ZE(XE(l,Dme(r,n,a+1)),o)),_7(n,null,a,o),new Rn(o)}function Dme(s,t,r){let n=[];if(_7(null,s,r,n),s.depth>r){let a=Rke(s,t,r+1);ZE(XE(a,Dme(s,t,r+1)),n)}return _7(t,null,r,n),new Rn(n)}function EJt(s,t){let r=t.depth-s.openStart,a=t.node(r).copy(s.content);for(let i=r-1;i>=0;i--)a=t.node(i).copy(Rn.from(a));return{start:a.resolveNoCache(s.openStart+r),end:a.resolveNoCache(a.content.size-s.openEnd-r)}}class R9{constructor(t,r,n){this.pos=t,this.path=r,this.parentOffset=n,this.depth=r.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,r=this.index(this.depth);if(r==t.childCount)return null;let n=this.pos-this.path[this.path.length-1],a=t.child(r);return n?t.child(r).cut(n):a}get nodeBefore(){let t=this.index(this.depth),r=this.pos-this.path[this.path.length-1];return r?this.parent.child(t).cut(0,r):t==0?null:this.parent.child(t-1)}posAtIndex(t,r){r=this.resolveDepth(r);let n=this.path[r*3],a=r==0?0:this.path[r*3-1]+1;for(let i=0;i0;r--)if(this.start(r)<=t&&this.end(r)>=t)return r;return 0}blockRange(t=this,r){if(t.pos=0;n--)if(t.pos<=this.end(n)&&(!r||r(this.node(n))))return new Rme(this,t,n);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&r<=t.content.size))throw new RangeError("Position "+r+" out of range");let n=[],a=0,i=r;for(let l=t;;){let{index:o,offset:c}=l.content.findIndex(i),d=i-c;if(n.push(l,o,a+c),!d||(l=l.child(o),l.isText))break;i=d-1,a+=c+1}return new R9(r,n,i)}static resolveCached(t,r){let n=Tze.get(t);if(n)for(let i=0;it&&this.nodesBetween(t,r,i=>(n.isInSet(i.marks)&&(a=!0),!a)),a}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),wdt(this.marks,t)}contentMatchAt(t){let r=this.type.contentMatch.matchFragment(this.content,0,t);if(!r)throw new Error("Called contentMatchAt on a node with invalid content");return r}canReplace(t,r,n=Rn.empty,a=0,i=n.childCount){let l=this.contentMatchAt(t).matchFragment(n,a,i),o=l&&l.matchFragment(this.content,r);if(!o||!o.validEnd)return!1;for(let c=a;cr.type.name)}`);this.content.forEach(r=>r.check())}toJSON(){let t={type:this.type.name};for(let r in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(r=>r.toJSON())),t}static fromJSON(t,r){if(!r)throw new RangeError("Invalid input for Node.fromJSON");let n;if(r.marks){if(!Array.isArray(r.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=r.marks.map(t.markFromJSON)}if(r.type=="text"){if(typeof r.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(r.text,n)}let a=Rn.fromJSON(t,r.content),i=t.nodeType(r.type).create(r.attrs,a,n);return i.type.checkAttrs(i.attrs),i}};vS.prototype.text=void 0;class Ome extends vS{constructor(t,r,n,a){if(super(t,r,null,a),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):wdt(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,r){return this.text.slice(t,r)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new Ome(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new Ome(this.type,this.attrs,t,this.marks)}cut(t=0,r=this.text.length){return t==0&&r==this.text.length?this:this.withText(this.text.slice(t,r))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function wdt(s,t){for(let r=s.length-1;r>=0;r--)t=s[r].type.name+"("+t+")";return t}class NA{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,r){let n=new PJt(t,r);if(n.next==null)return NA.empty;let a=jdt(n);n.next&&n.err("Unexpected trailing text");let i=BJt(zJt(a));return $Jt(i,n),i}matchType(t){for(let r=0;rd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function r(n){t.push(n);for(let a=0;a{let i=a+(n.validEnd?"*":" ")+" ";for(let l=0;l"+t.indexOf(n.next[l].next);return i}).join(` `)}}NA.empty=new NA(!0);class PJt{constructor(t,r){this.string=t,this.nodeTypes=r,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function jdt(s){let t=[];do t.push(LJt(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function LJt(s){let t=[];do t.push(DJt(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function DJt(s){let t=FJt(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=RJt(s,t);else break;return t}function Eze(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function RJt(s,t){let r=Eze(s),n=r;return s.eat(",")&&(s.next!="}"?n=Eze(s):n=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:r,max:n,expr:t}}function OJt(s,t){let r=s.nodeTypes,n=r[t];if(n)return[n];let a=[];for(let i in r){let l=r[i];l.isInGroup(t)&&a.push(l)}return a.length==0&&s.err("No node type or group '"+t+"' found"),a}function FJt(s){if(s.eat("(")){let t=jdt(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=OJt(s,s.next).map(r=>(s.inline==null?s.inline=r.isInline:s.inline!=r.isInline&&s.err("Mixing inline and block content"),{type:"name",value:r}));return s.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function zJt(s){let t=[[]];return a(i(s,0),r()),t;function r(){return t.push([])-1}function n(l,o,c){let d={term:c,to:o};return t[l].push(d),d}function a(l,o){l.forEach(c=>c.to=o)}function i(l,o){if(l.type=="choice")return l.exprs.reduce((c,d)=>c.concat(i(d,o)),[]);if(l.type=="seq")for(let c=0;;c++){let d=i(l.exprs[c],o);if(c==l.exprs.length-1)return d;a(d,o=r())}else if(l.type=="star"){let c=r();return n(o,c),a(i(l.expr,c),c),[n(c)]}else if(l.type=="plus"){let c=r();return a(i(l.expr,o),c),a(i(l.expr,c),c),[n(c)]}else{if(l.type=="opt")return[n(o)].concat(i(l.expr,o));if(l.type=="range"){let c=o;for(let d=0;d{s[l].forEach(({term:o,to:c})=>{if(!o)return;let d;for(let u=0;u{d||a.push([o,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let i=t[n.join(",")]=new NA(n.indexOf(s.length-1)>-1);for(let l=0;l-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:Sdt(this.attrs,t)}create(t=null,r,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new vS(this,this.computeAttrs(t),Rn.from(r),$c.setFrom(n))}createChecked(t=null,r,n){return r=Rn.from(r),this.checkContent(r),new vS(this,this.computeAttrs(t),r,$c.setFrom(n))}createAndFill(t=null,r,n){if(t=this.computeAttrs(t),r=Rn.from(r),r.size){let l=this.contentMatch.fillBefore(r);if(!l)return null;r=l.append(r)}let a=this.contentMatch.matchFragment(r),i=a&&a.fillBefore(Rn.empty,!0);return i?new vS(this,t,r.append(i),$c.setFrom(n)):null}validContent(t){let r=this.contentMatch.matchFragment(t);if(!r||!r.validEnd)return!1;for(let n=0;n-1}allowsMarks(t){if(this.markSet==null)return!0;for(let r=0;rn[i]=new Edt(i,r,l));let a=r.spec.topNode||"doc";if(!n[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let i in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function UJt(s,t,r){let n=r.split("|");return a=>{let i=a===null?"null":typeof a;if(n.indexOf(i)<0)throw new RangeError(`Expected value of type ${n} for attribute ${t} on type ${s}, got ${i}`)}}class qJt{constructor(t,r,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?UJt(t,r,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class Bge{constructor(t,r,n,a){this.name=t,this.rank=r,this.schema=n,this.spec=a,this.attrs=Tdt(t,a.attrs),this.excluded=null;let i=kdt(this.attrs);this.instance=i?new $c(this,i):null}create(t=null){return!t&&this.instance?this.instance:new $c(this,Sdt(this.attrs,t))}static compile(t,r){let n=Object.create(null),a=0;return t.forEach((i,l)=>n[i]=new Bge(i,a++,r,l)),n}removeFromSet(t){for(var r=0;r-1}}class Adt{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let r=this.spec={};for(let a in t)r[a]=t[a];r.nodes=Lf.from(t.nodes),r.marks=Lf.from(t.marks||{}),this.nodes=Mze.compile(this.spec.nodes,this),this.marks=Bge.compile(this.spec.marks,this);let n=Object.create(null);for(let a in this.nodes){if(a in this.marks)throw new RangeError(a+" can not be both a node and a mark");let i=this.nodes[a],l=i.spec.content||"",o=i.spec.marks;if(i.contentMatch=n[l]||(n[l]=NA.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?Ize(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==""?[]:Ize(this,l.split(" "))}this.nodeFromJSON=a=>vS.fromJSON(this,a),this.markFromJSON=a=>$c.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,r=null,n,a){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof Mze){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(r,n,a)}text(t,r){let n=this.nodes.text;return new Ome(n,n.defaultAttrs,t,$c.setFrom(r))}mark(t,r){return typeof t=="string"&&(t=this.marks[t]),t.create(r)}nodeType(t){let r=this.nodes[t];if(!r)throw new RangeError("Unknown node type: "+t);return r}}function Ize(s,t){let r=[];for(let n=0;n-1)&&r.push(l=c)}if(!l)throw new SyntaxError("Unknown mark type: '"+t[n]+"'")}return r}function VJt(s){return s.tag!=null}function HJt(s){return s.style!=null}let w7=class Fke{constructor(t,r){this.schema=t,this.rules=r,this.tags=[],this.styles=[];let n=this.matchedStyles=[];r.forEach(a=>{if(VJt(a))this.tags.push(a);else if(HJt(a)){let i=/[^=]*/.exec(a.style)[0];n.indexOf(i)<0&&n.push(i),this.styles.push(a)}}),this.normalizeLists=!this.tags.some(a=>{if(!/^(ul|ol)\b/.test(a.tag)||!a.node)return!1;let i=t.nodes[a.node];return i.contentMatch.matchType(i)})}parse(t,r={}){let n=new Lze(this,r,!1);return n.addAll(t,$c.none,r.from,r.to),n.finish()}parseSlice(t,r={}){let n=new Lze(this,r,!0);return n.addAll(t,$c.none,r.from,r.to),pa.maxOpen(n.finish())}matchTag(t,r,n){for(let a=n?this.tags.indexOf(n)+1:0;at.length&&(o.charCodeAt(t.length)!=61||o.slice(t.length+1)!=r))){if(l.getAttrs){let c=l.getAttrs(r);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let r=[];function n(a){let i=a.priority==null?50:a.priority,l=0;for(;l{n(l=Dze(l)),l.mark||l.ignore||l.clearMark||(l.mark=a)})}for(let a in t.nodes){let i=t.nodes[a].spec.parseDOM;i&&i.forEach(l=>{n(l=Dze(l)),l.node||l.ignore||l.mark||(l.node=a)})}return r}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new Fke(t,Fke.schemaRules(t)))}};const Mdt={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},GJt={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Idt={ol:!0,ul:!0},O9=1,zke=2,j7=4;function Pze(s,t,r){return t!=null?(t?O9:0)|(t==="full"?zke:0):s&&s.whitespace=="pre"?O9|zke:r&~j7}class Nq{constructor(t,r,n,a,i,l){this.type=t,this.attrs=r,this.marks=n,this.solid=a,this.options=l,this.content=[],this.activeMarks=$c.none,this.match=i||(l&j7?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let r=this.type.contentMatch.fillBefore(Rn.from(t));if(r)this.match=this.type.contentMatch.matchFragment(r);else{let n=this.type.contentMatch,a;return(a=n.findWrapping(t.type))?(this.match=n,a):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&O9)){let n=this.content[this.content.length-1],a;if(n&&n.isText&&(a=/[ \t\r\n\u000c]+$/.exec(n.text))){let i=n;n.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-a[0].length))}}let r=Rn.from(this.content);return!t&&this.match&&(r=r.append(this.match.fillBefore(Rn.empty,!0))),this.type?this.type.create(this.attrs,r,this.marks):r}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!Mdt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Lze{constructor(t,r,n){this.parser=t,this.options=r,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let a=r.topNode,i,l=Pze(null,r.preserveWhitespace,0)|(n?j7:0);a?i=new Nq(a.type,a.attrs,$c.none,!0,r.topMatch||a.type.contentMatch,l):n?i=new Nq(null,null,$c.none,!0,null,l):i=new Nq(t.schema.topNodeType,null,$c.none,!0,null,l),this.nodes=[i],this.find=r.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,r){t.nodeType==3?this.addTextNode(t,r):t.nodeType==1&&this.addElement(t,r)}addTextNode(t,r){let n=t.nodeValue,a=this.top,i=a.options&zke?"full":this.localPreserveWS||(a.options&O9)>0,{schema:l}=this.parser;if(i==="full"||a.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(i)if(i==="full")n=n.replace(/\r\n?/g,` `);else if(l.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(l.linebreakReplacement.create())){let o=n.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(d)):r=r.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)o=c;else break}}return r}addElementByRule(t,r,n,a){let i,l;if(r.node)if(l=this.parser.schema.nodes[r.node],l.isLeaf)this.insertNode(l.create(r.attrs),n,t.nodeName=="BR")||this.leafFallback(t,n);else{let c=this.enter(l,r.attrs||null,n,r.preserveWhitespace);c&&(i=!0,n=c)}else{let c=this.parser.schema.marks[r.mark];n=n.concat(c.create(r.attrs))}let o=this.top;if(l&&l.isLeaf)this.findInside(t);else if(a)this.addElement(t,n,a);else if(r.getContent)this.findInside(t),r.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c,n,!1));else{let c=t;typeof r.contentElement=="string"?c=t.querySelector(r.contentElement):typeof r.contentElement=="function"?c=r.contentElement(t):r.contentElement&&(c=r.contentElement),this.findAround(t,c,!0),this.addAll(c,n),this.findAround(t,c,!1)}i&&this.sync(o)&&this.open--}addAll(t,r,n,a){let i=n||0;for(let l=n?t.childNodes[n]:t.firstChild,o=a==null?null:t.childNodes[a];l!=o;l=l.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(l,r);this.findAtPoint(t,i)}findPlace(t,r,n){let a,i;for(let l=this.open,o=0;l>=0;l--){let c=this.nodes[l],d=c.findWrapping(t);if(d&&(!a||a.length>d.length+o)&&(a=d,i=c,!d.length))break;if(c.solid){if(n)break;o+=2}}if(!a)return null;this.sync(i);for(let l=0;l(l.type?l.type.allowsMarkType(d.type):Rze(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Nq(t,r,c,a,null,o)),this.open++,n}closeExtra(t=!1){let r=this.nodes.length-1;if(r>this.open){for(;r>this.open;r--)this.nodes[r-1].content.push(this.nodes[r].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(t){for(let r=this.open;r>=0;r--){if(this.nodes[r]==t)return this.open=r,!0;this.localPreserveWS&&(this.nodes[r].options|=O9)}return!1}get currentPos(){this.closeExtra();let t=0;for(let r=this.open;r>=0;r--){let n=this.nodes[r].content;for(let a=n.length-1;a>=0;a--)t+=n[a].nodeSize;r&&t++}return t}findAtPoint(t,r){if(this.find)for(let n=0;n-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let r=t.split("/"),n=this.options.context,a=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+(a?0:1),l=(o,c)=>{for(;o>=0;o--){let d=r[o];if(d==""){if(o==r.length-1||o==0)continue;for(;c>=i;c--)if(l(o-1,c))return!0;return!1}else{let u=c>0||c==0&&a?this.nodes[c].type:n&&c>=i?n.node(c-i).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return l(r.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let r=t.depth;r>=0;r--){let n=t.node(r).contentMatchAt(t.indexAfter(r)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let r in this.parser.schema.nodes){let n=this.parser.schema.nodes[r];if(n.isTextblock&&n.defaultAttrs)return n}}}function WJt(s){for(let t=s.firstChild,r=null;t;t=t.nextSibling){let n=t.nodeType==1?t.nodeName.toLowerCase():null;n&&Idt.hasOwnProperty(n)&&r?(r.appendChild(t),t=r):n=="li"?r=t:n&&(r=null)}}function KJt(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function Dze(s){let t={};for(let r in s)t[r]=s[r];return t}function Rze(s,t){let r=t.schema.nodes;for(let n in r){let a=r[n];if(!a.allowsMarkType(s))continue;let i=[],l=o=>{i.push(o);for(let c=0;c{if(i.length||l.marks.length){let o=0,c=0;for(;o=0;a--){let i=this.serializeMark(t.marks[a],t.isInline,r);i&&((i.contentDOM||i.dom).appendChild(n),n=i.dom)}return n}serializeMark(t,r,n={}){let a=this.marks[t.type.name];return a&&Xue(N_e(n),a(t,r),null,t.attrs)}static renderSpec(t,r,n=null,a){return Xue(t,r,n,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new QA(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let r=Oze(t.nodes);return r.text||(r.text=n=>n.text),r}static marksFromSchema(t){return Oze(t.marks)}}function Oze(s){let t={};for(let r in s){let n=s[r].spec.toDOM;n&&(t[r]=n)}return t}function N_e(s){return s.document||window.document}const Fze=new WeakMap;function YJt(s){let t=Fze.get(s);return t===void 0&&Fze.set(s,t=ZJt(s)),t}function ZJt(s){let t=null;function r(n){if(n&&typeof n=="object")if(Array.isArray(n))if(typeof n[0]=="string")t||(t=[]),t.push(n);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=a.indexOf(" ");l>0&&(r=a.slice(0,l),a=a.slice(l+1));let o,c=r?s.createElementNS(r,a):s.createElement(a),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let m in d)if(d[m]!=null){let f=m.indexOf(" ");f>0?c.setAttributeNS(m.slice(0,f),m.slice(f+1),d[m]):m=="style"&&c.style?c.style.cssText=d[m]:c.setAttribute(m,d[m])}}for(let m=u;mu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:x,contentDOM:y}=Xue(s,f,r,n);if(c.appendChild(x),y){if(o)throw new RangeError("Multiple content holes");o=y}}}return{dom:c,contentDOM:o}}const Pdt=65535,Ldt=Math.pow(2,16);function XJt(s,t){return s+t*Ldt}function zze(s){return s&Pdt}function QJt(s){return(s-(s&Pdt))/Ldt}const Ddt=1,Rdt=2,Que=4,Odt=8;class Bke{constructor(t,r,n){this.pos=t,this.delInfo=r,this.recover=n}get deleted(){return(this.delInfo&Odt)>0}get deletedBefore(){return(this.delInfo&(Ddt|Que))>0}get deletedAfter(){return(this.delInfo&(Rdt|Que))>0}get deletedAcross(){return(this.delInfo&Que)>0}}class v0{constructor(t,r=!1){if(this.ranges=t,this.inverted=r,!t.length&&v0.empty)return v0.empty}recover(t){let r=0,n=zze(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],m=c+d;if(t<=m){let f=d?t==c?-1:t==m?1:r:r,x=c+a+(f<0?0:u);if(n)return x;let y=t==(r<0?c:m)?null:XJt(o/3,t-c),_=t==c?Rdt:t==m?Ddt:Que;return(r<0?t!=c:t!=m)&&(_|=Odt),new Bke(x,_,y)}a+=u-d}return n?t+a:new Bke(t+a,0,null)}touches(t,r){let n=0,a=zze(r),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;n+=this.ranges[o+l]-d}return!1}forEach(t){let r=this.inverted?2:1,n=this.inverted?1:2;for(let a=0,i=0;a=0;r--){let a=t.getMirror(r);this.appendMap(t._maps[r].invert(),a!=null&&a>r?n-a-1:void 0)}}invert(){let t=new F9;return t.appendMappingInverted(this),t}map(t,r=1){if(this.mirror)return this._map(t,r,!0);for(let n=this.from;ni&&c!l.isAtom||!o.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),r.openStart,r.openEnd);return Lh.fromReplace(t,this.from,this.to,i)}invert(){return new h_(this.from,this.to,this.mark)}map(t){let r=t.mapResult(this.from,1),n=t.mapResult(this.to,-1);return r.deleted&&n.deleted||r.pos>=n.pos?null:new Fk(r.pos,n.pos,this.mark)}merge(t){return t instanceof Fk&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Fk(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,r){if(typeof r.from!="number"||typeof r.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Fk(r.from,r.to,t.markFromJSON(r.mark))}}Dp.jsonID("addMark",Fk);class h_ extends Dp{constructor(t,r,n){super(),this.from=t,this.to=r,this.mark=n}apply(t){let r=t.slice(this.from,this.to),n=new pa(SEe(r.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),r.openStart,r.openEnd);return Lh.fromReplace(t,this.from,this.to,n)}invert(){return new Fk(this.from,this.to,this.mark)}map(t){let r=t.mapResult(this.from,1),n=t.mapResult(this.to,-1);return r.deleted&&n.deleted||r.pos>=n.pos?null:new h_(r.pos,n.pos,this.mark)}merge(t){return t instanceof h_&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new h_(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,r){if(typeof r.from!="number"||typeof r.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new h_(r.from,r.to,t.markFromJSON(r.mark))}}Dp.jsonID("removeMark",h_);class zk extends Dp{constructor(t,r){super(),this.pos=t,this.mark=r}apply(t){let r=t.nodeAt(this.pos);if(!r)return Lh.fail("No node at mark step's position");let n=r.type.create(r.attrs,null,this.mark.addToSet(r.marks));return Lh.fromReplace(t,this.pos,this.pos+1,new pa(Rn.from(n),0,r.isLeaf?0:1))}invert(t){let r=t.nodeAt(this.pos);if(r){let n=this.mark.addToSet(r.marks);if(n.length==r.marks.length){for(let a=0;an.pos?null:new lf(r.pos,n.pos,a,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,r){if(typeof r.from!="number"||typeof r.to!="number"||typeof r.gapFrom!="number"||typeof r.gapTo!="number"||typeof r.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new lf(r.from,r.to,r.gapFrom,r.gapTo,pa.fromJSON(t,r.slice),r.insert,!!r.structure)}}Dp.jsonID("replaceAround",lf);function $ke(s,t,r){let n=s.resolve(t),a=r-t,i=n.depth;for(;a>0&&i>0&&n.indexAfter(i)==n.node(i).childCount;)i--,a--;if(a>0){let l=n.node(i).maybeChild(n.indexAfter(i));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function JJt(s,t,r,n){let a=[],i=[],l,o;s.doc.nodesBetween(t,r,(c,d,u)=>{if(!c.isInline)return;let m=c.marks;if(!n.isInSet(m)&&u.type.allowsMarkType(n.type)){let f=Math.max(d,t),x=Math.min(d+c.nodeSize,r),y=n.addToSet(m);for(let _=0;_s.step(c)),i.forEach(c=>s.step(c))}function ees(s,t,r,n){let a=[],i=0;s.doc.nodesBetween(t,r,(l,o)=>{if(!l.isInline)return;i++;let c=null;if(n instanceof Bge){let d=l.marks,u;for(;u=n.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else n?n.isInSet(l.marks)&&(c=[n]):c=l.marks;if(c&&c.length){let d=Math.min(o+l.nodeSize,r);for(let u=0;us.step(new h_(l.from,l.to,l.style)))}function CEe(s,t,r,n=r.contentMatch,a=!0){let i=s.doc.nodeAt(t),l=[],o=t+1;for(let c=0;c=0;c--)s.step(l[c])}function tes(s,t,r){return(t==0||s.canReplace(t,s.childCount))&&(r==s.childCount||s.canReplace(0,r))}function P8(s){let r=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let n=s.depth,a=0,i=0;;--n){let l=s.$from.node(n),o=s.$from.index(n)+a,c=s.$to.indexAfter(n)-i;if(nr;y--)_||n.index(y)>0?(_=!0,u=Rn.from(n.node(y).copy(u)),m++):c--;let f=Rn.empty,x=0;for(let y=i,_=!1;y>r;y--)_||a.after(y+1)=0;l--){if(n.size){let o=r[l].type.contentMatch.matchFragment(n);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=Rn.from(r[l].type.create(r[l].attrs,n))}let a=t.start,i=t.end;s.step(new lf(a,i,a,i,new pa(n,0,0),r.length,!0))}function ies(s,t,r,n,a){if(!n.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=s.steps.length;s.doc.nodesBetween(t,r,(l,o)=>{let c=typeof a=="function"?a(l):a;if(l.isTextblock&&!l.hasMarkup(n,c)&&oes(s.doc,s.mapping.slice(i).map(o),n)){let d=null;if(n.schema.linebreakReplacement){let x=n.whitespace=="pre",y=!!n.contentMatch.matchType(n.schema.linebreakReplacement);x&&!y?d=!1:!x&&y&&(d=!0)}d===!1&&zdt(s,l,o,i),CEe(s,s.mapping.slice(i).map(o,1),n,void 0,d===null);let u=s.mapping.slice(i),m=u.map(o,1),f=u.map(o+l.nodeSize,1);return s.step(new lf(m,f,m+1,f-1,new pa(Rn.from(n.create(c,null,l.marks)),0,0),1,!0)),d===!0&&Fdt(s,l,o,i),!1}})}function Fdt(s,t,r,n){t.forEach((a,i)=>{if(a.isText){let l,o=/\r?\n|\r/g;for(;l=o.exec(a.text);){let c=s.mapping.slice(n).map(r+1+i+l.index);s.replaceWith(c,c+1,t.type.schema.linebreakReplacement.create())}}})}function zdt(s,t,r,n){t.forEach((a,i)=>{if(a.type==a.type.schema.linebreakReplacement){let l=s.mapping.slice(n).map(r+1+i);s.replaceWith(l,l+1,t.type.schema.text(` `))}})}function oes(s,t,r){let n=s.resolve(t),a=n.index();return n.parent.canReplaceWith(a,a+1,r)}function les(s,t,r,n,a){let i=s.doc.nodeAt(t);if(!i)throw new RangeError("No node at given position");r||(r=i.type);let l=r.create(n,null,a||i.marks);if(i.isLeaf)return s.replaceWith(t,t+i.nodeSize,l);if(!r.validContent(i.content))throw new RangeError("Invalid content for node type "+r.name);s.step(new lf(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new pa(Rn.from(l),0,0),1,!0))}function jP(s,t,r=1,n){let a=s.resolve(t),i=a.depth-r,l=n&&n[n.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,u=r-2;d>i;d--,u--){let m=a.node(d),f=a.index(d);if(m.type.spec.isolating)return!1;let x=m.content.cutByIndex(f,m.childCount),y=n&&n[u+1];y&&(x=x.replaceChild(0,y.type.create(y.attrs)));let _=n&&n[u]||m;if(!m.canReplace(f+1,m.childCount)||!_.type.validContent(x))return!1}let o=a.indexAfter(i),c=n&&n[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function ces(s,t,r=1,n){let a=s.doc.resolve(t),i=Rn.empty,l=Rn.empty;for(let o=a.depth,c=a.depth-r,d=r-1;o>c;o--,d--){i=Rn.from(a.node(o).copy(i));let u=n&&n[d];l=Rn.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Mh(t,t,new pa(i.append(l),r,r),!0))}function n4(s,t){let r=s.resolve(t),n=r.index();return Bdt(r.nodeBefore,r.nodeAfter)&&r.parent.canReplace(n,n+1)}function des(s,t){t.content.size||s.type.compatibleContent(t.type);let r=s.contentMatchAt(s.childCount),{linebreakReplacement:n}=s.type.schema;for(let a=0;a0?(i=n.node(a+1),o++,l=n.node(a).maybeChild(o)):(i=n.node(a).maybeChild(o-1),l=n.node(a+1)),i&&!i.isTextblock&&Bdt(i,l)&&n.node(a).canReplace(o,o+1))return t;if(a==0)break;t=r<0?n.before(a):n.after(a)}}function ues(s,t,r){let n=null,{linebreakReplacement:a}=s.doc.type.schema,i=s.doc.resolve(t-r),l=i.node().type;if(a&&l.inlineContent){let u=l.whitespace=="pre",m=!!l.contentMatch.matchType(a);u&&!m?n=!1:!u&&m&&(n=!0)}let o=s.steps.length;if(n===!1){let u=s.doc.resolve(t+r);zdt(s,u.node(),u.before(),o)}l.inlineContent&&CEe(s,t+r-1,l,i.node().contentMatchAt(i.index()),n==null);let c=s.mapping.slice(o),d=c.map(t-r);if(s.step(new Mh(d,c.map(t+r,-1),pa.empty,!0)),n===!0){let u=s.doc.resolve(d);Fdt(s,u.node(),u.before(),s.steps.length)}return s}function hes(s,t,r){let n=s.resolve(t);if(n.parent.canReplaceWith(n.index(),n.index(),r))return t;if(n.parentOffset==0)for(let a=n.depth-1;a>=0;a--){let i=n.index(a);if(n.node(a).canReplaceWith(i,i,r))return n.before(a+1);if(i>0)return null}if(n.parentOffset==n.parent.content.size)for(let a=n.depth-1;a>=0;a--){let i=n.indexAfter(a);if(n.node(a).canReplaceWith(i,i,r))return n.after(a+1);if(i=0;l--){let o=l==n.depth?0:n.pos<=(n.start(l+1)+n.end(l+1))/2?-1:1,c=n.index(l)+(o>0?1:0),d=n.node(l),u=!1;if(i==1)u=d.canReplace(c,c,a);else{let m=d.contentMatchAt(c).findWrapping(a.firstChild.type);u=m&&d.canReplaceWith(c,c,m[0])}if(u)return o==0?n.pos:o<0?n.before(l+1):n.after(l+1)}return null}function Uge(s,t,r=t,n=pa.empty){if(t==r&&!n.size)return null;let a=s.resolve(t),i=s.resolve(r);return Udt(a,i,n)?new Mh(t,r,n):new mes(a,i,n).fit()}function Udt(s,t,r){return!r.openStart&&!r.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),r.content)}class mes{constructor(t,r,n){this.$from=t,this.$to=r,this.unplaced=n,this.frontier=[],this.placed=Rn.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=Rn.from(t.node(a).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),r=this.placed.size-this.depth-this.$from.depth,n=this.$from,a=this.close(t<0?this.$to:n.doc.resolve(t));if(!a)return null;let i=this.placed,l=n.depth,o=a.depth;for(;l&&o&&i.childCount==1;)i=i.firstChild.content,l--,o--;let c=new pa(i,l,o);return t>-1?new lf(n.pos,t,this.$to.pos,this.$to.end(),c,r):c.size||n.pos!=this.$to.pos?new Mh(n.pos,a.pos,c):null}findFittable(){let t=this.unplaced.openStart;for(let r=this.unplaced.content,n=0,a=this.unplaced.openEnd;n1&&(a=0),i.type.spec.isolating&&a<=n){t=n;break}r=i.content}for(let r=1;r<=2;r++)for(let n=r==1?t:this.unplaced.openStart;n>=0;n--){let a,i=null;n?(i=S_e(this.unplaced.content,n-1).firstChild,a=i.content):a=this.unplaced.content;let l=a.firstChild;for(let o=this.depth;o>=0;o--){let{type:c,match:d}=this.frontier[o],u,m=null;if(r==1&&(l?d.matchType(l.type)||(m=d.fillBefore(Rn.from(l),!1)):i&&c.compatibleContent(i.type)))return{sliceDepth:n,frontierDepth:o,parent:i,inject:m};if(r==2&&l&&(u=d.findWrapping(l.type)))return{sliceDepth:n,frontierDepth:o,parent:i,wrap:u};if(i&&d.matchType(i.type))break}}}openMore(){let{content:t,openStart:r,openEnd:n}=this.unplaced,a=S_e(t,r);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new pa(t,r+1,Math.max(n,a.size+r>=t.size-n?r+1:0)),!0)}dropNode(){let{content:t,openStart:r,openEnd:n}=this.unplaced,a=S_e(t,r);if(a.childCount<=1&&r>0){let i=t.size-r<=r+a.size;this.unplaced=new pa(PO(t,r-1,1),r-1,i?r-1:n)}else this.unplaced=new pa(PO(t,r,1),r,n)}placeNodes({sliceDepth:t,frontierDepth:r,parent:n,inject:a,wrap:i}){for(;this.depth>r;)this.closeFrontierNode();if(i)for(let _=0;_1||c==0||_.content.size)&&(m=b,u.push(qdt(_.mark(f.allowedMarks(_.marks)),d==1?c:0,d==o.childCount?x:-1)))}let y=d==o.childCount;y||(x=-1),this.placed=LO(this.placed,r,Rn.from(u)),this.frontier[r].match=m,y&&x<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let _=0,b=o;_1&&a==this.$to.end(--n);)++a;return a}findCloseLevel(t){e:for(let r=Math.min(this.depth,t.depth);r>=0;r--){let{match:n,type:a}=this.frontier[r],i=r=0;o--){let{match:c,type:d}=this.frontier[o],u=C_e(t,o,d,c,!0);if(!u||u.childCount)continue e}return{depth:r,fit:l,move:i?t.doc.resolve(t.after(r+1)):t}}}}close(t){let r=this.findCloseLevel(t);if(!r)return null;for(;this.depth>r.depth;)this.closeFrontierNode();r.fit.childCount&&(this.placed=LO(this.placed,r.depth,r.fit)),t=r.move;for(let n=r.depth+1;n<=t.depth;n++){let a=t.node(n),i=a.type.contentMatch.fillBefore(a.content,!0,t.index(n));this.openFrontierNode(a.type,a.attrs,i)}return t}openFrontierNode(t,r=null,n){let a=this.frontier[this.depth];a.match=a.match.matchType(t),this.placed=LO(this.placed,this.depth,Rn.from(t.create(r,n))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let r=this.frontier.pop().match.fillBefore(Rn.empty,!0);r.childCount&&(this.placed=LO(this.placed,this.frontier.length,r))}}function PO(s,t,r){return t==0?s.cutByIndex(r,s.childCount):s.replaceChild(0,s.firstChild.copy(PO(s.firstChild.content,t-1,r)))}function LO(s,t,r){return t==0?s.append(r):s.replaceChild(s.childCount-1,s.lastChild.copy(LO(s.lastChild.content,t-1,r)))}function S_e(s,t){for(let r=0;r1&&(n=n.replaceChild(0,qdt(n.firstChild,t-1,n.childCount==1?r-1:0))),t>0&&(n=s.type.contentMatch.fillBefore(n).append(n),r<=0&&(n=n.append(s.type.contentMatch.matchFragment(n).fillBefore(Rn.empty,!0)))),s.copy(n)}function C_e(s,t,r,n,a){let i=s.node(t),l=a?s.indexAfter(t):s.index(t);if(l==i.childCount&&!r.compatibleContent(i.type))return null;let o=n.fillBefore(i.content,!0,l);return o&&!fes(r,i.content,l)?o:null}function fes(s,t,r){for(let n=r;n0;f--,x--){let y=a.node(f).type.spec;if(y.defining||y.definingAsContext||y.isolating)break;l.indexOf(f)>-1?o=f:a.before(f)==x&&l.splice(1,0,-f)}let c=l.indexOf(o),d=[],u=n.openStart;for(let f=n.content,x=0;;x++){let y=f.firstChild;if(d.push(y),x==n.openStart)break;f=y.content}for(let f=u-1;f>=0;f--){let x=d[f],y=pes(x.type);if(y&&!x.sameMarkup(a.node(Math.abs(o)-1)))u=f;else if(y||!x.type.isTextblock)break}for(let f=n.openStart;f>=0;f--){let x=(f+u+1)%(n.openStart+1),y=d[x];if(y)for(let _=0;_=0&&(s.replace(t,r,n),!(s.steps.length>m));f--){let x=l[f];x<0||(t=a.before(x),r=i.after(x))}}function Vdt(s,t,r,n,a){if(tn){let i=a.contentMatchAt(0),l=i.fillBefore(s).append(s);s=l.append(i.matchFragment(l).fillBefore(Rn.empty,!0))}return s}function ges(s,t,r,n){if(!n.isInline&&t==r&&s.doc.resolve(t).parent.content.size){let a=hes(s.doc,t,n.type);a!=null&&(t=r=a)}s.replaceRange(t,r,new pa(Rn.from(n),0,0))}function yes(s,t,r){let n=s.doc.resolve(t),a=s.doc.resolve(r);if(n.parent.isTextblock&&a.parent.isTextblock&&n.start()!=a.start()&&n.parentOffset==0&&a.parentOffset==0){let l=n.sharedDepth(r),o=!1;for(let c=n.depth;c>l;c--)n.node(c).type.spec.isolating&&(o=!0);for(let c=a.depth;c>l;c--)a.node(c).type.spec.isolating&&(o=!0);if(!o){for(let c=n.depth;c>0&&t==n.start(c);c--)t=n.before(c);for(let c=a.depth;c>0&&r==a.start(c);c--)r=a.before(c);n=s.doc.resolve(t),a=s.doc.resolve(r)}}let i=Hdt(n,a);for(let l=0;l0&&(c||n.node(o-1).canReplace(n.index(o-1),a.indexAfter(o-1))))return s.delete(n.before(o),a.after(o))}for(let l=1;l<=n.depth&&l<=a.depth;l++)if(t-n.start(l)==n.depth-l&&r>n.end(l)&&a.end(l)-r!=a.depth-l&&n.start(l-1)==a.start(l-1)&&n.node(l-1).canReplace(n.index(l-1),a.index(l-1)))return s.delete(n.before(l),r);s.delete(t,r)}function Hdt(s,t){let r=[],n=Math.min(s.depth,t.depth);for(let a=n;a>=0;a--){let i=s.start(a);if(it.pos+(t.depth-a)||s.node(a).type.spec.isolating||t.node(a).type.spec.isolating)break;(i==t.start(a)||a==s.depth&&a==t.depth&&s.parent.inlineContent&&t.parent.inlineContent&&a&&t.start(a-1)==i-1)&&r.push(a)}return r}class NP extends Dp{constructor(t,r,n){super(),this.pos=t,this.attr=r,this.value=n}apply(t){let r=t.nodeAt(this.pos);if(!r)return Lh.fail("No node at attribute step's position");let n=Object.create(null);for(let i in r.attrs)n[i]=r.attrs[i];n[this.attr]=this.value;let a=r.type.create(n,null,r.marks);return Lh.fromReplace(t,this.pos,this.pos+1,new pa(Rn.from(a),0,r.isLeaf?0:1))}getMap(){return v0.empty}invert(t){return new NP(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let r=t.mapResult(this.pos,1);return r.deletedAfter?null:new NP(r.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,r){if(typeof r.pos!="number"||typeof r.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new NP(r.pos,r.attr,r.value)}}Dp.jsonID("attr",NP);class z9 extends Dp{constructor(t,r){super(),this.attr=t,this.value=r}apply(t){let r=Object.create(null);for(let a in t.attrs)r[a]=t.attrs[a];r[this.attr]=this.value;let n=t.type.create(r,t.content,t.marks);return Lh.ok(n)}getMap(){return v0.empty}invert(t){return new z9(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,r){if(typeof r.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new z9(r.attr,r.value)}}Dp.jsonID("docAttr",z9);let xL=class extends Error{};xL=function s(t){let r=Error.call(this,t);return r.__proto__=s.prototype,r};xL.prototype=Object.create(Error.prototype);xL.prototype.constructor=xL;xL.prototype.name="TransformError";let EEe=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new F9}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let r=this.maybeStep(t);if(r.failed)throw new xL(r.failed);return this}maybeStep(t){let r=t.apply(this.doc);return r.failed||this.addStep(t,r.doc),r}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,r=-1e9;for(let n=0;n{t=Math.min(t,o),r=Math.max(r,c)})}return t==1e9?null:{from:t,to:r}}addStep(t,r){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=r}replace(t,r=t,n=pa.empty){let a=Uge(this.doc,t,r,n);return a&&this.step(a),this}replaceWith(t,r,n){return this.replace(t,r,new pa(Rn.from(n),0,0))}delete(t,r){return this.replace(t,r,pa.empty)}insert(t,r){return this.replaceWith(t,t,r)}replaceRange(t,r,n){return xes(this,t,r,n),this}replaceRangeWith(t,r,n){return ges(this,t,r,n),this}deleteRange(t,r){return yes(this,t,r),this}lift(t,r){return ses(this,t,r),this}join(t,r=1){return ues(this,t,r),this}wrap(t,r){return aes(this,t,r),this}setBlockType(t,r=t,n,a=null){return ies(this,t,r,n,a),this}setNodeMarkup(t,r,n=null,a){return les(this,t,r,n,a),this}setNodeAttribute(t,r,n){return this.step(new NP(t,r,n)),this}setDocAttribute(t,r){return this.step(new z9(t,r)),this}addNodeMark(t,r){return this.step(new zk(t,r)),this}removeNodeMark(t,r){let n=this.doc.nodeAt(t);if(!n)throw new RangeError("No node at position "+t);if(r instanceof $c)r.isInSet(n.marks)&&this.step(new kA(t,r));else{let a=n.marks,i,l=[];for(;i=r.isInSet(a);)l.push(new kA(t,i)),a=i.removeFromSet(a);for(let o=l.length-1;o>=0;o--)this.step(l[o])}return this}split(t,r=1,n){return ces(this,t,r,n),this}addMark(t,r,n){return JJt(this,t,r,n),this}removeMark(t,r,n){return ees(this,t,r,n),this}clearIncompatible(t,r,n){return CEe(this,t,r,n),this}};const T_e=Object.create(null);class Qi{constructor(t,r,n){this.$anchor=t,this.$head=r,this.ranges=n||[new Gdt(t.min(r),t.max(r))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let r=0;r=0;i--){let l=r<0?tI(t.node(0),t.node(i),t.before(i+1),t.index(i),r,n):tI(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,r,n);if(l)return l}return null}static near(t,r=1){return this.findFrom(t,r)||this.findFrom(t,-r)||new rv(t.node(0))}static atStart(t){return tI(t,t,0,0,1)||new rv(t)}static atEnd(t){return tI(t,t,t.content.size,t.childCount,-1)||new rv(t)}static fromJSON(t,r){if(!r||!r.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=T_e[r.type];if(!n)throw new RangeError(`No selection type ${r.type} defined`);return n.fromJSON(t,r)}static jsonID(t,r){if(t in T_e)throw new RangeError("Duplicate use of selection JSON ID "+t);return T_e[t]=r,r.prototype.jsonID=t,r}getBookmark(){return Oi.between(this.$anchor,this.$head).getBookmark()}}Qi.prototype.visible=!0;class Gdt{constructor(t,r){this.$from=t,this.$to=r}}let $ze=!1;function Uze(s){!$ze&&!s.parent.inlineContent&&($ze=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Oi extends Qi{constructor(t,r=t){Uze(t),Uze(r),super(t,r)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,r){let n=t.resolve(r.map(this.head));if(!n.parent.inlineContent)return Qi.near(n);let a=t.resolve(r.map(this.anchor));return new Oi(a.parent.inlineContent?a:n,n)}replace(t,r=pa.empty){if(super.replace(t,r),r==pa.empty){let n=this.$from.marksAcross(this.$to);n&&t.ensureMarks(n)}}eq(t){return t instanceof Oi&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new qge(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,r){if(typeof r.anchor!="number"||typeof r.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Oi(t.resolve(r.anchor),t.resolve(r.head))}static create(t,r,n=r){let a=t.resolve(r);return new this(a,n==r?a:t.resolve(n))}static between(t,r,n){let a=t.pos-r.pos;if((!n||a)&&(n=a>=0?1:-1),!r.parent.inlineContent){let i=Qi.findFrom(r,n,!0)||Qi.findFrom(r,-n,!0);if(i)r=i.$head;else return Qi.near(r,n)}return t.parent.inlineContent||(a==0?t=r:(t=(Qi.findFrom(t,-n,!0)||Qi.findFrom(t,n,!0)).$anchor,t.pos0?0:1);a>0?l=0;l+=a){let o=t.child(l);if(o.isAtom){if(!i&&Ei.isSelectable(o))return Ei.create(s,r-(a<0?o.nodeSize:0))}else{let c=tI(s,o,r+a,a<0?o.childCount:0,a,i);if(c)return c}r+=o.nodeSize*a}return null}function qze(s,t,r){let n=s.steps.length-1;if(n{l==null&&(l=u)}),s.setSelection(Qi.near(s.doc.resolve(l),r))}const Vze=1,kq=2,Hze=4;class bes extends EEe{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|=kq,this}ensureMarks(t){return $c.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&kq)>0}addStep(t,r){super.addStep(t,r),this.updated=this.updated&~kq,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,r=!0){let n=this.selection;return r&&(t=t.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||$c.none))),n.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,r,n){let a=this.doc.type.schema;if(r==null)return t?this.replaceSelectionWith(a.text(t),!0):this.deleteSelection();{if(n==null&&(n=r),!t)return this.deleteRange(r,n);let i=this.storedMarks;if(!i){let l=this.doc.resolve(r);i=n==r?l.marks():l.marksAcross(this.doc.resolve(n))}return this.replaceRangeWith(r,n,a.text(t,i)),!this.selection.empty&&this.selection.to==r+t.length&&this.setSelection(Qi.near(this.selection.$to)),this}}setMeta(t,r){return this.meta[typeof t=="string"?t:t.key]=r,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Hze,this}get scrolledIntoView(){return(this.updated&Hze)>0}}function Gze(s,t){return!t||!s?s:s.bind(t)}class DO{constructor(t,r,n){this.name=t,this.init=Gze(r.init,n),this.apply=Gze(r.apply,n)}}const _es=[new DO("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new DO("selection",{init(s,t){return s.selection||Qi.atStart(t.doc)},apply(s){return s.selection}}),new DO("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,r,n){return n.selection.$cursor?s.storedMarks:null}}),new DO("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class E_e{constructor(t,r){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=_es.slice(),r&&r.forEach(n=>{if(this.pluginsByKey[n.key])throw new RangeError("Adding different instances of a keyed plugin ("+n.key+")");this.plugins.push(n),this.pluginsByKey[n.key]=n,n.spec.state&&this.fields.push(new DO(n.key,n.spec.state,n))})}}class NI{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,r=-1){for(let n=0;nn.toJSON())),t&&typeof t=="object")for(let n in t){if(n=="doc"||n=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let a=t[n],i=a.spec.state;i&&i.toJSON&&(r[n]=i.toJSON.call(a,this[a.key]))}return r}static fromJSON(t,r,n){if(!r)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let a=new E_e(t.schema,t.plugins),i=new NI(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=vS.fromJSON(t.schema,r.doc);else if(l.name=="selection")i.selection=Qi.fromJSON(i.doc,r.selection);else if(l.name=="storedMarks")r.storedMarks&&(i.storedMarks=r.storedMarks.map(t.schema.markFromJSON));else{if(n)for(let o in n){let c=n[o],d=c.spec.state;if(c.key==l.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(r,o)){i[l.name]=d.fromJSON.call(c,t,r[o],i);return}}i[l.name]=l.init(t,i)}}),i}}function Wdt(s,t,r){for(let n in s){let a=s[n];a instanceof Function?a=a.bind(t):n=="handleDOMEvents"&&(a=Wdt(a,t,{})),r[n]=a}return r}class Tm{constructor(t){this.spec=t,this.props={},t.props&&Wdt(t.props,this,this.props),this.key=t.key?t.key.key:Kdt("plugin")}getState(t){return t[this.key]}}const A_e=Object.create(null);function Kdt(s){return s in A_e?s+"$"+ ++A_e[s]:(A_e[s]=0,s+"$")}class Rp{constructor(t="key"){this.key=Kdt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const zf=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},gL=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let Uke=null;const Mj=function(s,t,r){let n=Uke||(Uke=document.createRange());return n.setEnd(s,r??s.nodeValue.length),n.setStart(s,t||0),n},wes=function(){Uke=null},SA=function(s,t,r,n){return r&&(Wze(s,t,r,n,-1)||Wze(s,t,r,n,1))},jes=/^(img|br|input|textarea|hr)$/i;function Wze(s,t,r,n,a){for(var i;;){if(s==r&&t==n)return!0;if(t==(a<0?0:By(s))){let l=s.parentNode;if(!l||l.nodeType!=1||AB(s)||jes.test(s.nodeName)||s.contentEditable=="false")return!1;t=zf(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?By(s):0}else return!1}}function By(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function Nes(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=By(s)}else if(s.parentNode&&!AB(s))t=zf(s),s=s.parentNode;else return null}}function kes(s,t){for(;;){if(s.nodeType==3&&t2),Ly=yL||(U_?/Mac/.test(U_.platform):!1),Xdt=U_?/Win/.test(U_.platform):!1,Kj=/Android \d/.test(a4),MB=!!Kze&&"webkitFontSmoothing"in Kze.documentElement.style,Ees=MB?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Aes(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 fj(s,t){return typeof s=="number"?s:s[t]}function Mes(s){let t=s.getBoundingClientRect(),r=t.width/s.offsetWidth||1,n=t.height/s.offsetHeight||1;return{left:t.left,right:t.left+s.clientWidth*r,top:t.top,bottom:t.top+s.clientHeight*n}}function Yze(s,t,r){let n=s.someProp("scrollThreshold")||0,a=s.someProp("scrollMargin")||5,i=s.dom.ownerDocument;for(let l=r||s.dom;l;){if(l.nodeType!=1){l=gL(l);continue}let o=l,c=o==i.body,d=c?Aes(i):Mes(o),u=0,m=0;if(t.topd.bottom-fj(n,"bottom")&&(m=t.bottom-t.top>d.bottom-d.top?t.top+fj(a,"top")-d.top:t.bottom-d.bottom+fj(a,"bottom")),t.leftd.right-fj(n,"right")&&(u=t.right-d.right+fj(a,"right")),u||m)if(c)i.defaultView.scrollBy(u,m);else{let x=o.scrollLeft,y=o.scrollTop;m&&(o.scrollTop+=m),u&&(o.scrollLeft+=u);let _=o.scrollLeft-x,b=o.scrollTop-y;t={left:t.left-_,top:t.top-b,right:t.right-_,bottom:t.bottom-b}}let f=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(f))break;l=f=="absolute"?l.offsetParent:gL(l)}}function Ies(s){let t=s.dom.getBoundingClientRect(),r=Math.max(0,t.top),n,a;for(let i=(t.left+t.right)/2,l=r+1;l=r-20){n=o,a=c.top;break}}return{refDOM:n,refTop:a,stack:Qdt(s.dom)}}function Qdt(s){let t=[],r=s.ownerDocument;for(let n=s;n&&(t.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),s!=r);n=gL(n));return t}function Pes({refDOM:s,refTop:t,stack:r}){let n=s?s.getBoundingClientRect().top:0;Jdt(r,n==0?0:n-t)}function Jdt(s,t){for(let r=0;r=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});!r&&(t.left>=y.right&&t.top>=y.top||t.left>=y.left&&t.top>=y.bottom)&&(i=m+1)}}return!r&&c&&(r=c,a=d,n=0),r&&r.nodeType==3?Des(r,a):!r||n&&r.nodeType==1?{node:s,offset:i}:eut(r,a)}function Des(s,t){let r=s.nodeValue.length,n=document.createRange(),a;for(let i=0;i=(l.left+l.right)/2?1:0)};break}}return n.detach(),a||{node:s,offset:0}}function MEe(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function Res(s,t){let r=s.parentNode;return r&&/^li$/i.test(r.nodeName)&&t.left(l.left+l.right)/2?1:-1}return s.docView.posFromDOM(n,a,i)}function Fes(s,t,r,n){let a=-1;for(let i=t,l=!1;i!=s.dom;){let o=s.docView.nearestDesc(i,!0),c;if(!o)return null;if(o.dom.nodeType==1&&(o.node.isBlock&&o.parent||!o.contentDOM)&&((c=o.dom.getBoundingClientRect()).width||c.height)&&(o.node.isBlock&&o.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(o.dom.nodeName)&&(!l&&c.left>n.left||c.top>n.top?a=o.posBefore:(!l&&c.right-1?a:s.docView.posFromDOM(t,r,-1)}function tut(s,t,r){let n=s.childNodes.length;if(n&&r.topt.top&&a++}let d;MB&&a&&n.nodeType==1&&(d=n.childNodes[a-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=t.top&&a--,n==s.dom&&a==n.childNodes.length-1&&n.lastChild.nodeType==1&&t.top>n.lastChild.getBoundingClientRect().bottom?o=s.state.doc.content.size:(a==0||n.nodeType!=1||n.childNodes[a-1].nodeName!="BR")&&(o=Fes(s,n,a,t))}o==null&&(o=Oes(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function Zze(s){return s.top=0&&a==n.nodeValue.length?(c--,u=1):r<0?c--:d++,WR(XN(Mj(n,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(r<0||a==By(n))){let c=n.childNodes[a-1];if(c.nodeType==1)return M_e(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(r<0||a==By(n))){let c=n.childNodes[a-1],d=c.nodeType==3?Mj(c,By(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return WR(XN(d,1),!1)}if(i==null&&a=0)}function WR(s,t){if(s.width==0)return s;let r=t?s.left:s.right;return{top:s.top,bottom:s.bottom,left:r,right:r}}function M_e(s,t){if(s.height==0)return s;let r=t?s.top:s.bottom;return{top:r,bottom:r,left:s.left,right:s.right}}function rut(s,t,r){let n=s.state,a=s.root.activeElement;n!=t&&s.updateState(t),a!=s.dom&&s.focus();try{return r()}finally{n!=t&&s.updateState(n),a!=s.dom&&a&&a.focus()}}function $es(s,t,r){let n=t.selection,a=r=="up"?n.$from:n.$to;return rut(s,t,()=>{let{node:i}=s.docView.domFromPos(a.pos,r=="up"?-1:1);for(;;){let o=s.docView.nearestDesc(i,!0);if(!o)break;if(o.node.isBlock){i=o.contentDOM||o.dom;break}i=o.dom.parentNode}let l=sut(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=Mj(o,0,o.nodeValue.length).getClientRects();else continue;for(let d=0;du.top+1&&(r=="up"?l.top-u.top>(u.bottom-l.top)*2:u.bottom-l.bottom>(l.bottom-u.top)*2))return!1}}return!0})}const Ues=/[\u0590-\u08ac]/;function qes(s,t,r){let{$head:n}=t.selection;if(!n.parent.isTextblock)return!1;let a=n.parentOffset,i=!a,l=a==n.parent.content.size,o=s.domSelection();return o?!Ues.test(n.parent.textContent)||!o.modify?r=="left"||r=="backward"?i:l:rut(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:m}=s.domSelectionRange(),f=o.caretBidiLevel;o.modify("move",r,"character");let x=n.depth?s.docView.domAfterPos(n.before()):s.dom,{focusNode:y,focusOffset:_}=s.domSelectionRange(),b=y&&!x.contains(y.nodeType==1?y:y.parentNode)||c==y&&d==_;try{o.collapse(u,m),c&&(c!=u||d!=m)&&o.extend&&o.extend(c,d)}catch{}return f!=null&&(o.caretBidiLevel=f),b}):n.pos==n.start()||n.pos==n.end()}let Xze=null,Qze=null,Jze=!1;function Ves(s,t,r){return Xze==t&&Qze==r?Jze:(Xze=t,Qze=r,Jze=r=="up"||r=="down"?$es(s,t,r):qes(s,t,r))}const av=0,eBe=1,JT=2,q_=3;class IB{constructor(t,r,n,a){this.parent=t,this.children=r,this.dom=n,this.contentDOM=a,this.dirty=av,n.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,r,n){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let r=0;rzf(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=t.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(r==0)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!1;break}if(i.previousSibling)break}if(a==null&&r==t.childNodes.length)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!0;break}if(i.nextSibling)break}}return a??n>0?this.posAtEnd:this.posAtStart}nearestDesc(t,r=!1){for(let n=!0,a=t;a;a=a.parentNode){let i=this.getDesc(a),l;if(i&&(!r||i.node))if(n&&(l=i.nodeDOM)&&!(l.nodeType==1?l.contains(t.nodeType==1?t:t.parentNode):l==t))n=!1;else return i}}getDesc(t){let r=t.pmViewDesc;for(let n=r;n;n=n.parent)if(n==this)return r}posFromDOM(t,r,n){for(let a=t;a;a=a.parentNode){let i=this.getDesc(a);if(i)return i.localPosFromDOM(t,r,n)}return-1}descAt(t){for(let r=0,n=0;rt||l instanceof aut){a=t-i;break}i=o}if(a)return this.children[n].domFromPos(a-this.children[n].border,r);for(let i;n&&!(i=this.children[n-1]).size&&i instanceof nut&&i.side>=0;n--);if(r<=0){let i,l=!0;for(;i=n?this.children[n-1]:null,!(!i||i.dom.parentNode==this.contentDOM);n--,l=!1);return i&&r&&l&&!i.border&&!i.domAtom?i.domFromPos(i.size,r):{node:this.contentDOM,offset:i?zf(i.dom)+1:0}}else{let i,l=!0;for(;i=n=u&&r<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,r,u);t=l;for(let m=o;m>0;m--){let f=this.children[m-1];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(1)){a=zf(f.dom)+1;break}t-=f.size}a==-1&&(a=0)}if(a>-1&&(d>r||o==this.children.length-1)){r=d;for(let u=o+1;uy&&lr){let y=o;o=c,c=y}let x=document.createRange();x.setEnd(c.node,c.offset),x.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(x)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,r){for(let n=0,a=0;a=n:tn){let o=n+i.border,c=l-i.border;if(t>=o&&r<=c){this.dirty=t==n||r==l?JT:eBe,t==o&&r==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=q_:i.markDirty(t-o,r-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?JT:q_}n=l}this.dirty=JT}markParentsDirty(){let t=1;for(let r=this.parent;r;r=r.parent,t++){let n=t==1?JT:eBe;r.dirty{if(!i)return a;if(i.parent)return i.parent.posBeforeChild(i)})),!r.type.spec.raw){if(l.nodeType!=1){let o=document.createElement("span");o.appendChild(l),l=o}l.contentEditable="false",l.classList.add("ProseMirror-widget")}super(t,[],l,null),this.widget=r,this.widget=r,i=this}matchesWidget(t){return this.dirty==av&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let r=this.widget.spec.stopEvent;return r?r(t):!1}ignoreMutation(t){return t.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Hes extends IB{constructor(t,r,n,a){super(t,[],r,null),this.textDOM=n,this.text=a}get size(){return this.text.length}localPosFromDOM(t,r){return t!=this.textDOM?this.posAtStart+(r?this.size:0):this.posAtStart+r}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class CA extends IB{constructor(t,r,n,a,i){super(t,[],n,a),this.mark=r,this.spec=i}static create(t,r,n,a){let i=a.nodeViews[r.type.name],l=i&&i(r,a,n);return(!l||!l.dom)&&(l=QA.renderSpec(document,r.type.spec.toDOM(r,n),null,r.attrs)),new CA(t,r,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&q_||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=q_&&this.mark.eq(t)}markDirty(t,r){if(super.markDirty(t,r),this.dirty!=av){let n=this.parent;for(;!n.node;)n=n.parent;n.dirty0&&(i=Wke(i,0,t,n));for(let o=0;o{if(!c)return l;if(c.parent)return c.parent.posBeforeChild(c)},n,a),u=d&&d.dom,m=d&&d.contentDOM;if(r.isText){if(!u)u=document.createTextNode(r.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:m}=QA.renderSpec(document,r.type.spec.toDOM(r),null,r.attrs));!m&&!r.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),r.type.spec.draggable&&(u.draggable=!0));let f=u;return u=lut(u,n,r),d?c=new Ges(t,r,n,a,u,m||null,f,d,i,l+1):r.isText?new Hge(t,r,n,a,u,f,i):new _S(t,r,n,a,u,m||null,f,i,l+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let n=this.children[r];if(this.dom.contains(n.dom.parentNode)){t.contentElement=n.dom.parentNode;break}}t.contentElement||(t.getContent=()=>Rn.empty)}return t}matchesNode(t,r,n){return this.dirty==av&&t.eq(this.node)&&Fme(r,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,r){let n=this.node.inlineContent,a=r,i=t.composing?this.localCompositionInfo(t,r):null,l=i&&i.pos>-1?i:null,o=i&&i.pos<0,c=new Kes(this,l&&l.node,t);Xes(this.node,this.innerDeco,(d,u,m)=>{d.spec.marks?c.syncToMarks(d.spec.marks,n,t,u):d.type.side>=0&&!m&&c.syncToMarks(u==this.node.childCount?$c.none:this.node.child(u).marks,n,t,u),c.placeWidget(d,t,a)},(d,u,m,f)=>{c.syncToMarks(d.marks,n,t,f);let x;c.findNodeMatch(d,u,m,f)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,m,x,t)||c.updateNextNode(d,u,m,t,f,a)||c.addNode(d,u,m,t,a),a+=d.nodeSize}),c.syncToMarks([],n,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==JT)&&(l&&this.protectLocalComposition(t,l),iut(this.contentDOM,this.children,t),yL&&Qes(this.dom))}localCompositionInfo(t,r){let{from:n,to:a}=t.state.selection;if(!(t.state.selection instanceof Oi)||nr+this.node.content.size)return null;let i=t.input.compositionNode;if(!i||!this.dom.contains(i.parentNode))return null;if(this.node.inlineContent){let l=i.nodeValue,o=Jes(this.node.content,l,n-r,a-r);return o<0?null:{node:i,pos:o,text:l}}else return{node:i,pos:-1,text:""}}protectLocalComposition(t,{node:r,pos:n,text:a}){if(this.getDesc(r))return;let i=r;for(;i.parentNode!=this.contentDOM;i=i.parentNode){for(;i.previousSibling;)i.parentNode.removeChild(i.previousSibling);for(;i.nextSibling;)i.parentNode.removeChild(i.nextSibling);i.pmViewDesc&&(i.pmViewDesc=void 0)}let l=new Hes(this,i,r,a);t.input.compositionNodes.push(l),this.children=Wke(this.children,n,n+a.length,t,l)}update(t,r,n,a){return this.dirty==q_||!t.sameMarkup(this.node)?!1:(this.updateInner(t,r,n,a),!0)}updateInner(t,r,n,a){this.updateOuterDeco(r),this.node=t,this.innerDeco=n,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=av}updateOuterDeco(t){if(Fme(t,this.outerDeco))return;let r=this.nodeDOM.nodeType!=1,n=this.dom;this.dom=out(this.dom,this.nodeDOM,Gke(this.outerDeco,this.node,r),Gke(t,this.node,r)),this.dom!=n&&(n.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function tBe(s,t,r,n,a){lut(n,t,s);let i=new _S(void 0,s,t,r,n,n,n,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class Hge extends _S{constructor(t,r,n,a,i,l,o){super(t,r,n,a,i,null,l,o,0)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,r,n,a){return this.dirty==q_||this.dirty!=av&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(r),(this.dirty!=av||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=av,!0)}inParent(){let t=this.parent.contentDOM;for(let r=this.nodeDOM;r;r=r.parentNode)if(r==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,r,n){return t==this.nodeDOM?this.posAtStart+Math.min(r,this.node.text.length):super.localPosFromDOM(t,r,n)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,r,n){let a=this.node.cut(t,r),i=document.createTextNode(a.text);return new Hge(this.parent,a,this.outerDeco,this.innerDeco,i,i,n)}markDirty(t,r){super.markDirty(t,r),this.dom!=this.nodeDOM&&(t==0||r==this.nodeDOM.nodeValue.length)&&(this.dirty=q_)}get domAtom(){return!1}isText(t){return this.node.text==t}}class aut extends IB{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==av&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Ges extends _S{constructor(t,r,n,a,i,l,o,c,d,u){super(t,r,n,a,i,l,o,d,u),this.spec=c}update(t,r,n,a){if(this.dirty==q_)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let i=this.spec.update(t,r,n);return i&&this.updateInner(t,r,n,a),i}else return!this.contentDOM&&!t.isLeaf?!1:super.update(t,r,n,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,r,n,a){this.spec.setSelection?this.spec.setSelection(t,r,n.root):super.setSelection(t,r,n,a)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(t){return this.spec.stopEvent?this.spec.stopEvent(t):!1}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}}function iut(s,t,r){let n=s.firstChild,a=!1;for(let i=0;i>1,o=Math.min(l,t.length);for(;i-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let u=CA.create(this.top,t[l],r,n);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,l++}}findNodeMatch(t,r,n,a){let i=-1,l;if(a>=this.preMatch.index&&(l=this.preMatch.matches[a-this.preMatch.index]).parent==this.top&&l.matchesNode(t,r,n))i=this.top.children.indexOf(l,this.index);else for(let o=this.index,c=Math.min(this.top.children.length,o+5);o0;){let o;for(;;)if(n){let d=r.children[n-1];if(d instanceof CA)r=d,n=d.children.length;else{o=d,n--;break}}else{if(r==t)break e;n=r.parent.children.indexOf(r),r=r.parent}let c=o.node;if(c){if(c!=s.child(a-1))break;--a,i.set(o,a),l.push(o)}}return{index:a,matched:i,matches:l.reverse()}}function Zes(s,t){return s.type.side-t.type.side}function Xes(s,t,r,n){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let y=i+f.nodeSize;if(f.isText){let b=y;l!b.inline):o.slice();n(f,_,t.forChild(i,f),x),i=y}}function Qes(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 Jes(s,t,r,n){for(let a=0,i=0;a=r){if(i>=n&&c.slice(n-t.length-o,n-o)==t)return n-t.length;let d=o=0&&d+t.length+o>=r)return o+d;if(r==n&&c.length>=n+t.length-o&&c.slice(n-o,n-o+t.length)==t)return n}}return-1}function Wke(s,t,r,n,a){let i=[];for(let l=0,o=0;l=r||u<=t?i.push(c):(dr&&i.push(c.slice(r-d,c.size,n)))}return i}function IEe(s,t=null){let r=s.domSelectionRange(),n=s.state.doc;if(!r.focusNode)return null;let a=s.docView.nearestDesc(r.focusNode),i=a&&a.size==0,l=s.docView.posFromDOM(r.focusNode,r.focusOffset,1);if(l<0)return null;let o=n.resolve(l),c,d;if(Vge(r)){for(c=l;a&&!a.node;)a=a.parent;let m=a.node;if(a&&m.isAtom&&Ei.isSelectable(m)&&a.parent&&!(m.isInline&&Ses(r.focusNode,r.focusOffset,a.dom))){let f=a.posBefore;d=new Ei(l==f?o:n.resolve(f))}}else{if(r instanceof s.dom.ownerDocument.defaultView.Selection&&r.rangeCount>1){let m=l,f=l;for(let x=0;x{(r.anchorNode!=n||r.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!cut(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function tts(s){let t=s.domSelection();if(!t)return;let r=s.cursorWrapper.dom,n=r.nodeName=="IMG";n?t.collapse(r.parentNode,zf(r)+1):t.collapse(r,0),!n&&!s.state.selection.visible&&bg&&bS<=11&&(r.disabled=!0,r.disabled=!1)}function dut(s,t){if(t instanceof Ei){let r=s.docView.descAt(t.from);r!=s.lastSelectedViewDesc&&(iBe(s),r&&r.selectNode(),s.lastSelectedViewDesc=r)}else iBe(s)}function iBe(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function PEe(s,t,r,n){return s.someProp("createSelectionBetween",a=>a(s,t,r))||Oi.between(t,r,n)}function oBe(s){return s.editable&&!s.hasFocus()?!1:uut(s)}function uut(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 sts(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),r=s.domSelectionRange();return SA(t.node,t.offset,r.anchorNode,r.anchorOffset)}function Kke(s,t){let{$anchor:r,$head:n}=s.selection,a=t>0?r.max(n):r.min(n),i=a.parent.inlineContent?a.depth?s.doc.resolve(t>0?a.after():a.before()):null:a;return i&&Qi.findFrom(i,t)}function ak(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function lBe(s,t,r){let n=s.state.selection;if(n instanceof Oi)if(r.indexOf("s")>-1){let{$head:a}=n,i=a.textOffset?null:t<0?a.nodeBefore:a.nodeAfter;if(!i||i.isText||!i.isLeaf)return!1;let l=s.state.doc.resolve(a.pos+i.nodeSize*(t<0?-1:1));return ak(s,new Oi(n.$anchor,l))}else if(n.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=Kke(s.state,t);return a&&a instanceof Ei?ak(s,a):!1}else if(!(Ly&&r.indexOf("m")>-1)){let a=n.$head,i=a.textOffset?null:t<0?a.nodeBefore:a.nodeAfter,l;if(!i||i.isText)return!1;let o=t<0?a.pos-i.nodeSize:a.pos;return i.isAtom||(l=s.docView.descAt(o))&&!l.contentDOM?Ei.isSelectable(i)?ak(s,new Ei(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):MB?ak(s,new Oi(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(n instanceof Ei&&n.node.isInline)return ak(s,new Oi(t>0?n.$to:n.$from));{let a=Kke(s.state,t);return a?ak(s,a):!1}}}function zme(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function k7(s,t){let r=s.pmViewDesc;return r&&r.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function S6(s,t){return t<0?rts(s):nts(s)}function rts(s){let t=s.domSelectionRange(),r=t.focusNode,n=t.focusOffset;if(!r)return;let a,i,l=!1;for(nv&&r.nodeType==1&&n0){if(r.nodeType!=1)break;{let o=r.childNodes[n-1];if(k7(o,-1))a=r,i=--n;else if(o.nodeType==3)r=o,n=r.nodeValue.length;else break}}else{if(hut(r))break;{let o=r.previousSibling;for(;o&&k7(o,-1);)a=r.parentNode,i=zf(o),o=o.previousSibling;if(o)r=o,n=zme(r);else{if(r=r.parentNode,r==s.dom)break;n=0}}}l?Yke(s,r,n):a&&Yke(s,a,i)}function nts(s){let t=s.domSelectionRange(),r=t.focusNode,n=t.focusOffset;if(!r)return;let a=zme(r),i,l;for(;;)if(n{s.state==a&&p2(s)},50)}function cBe(s,t){let r=s.state.doc.resolve(t);if(!(Vf||Xdt)&&r.parent.inlineContent){let a=s.coordsAtPos(t);if(t>r.start()){let i=s.coordsAtPos(t-1),l=(i.top+i.bottom)/2;if(l>a.top&&l1)return i.lefta.top&&l1)return i.left>a.left?"ltr":"rtl"}}return getComputedStyle(s.dom).direction=="rtl"?"rtl":"ltr"}function dBe(s,t,r){let n=s.state.selection;if(n instanceof Oi&&!n.empty||r.indexOf("s")>-1||Ly&&r.indexOf("m")>-1)return!1;let{$from:a,$to:i}=n;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=Kke(s.state,t);if(l&&l instanceof Ei)return ak(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=n instanceof rv?Qi.near(l,t):Qi.findFrom(l,t);return o?ak(s,o):!1}return!1}function uBe(s,t){if(!(s.state.selection instanceof Oi))return!0;let{$head:r,$anchor:n,empty:a}=s.state.selection;if(!r.sameParent(n))return!0;if(!a)return!1;if(s.endOfTextblock(t>0?"forward":"backward"))return!0;let i=!r.textOffset&&(t<0?r.nodeBefore:r.nodeAfter);if(i&&!i.isText){let l=s.state.tr;return t<0?l.delete(r.pos-i.nodeSize,r.pos):l.delete(r.pos,r.pos+i.nodeSize),s.dispatch(l),!0}return!1}function hBe(s,t,r){s.domObserver.stop(),t.contentEditable=r,s.domObserver.start()}function ots(s){if(!Ip||s.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:r}=s.domSelectionRange();if(t&&t.nodeType==1&&r==0&&t.firstChild&&t.firstChild.contentEditable=="false"){let n=t.firstChild;hBe(s,n,"true"),setTimeout(()=>hBe(s,n,"false"),20)}return!1}function lts(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function cts(s,t){let r=t.keyCode,n=lts(t);if(r==8||Ly&&r==72&&n=="c")return uBe(s,-1)||S6(s,-1);if(r==46&&!t.shiftKey||Ly&&r==68&&n=="c")return uBe(s,1)||S6(s,1);if(r==13||r==27)return!0;if(r==37||Ly&&r==66&&n=="c"){let a=r==37?cBe(s,s.state.selection.from)=="ltr"?-1:1:-1;return lBe(s,a,n)||S6(s,a)}else if(r==39||Ly&&r==70&&n=="c"){let a=r==39?cBe(s,s.state.selection.from)=="ltr"?1:-1:1;return lBe(s,a,n)||S6(s,a)}else{if(r==38||Ly&&r==80&&n=="c")return dBe(s,-1,n)||S6(s,-1);if(r==40||Ly&&r==78&&n=="c")return ots(s)||dBe(s,1,n)||S6(s,1);if(n==(Ly?"m":"c")&&(r==66||r==73||r==89||r==90))return!0}return!1}function LEe(s,t){s.someProp("transformCopied",x=>{t=x(t,s)});let r=[],{content:n,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&n.childCount==1&&n.firstChild.childCount==1;){a--,i--;let x=n.firstChild;r.push(x.type.name,x.attrs!=x.type.defaultAttrs?x.attrs:null),n=x.content}let l=s.someProp("clipboardSerializer")||QA.fromSchema(s.state.schema),o=yut(),c=o.createElement("div");c.appendChild(l.serializeFragment(n,{document:o}));let d=c.firstChild,u,m=0;for(;d&&d.nodeType==1&&(u=gut[d.nodeName.toLowerCase()]);){for(let x=u.length-1;x>=0;x--){let y=o.createElement(u[x]);for(;c.firstChild;)y.appendChild(c.firstChild);c.appendChild(y),m++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${m?` -${m}`:""} ${JSON.stringify(r)}`);let f=s.someProp("clipboardTextSerializer",x=>x(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:f,slice:t}}function mut(s,t,r,n,a){let i=a.parent.type.spec.code,l,o;if(!r&&!t)return null;let c=!!t&&(n||i||!r);if(c){if(s.someProp("transformPastedText",f=>{t=f(t,i||n,s)}),i)return o=new pa(Rn.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",f=>{o=f(o,s,!0)}),o;let m=s.someProp("clipboardTextParser",f=>f(t,a,n,s));if(m)o=m;else{let f=a.marks(),{schema:x}=s.state,y=QA.fromSchema(x);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(_=>{let b=l.appendChild(document.createElement("p"));_&&b.appendChild(y.serializeNode(x.text(_,f)))})}}else s.someProp("transformPastedHTML",m=>{r=m(r,s)}),l=mts(r),MB&&fts(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 m=+u[3];m>0;m--){let f=l.firstChild;for(;f&&f.nodeType!=1;)f=f.nextSibling;if(!f)break;l=f}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||w7.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(f){return f.nodeName=="BR"&&!f.nextSibling&&f.parentNode&&!dts.test(f.parentNode.nodeName)?{ignore:!0}:null}})),u)o=pts(mBe(o,+u[1],+u[2]),u[4]);else if(o=pa.maxOpen(uts(o.content,a),!0),o.openStart||o.openEnd){let m=0,f=0;for(let x=o.content.firstChild;m{o=m(o,s,c)}),o}const dts=/^(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 uts(s,t){if(s.childCount<2)return s;for(let r=t.depth;r>=0;r--){let a=t.node(r).contentMatchAt(t.index(r)),i,l=[];if(s.forEach(o=>{if(!l)return;let c=a.findWrapping(o.type),d;if(!c)return l=null;if(d=l.length&&i.length&&put(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=xut(l[l.length-1],i.length));let u=fut(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Rn.from(l)}return s}function fut(s,t,r=0){for(let n=t.length-1;n>=r;n--)s=t[n].create(null,Rn.from(s));return s}function put(s,t,r,n,a){if(a1&&(i=0),a=r&&(o=t<0?l.contentMatchAt(0).fillBefore(o,i<=a).append(o):o.append(l.contentMatchAt(l.childCount).fillBefore(Rn.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function mBe(s,t,r){return tr})),P_e.createHTML(s)):s}function mts(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let r=yut().createElement("div"),n=/<([a-z][^>\s]+)/i.exec(s),a;if((a=n&&gut[n[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),r.innerHTML=hts(s),a)for(let i=0;i=0;o-=2){let c=r.nodes[n[o]];if(!c||c.hasRequiredAttrs())break;a=Rn.from(c.create(n[o+1],a)),i++,l++}return new pa(a,i,l)}const Mx={},Ix={},xts={touchstart:!0,touchmove:!0};class gts{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 yts(s){for(let t in Mx){let r=Mx[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=n=>{bts(s,n)&&!DEe(s,n)&&(s.editable||!(n.type in Ix))&&r(s,n)},xts[t]?{passive:!0}:void 0)}Ip&&s.dom.addEventListener("input",()=>null),Xke(s)}function Bk(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function vts(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 Xke(s){s.someProp("handleDOMEvents",t=>{for(let r in t)s.input.eventHandlers[r]||s.dom.addEventListener(r,s.input.eventHandlers[r]=n=>DEe(s,n))})}function DEe(s,t){return s.someProp("handleDOMEvents",r=>{let n=r[t.type];return n?n(s,t)||t.defaultPrevented:!1})}function bts(s,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let r=t.target;r!=s.dom;r=r.parentNode)if(!r||r.nodeType==11||r.pmViewDesc&&r.pmViewDesc.stopEvent(t))return!1;return!0}function _ts(s,t){!DEe(s,t)&&Mx[t.type]&&(s.editable||!(t.type in Ix))&&Mx[t.type](s,t)}Ix.keydown=(s,t)=>{let r=t;if(s.input.shiftKey=r.keyCode==16||r.shiftKey,!but(s,r)&&(s.input.lastKeyCode=r.keyCode,s.input.lastKeyCodeTime=Date.now(),!(Kj&&Vf&&r.keyCode==13)))if(r.keyCode!=229&&s.domObserver.forceFlush(),yL&&r.keyCode==13&&!r.ctrlKey&&!r.altKey&&!r.metaKey){let n=Date.now();s.input.lastIOSEnter=n,s.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{s.input.lastIOSEnter==n&&(s.someProp("handleKeyDown",a=>a(s,UT(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",n=>n(s,r))||cts(s,r)?r.preventDefault():Bk(s,"key")};Ix.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};Ix.keypress=(s,t)=>{let r=t;if(but(s,r)||!r.charCode||r.ctrlKey&&!r.altKey||Ly&&r.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,r))){r.preventDefault();return}let n=s.state.selection;if(!(n instanceof Oi)||!n.$from.sameParent(n.$to)){let a=String.fromCharCode(r.charCode),i=()=>s.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!s.someProp("handleTextInput",l=>l(s,n.$from.pos,n.$to.pos,a,i))&&s.dispatch(i()),r.preventDefault()}};function Gge(s){return{left:s.clientX,top:s.clientY}}function wts(s,t){let r=t.x-s.clientX,n=t.y-s.clientY;return r*r+n*n<100}function REe(s,t,r,n,a){if(n==-1)return!1;let i=s.state.doc.resolve(n);for(let l=i.depth+1;l>0;l--)if(s.someProp(t,o=>l>i.depth?o(s,r,i.nodeAfter,i.before(l),a,!0):o(s,r,i.node(l),i.before(l),a,!1)))return!0;return!1}function kP(s,t,r){if(s.focused||s.focus(),s.state.selection.eq(t))return;let n=s.state.tr.setSelection(t);n.setMeta("pointer",!0),s.dispatch(n)}function jts(s,t){if(t==-1)return!1;let r=s.state.doc.resolve(t),n=r.nodeAfter;return n&&n.isAtom&&Ei.isSelectable(n)?(kP(s,new Ei(r)),!0):!1}function Nts(s,t){if(t==-1)return!1;let r=s.state.selection,n,a;r instanceof Ei&&(n=r.node);let i=s.state.doc.resolve(t);for(let l=i.depth+1;l>0;l--){let o=l>i.depth?i.nodeAfter:i.node(l);if(Ei.isSelectable(o)){n&&r.$from.depth>0&&l>=r.$from.depth&&i.before(r.$from.depth+1)==r.$from.pos?a=i.before(r.$from.depth):a=i.before(l);break}}return a!=null?(kP(s,Ei.create(s.state.doc,a)),!0):!1}function kts(s,t,r,n,a){return REe(s,"handleClickOn",t,r,n)||s.someProp("handleClick",i=>i(s,t,n))||(a?Nts(s,r):jts(s,r))}function Sts(s,t,r,n){return REe(s,"handleDoubleClickOn",t,r,n)||s.someProp("handleDoubleClick",a=>a(s,t,n))}function Cts(s,t,r,n){return REe(s,"handleTripleClickOn",t,r,n)||s.someProp("handleTripleClick",a=>a(s,t,n))||Tts(s,r,n)}function Tts(s,t,r){if(r.button!=0)return!1;let n=s.state.doc;if(t==-1)return n.inlineContent?(kP(s,Oi.create(n,0,n.content.size)),!0):!1;let a=n.resolve(t);for(let i=a.depth+1;i>0;i--){let l=i>a.depth?a.nodeAfter:a.node(i),o=a.before(i);if(l.inlineContent)kP(s,Oi.create(n,o+1,o+1+l.content.size));else if(Ei.isSelectable(l))kP(s,Ei.create(n,o));else continue;return!0}}function OEe(s){return Bme(s)}const vut=Ly?"metaKey":"ctrlKey";Mx.mousedown=(s,t)=>{let r=t;s.input.shiftKey=r.shiftKey;let n=OEe(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&wts(r,s.input.lastClick)&&!r[vut]&&s.input.lastClick.button==r.button&&(s.input.lastClick.type=="singleClick"?i="doubleClick":s.input.lastClick.type=="doubleClick"&&(i="tripleClick")),s.input.lastClick={time:a,x:r.clientX,y:r.clientY,type:i,button:r.button};let l=s.posAtCoords(Gge(r));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new Ets(s,l,r,!!n)):(i=="doubleClick"?Sts:Cts)(s,l.pos,l.inside,r)?r.preventDefault():Bk(s,"pointer"))};class Ets{constructor(t,r,n,a){this.view=t,this.pos=r,this.event=n,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=t.state.doc,this.selectNode=!!n[vut],this.allowDefault=n.shiftKey;let i,l;if(r.inside>-1)i=t.state.doc.nodeAt(r.inside),l=r.inside;else{let u=t.state.doc.resolve(r.pos);i=u.parent,l=u.depth?u.before():0}const o=a?null:n.target,c=o?t.docView.nearestDesc(o,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=t.state;n.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof Ei&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&nv&&!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)),Bk(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(()=>p2(this.view)),this.view.input.mouseDown=null}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let r=this.pos;this.view.state.doc!=this.startDoc&&(r=this.view.posAtCoords(Gge(t))),this.updateAllowDefault(t),this.allowDefault||!r?Bk(this.view,"pointer"):kts(this.view,r.pos,r.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||Ip&&this.mightDrag&&!this.mightDrag.node.isAtom||Vf&&!this.view.state.selection.visible&&Math.min(Math.abs(r.pos-this.view.state.selection.from),Math.abs(r.pos-this.view.state.selection.to))<=2)?(kP(this.view,Qi.near(this.view.state.doc.resolve(r.pos))),t.preventDefault()):Bk(this.view,"pointer")}move(t){this.updateAllowDefault(t),Bk(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)}}Mx.touchstart=s=>{s.input.lastTouch=Date.now(),OEe(s),Bk(s,"pointer")};Mx.touchmove=s=>{s.input.lastTouch=Date.now(),Bk(s,"pointer")};Mx.contextmenu=s=>OEe(s);function but(s,t){return s.composing?!0:Ip&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const Ats=Kj?5e3:-1;Ix.compositionstart=Ix.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,r=t.selection.$to;if(t.selection instanceof Oi&&(t.storedMarks||!r.textOffset&&r.parentOffset&&r.nodeBefore.marks.some(n=>n.type.spec.inclusive===!1)||Vf&&Xdt&&Mts(s)))s.markCursor=s.state.storedMarks||r.marks(),Bme(s,!0),s.markCursor=null;else if(Bme(s,!t.selection.empty),nv&&t.selection.empty&&r.parentOffset&&!r.textOffset&&r.nodeBefore.marks.length){let n=s.domSelectionRange();for(let a=n.focusNode,i=n.focusOffset;a&&a.nodeType==1&&i!=0;){let l=i<0?a.lastChild:a.childNodes[i-1];if(!l)break;if(l.nodeType==3){let o=s.domSelection();o&&o.collapse(l,l.nodeValue.length);break}else a=l,i=-1}}s.input.composing=!0}_ut(s,Ats)};function Mts(s){let{focusNode:t,focusOffset:r}=s.domSelectionRange();if(!t||t.nodeType!=1||r>=t.childNodes.length)return!1;let n=t.childNodes[r];return n.nodeType==1&&n.contentEditable=="false"}Ix.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++,_ut(s,20))};function _ut(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>Bme(s),t))}function wut(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Pts());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function Its(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let r=Nes(t.focusNode,t.focusOffset),n=kes(t.focusNode,t.focusOffset);if(r&&n&&r!=n){let a=n.pmViewDesc,i=s.domObserver.lastChangedTextNode;if(r==i||n==i)return i;if(!a||!a.isText(n.nodeValue))return n;if(s.input.compositionNode==n){let l=r.pmViewDesc;if(!(!l||!l.isText(r.nodeValue)))return n}}return r||n}function Pts(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function Bme(s,t=!1){if(!(Kj&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),wut(s),t||s.docView&&s.docView.dirty){let r=IEe(s),n=s.state.selection;return r&&!r.eq(n)?s.dispatch(s.state.tr.setSelection(r)):(s.markCursor||t)&&!n.$from.node(n.$from.sharedDepth(n.to)).inlineContent?s.dispatch(s.state.tr.deleteSelection()):s.updateState(s.state),!0}return!1}}function Lts(s,t){if(!s.dom.parentNode)return;let r=s.dom.parentNode.appendChild(document.createElement("div"));r.appendChild(t),r.style.cssText="position: fixed; left: -10000px; top: 10px";let n=getSelection(),a=document.createRange();a.selectNodeContents(t),s.dom.blur(),n.removeAllRanges(),n.addRange(a),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r),s.focus()},50)}const B9=bg&&bS<15||yL&&Ees<604;Mx.copy=Ix.cut=(s,t)=>{let r=t,n=s.state.selection,a=r.type=="cut";if(n.empty)return;let i=B9?null:r.clipboardData,l=n.content(),{dom:o,text:c}=LEe(s,l);i?(r.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):Lts(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Dts(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function Rts(s,t){if(!s.dom.parentNode)return;let r=s.input.shiftKey||s.state.selection.$from.parent.type.spec.code,n=s.dom.parentNode.appendChild(document.createElement(r?"textarea":"div"));r||(n.contentEditable="true"),n.style.cssText="position: fixed; left: -10000px; top: 10px",n.focus();let a=s.input.shiftKey&&s.input.lastKeyCode!=45;setTimeout(()=>{s.focus(),n.parentNode&&n.parentNode.removeChild(n),r?$9(s,n.value,null,a,t):$9(s,n.textContent,n.innerHTML,a,t)},50)}function $9(s,t,r,n,a){let i=mut(s,t,r,n,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||pa.empty)))return!0;if(!i)return!1;let l=Dts(i),o=l?s.state.tr.replaceSelectionWith(l,n):s.state.tr.replaceSelection(i);return s.dispatch(o.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function jut(s){let t=s.getData("text/plain")||s.getData("Text");if(t)return t;let r=s.getData("text/uri-list");return r?r.replace(/\r?\n/g," "):""}Ix.paste=(s,t)=>{let r=t;if(s.composing&&!Kj)return;let n=B9?null:r.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;n&&$9(s,jut(n),n.getData("text/html"),a,r)?r.preventDefault():Rts(s,r)};class Nut{constructor(t,r,n){this.slice=t,this.move=r,this.node=n}}const Ots=Ly?"altKey":"ctrlKey";function kut(s,t){let r;return s.someProp("dragCopies",n=>{r=r||n(t)}),r!=null?!r:!t[Ots]}Mx.dragstart=(s,t)=>{let r=t,n=s.input.mouseDown;if(n&&n.done(),!r.dataTransfer)return;let a=s.state.selection,i=a.empty?null:s.posAtCoords(Gge(r)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Ei?a.to-1:a.to))){if(n&&n.mightDrag)l=Ei.create(s.state.doc,n.mightDrag.pos);else if(r.target&&r.target.nodeType==1){let m=s.docView.nearestDesc(r.target,!0);m&&m.node.type.spec.draggable&&m!=s.docView&&(l=Ei.create(s.state.doc,m.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=LEe(s,o);(!r.dataTransfer.files.length||!Vf||Zdt>120)&&r.dataTransfer.clearData(),r.dataTransfer.setData(B9?"Text":"text/html",c.innerHTML),r.dataTransfer.effectAllowed="copyMove",B9||r.dataTransfer.setData("text/plain",d),s.dragging=new Nut(u,kut(s,r),l)};Mx.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};Ix.dragover=Ix.dragenter=(s,t)=>t.preventDefault();Ix.drop=(s,t)=>{try{Fts(s,t,s.dragging)}finally{s.dragging=null}};function Fts(s,t,r){if(!t.dataTransfer)return;let n=s.posAtCoords(Gge(t));if(!n)return;let a=s.state.doc.resolve(n.pos),i=r&&r.slice;i?s.someProp("transformPasted",x=>{i=x(i,s,!1)}):i=mut(s,jut(t.dataTransfer),B9?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(r&&kut(s,t));if(s.someProp("handleDrop",x=>x(s,t,i||pa.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?$dt(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:x}=r;x?x.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,m=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(m))return;let f=c.doc.resolve(d);if(u&&Ei.isSelectable(i.content.firstChild)&&f.nodeAfter&&f.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Ei(f));else{let x=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((y,_,b,j)=>x=j),c.setSelection(PEe(s,f,c.doc.resolve(x)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}Mx.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())&&p2(s)},20))};Mx.blur=(s,t)=>{let r=t;s.focused&&(s.domObserver.stop(),s.dom.classList.remove("ProseMirror-focused"),s.domObserver.start(),r.relatedTarget&&s.dom.contains(r.relatedTarget)&&s.domObserver.currentSelection.clear(),s.focused=!1)};Mx.beforeinput=(s,t)=>{if(Vf&&Kj&&t.inputType=="deleteContentBackward"){s.domObserver.flushSoon();let{domChangeCount:n}=s.input;setTimeout(()=>{if(s.input.domChangeCount!=n||(s.dom.blur(),s.focus(),s.someProp("handleKeyDown",i=>i(s,UT(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 Ix)Mx[s]=Ix[s];function U9(s,t){if(s==t)return!0;for(let r in s)if(s[r]!==t[r])return!1;for(let r in t)if(!(r in s))return!1;return!0}class $me{constructor(t,r){this.toDOM=t,this.spec=r||QE,this.side=this.spec.side||0}map(t,r,n,a){let{pos:i,deleted:l}=t.mapResult(r.from+a,this.side<0?-1:1);return l?null:new jx(i-n,i-n,this)}valid(){return!0}eq(t){return this==t||t instanceof $me&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&U9(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class wS{constructor(t,r){this.attrs=t,this.spec=r||QE}map(t,r,n,a){let i=t.map(r.from+a,this.spec.inclusiveStart?-1:1)-n,l=t.map(r.to+a,this.spec.inclusiveEnd?1:-1)-n;return i>=l?null:new jx(i,l,this)}valid(t,r){return r.from=t&&(!i||i(o.spec))&&n.push(o.copy(o.from+a,o.to+a))}for(let l=0;lt){let o=this.children[l]+1;this.children[l+2].findInner(t-o,r-o,n,a+o,i)}}map(t,r,n){return this==_p||t.maps.length==0?this:this.mapInner(t,r,0,0,n||QE)}mapInner(t,r,n,a,i){let l;for(let o=0;o{let d=c+n,u;if(u=Cut(r,o,d)){for(a||(a=this.children.slice());io&&m.to=t){this.children[o]==t&&(n=this.children[o+2]);break}let i=t+1,l=i+r.content.size;for(let o=0;oi&&c.type instanceof wS){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,r,QE));return yk.from(n)}forChild(t,r){if(r.isLeaf)return Fu.empty;let n=[];for(let a=0;ar instanceof Fu)?t:t.reduce((r,n)=>r.concat(n instanceof Fu?n:n.members),[]))}}forEachSet(t){for(let r=0;r{let b=_-y-(x-f);for(let j=0;jN+u-m)continue;let C=o[j]+u-m;x>=C?o[j+1]=f<=C?-2:-1:f>=u&&b&&(o[j]+=b,o[j+1]+=b)}m+=b}),u=r.maps[d].map(u,-1)}let c=!1;for(let d=0;d=n.content.size){c=!0;continue}let f=r.map(s[d+1]+i,-1),x=f-a,{index:y,offset:_}=n.content.findIndex(m),b=n.maybeChild(y);if(b&&_==m&&_+b.nodeSize==x){let j=o[d+2].mapInner(r,b,u+1,s[d]+i+1,l);j!=_p?(o[d]=m,o[d+1]=x,o[d+2]=j):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=Bts(o,s,t,r,a,i,l),u=Ume(d,n,0,l);t=u.local;for(let m=0;mr&&l.to{let d=Cut(s,o,c+r);if(d){i=!0;let u=Ume(d,o,r+c+1,n);u!=_p&&a.push(c,c+o.nodeSize,u)}});let l=Sut(i?Tut(s):s,-r).sort(JE);for(let o=0;o0;)t++;s.splice(t,0,r)}function L_e(s){let t=[];return s.someProp("decorations",r=>{let n=r(s.state);n&&n!=_p&&t.push(n)}),s.cursorWrapper&&t.push(Fu.create(s.state.doc,[s.cursorWrapper.deco])),yk.from(t)}const $ts={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Uts=bg&&bS<=11;class qts{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 Vts{constructor(t,r){this.view=t,this.handleDOMChange=r,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new qts,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(n=>{for(let a=0;aa.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():Ip&&t.composing&&n.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Uts&&(this.onCharData=n=>{this.queue.push({target:n.target,type:"characterData",oldValue:n.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,$ts)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.length){for(let r=0;rthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(oBe(this.view)){if(this.suppressingSelectionUpdates)return p2(this.view);if(bg&&bS<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&SA(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let r=new Set,n;for(let i=t.focusNode;i;i=gL(i))r.add(i);for(let i=t.anchorNode;i;i=gL(i))if(r.has(i)){n=i;break}let a=n&&this.view.docView.nearestDesc(n);if(a&&a.ignoreMutation({type:"selection",target:n.nodeType==3?n.parentNode:n}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let r=this.pendingRecords();r.length&&(this.queue=[]);let n=t.domSelectionRange(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(n)&&oBe(t)&&!this.ignoreSelectionChange(n),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 m=u.nextSibling;for(;m&&m.nodeType==1;){if(m.contentEditable=="false"){u.parentNode.removeChild(u);break}m=m.firstChild}}}else if(nv&&c.length){let u=c.filter(m=>m.nodeName=="BR");if(u.length==2){let[m,f]=u;m.parentNode&&m.parentNode.parentNode==f.parentNode?f.remove():m.remove()}else{let{focusNode:m}=this.currentSelection;for(let f of u){let x=f.parentNode;x&&x.nodeName=="LI"&&(!m||Wts(t,m)!=x)&&f.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),Hts(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,Kts(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(n)||p2(t),this.currentSelection.set(n))}registerMutation(t,r){if(r.indexOf(t.target)>-1)return null;let n=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(n==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!n||n.ignoreMutation(t))return null;if(t.type=="childList"){for(let u=0;ua;b--){let j=n.childNodes[b-1],N=j.pmViewDesc;if(j.nodeName=="BR"&&!N){i=b;break}if(!N||N.size)break}let m=s.state.doc,f=s.someProp("domParser")||w7.fromSchema(s.state.schema),x=m.resolve(l),y=null,_=f.parse(n,{topNode:x.parent,topMatch:x.parent.contentMatchAt(x.index()),topOpen:!0,from:a,to:i,preserveWhitespace:x.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:Zts,context:x});if(d&&d[0].pos!=null){let b=d[0].pos,j=d[1]&&d[1].pos;j==null&&(j=b),y={anchor:b+l,head:j+l}}return{doc:_,sel:y,from:l,to:o}}function Zts(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(Ip&&/^(ul|ol)$/i.test(s.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(s.parentNode.lastChild==s||Ip&&/^(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 Xts=/^(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 Qts(s,t,r,n,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let R=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,F=IEe(s,R);if(F&&!s.state.selection.eq(F)){if(Vf&&Kj&&s.input.lastKeyCode===13&&Date.now()-100B(s,UT(13,"Enter"))))return;let O=s.state.tr.setSelection(F);R=="pointer"?O.setMeta("pointer",!0):R=="key"&&O.scrollIntoView(),i&&O.setMeta("composition",i),s.dispatch(O)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(r);t=l.before(o+1),r=s.state.doc.resolve(r).after(o+1);let c=s.state.selection,d=Yts(s,t,r),u=s.state.doc,m=u.slice(d.from,d.to),f,x;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Kj)&&a.some(R=>R.nodeType==1&&!Xts.test(R.nodeName))&&(!y||y.endA>=y.endB)&&s.someProp("handleKeyDown",R=>R(s,UT(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!y)if(n&&c instanceof Oi&&!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 R=vBe(s,s.state.doc,d.sel);if(R&&!R.eq(s.state.selection)){let F=s.state.tr.setSelection(R);i&&F.setMeta("composition",i),s.dispatch(F)}}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)),bg&&bS<=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),b=d.doc.resolveNoCache(y.endB-d.from),j=u.resolve(y.start),N=_.sameParent(b)&&_.parent.inlineContent&&j.end()>=y.endA;if((yL&&s.input.lastIOSEnter>Date.now()-225&&(!N||a.some(R=>R.nodeName=="DIV"||R.nodeName=="P"))||!N&&_.posR(s,UT(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>y.start&&ess(u,y.start,y.endA,_,b)&&s.someProp("handleKeyDown",R=>R(s,UT(8,"Backspace")))){Kj&&Vf&&s.domObserver.suppressSelectionUpdates();return}Vf&&y.endB==y.start&&(s.input.lastChromeDelete=Date.now()),Kj&&!N&&_.start()!=b.start()&&b.parentOffset==0&&_.depth==b.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==y.endA&&(y.endB-=2,b=d.doc.resolveNoCache(y.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(R){return R(s,UT(13,"Enter"))})},20));let C=y.start,A=y.endA,E=R=>{let F=R||s.state.tr.replace(C,A,d.doc.slice(y.start-d.from,y.endB-d.from));if(d.sel){let O=vBe(s,F.doc,d.sel);O&&!(Vf&&s.composing&&O.empty&&(y.start!=y.endB||s.input.lastChromeDeletep2(s),20));let R=E(s.state.tr.delete(C,A)),F=u.resolve(y.start).marksAcross(u.resolve(y.endA));F&&R.ensureMarks(F),s.dispatch(R)}else if(y.endA==y.endB&&(D=Jts(_.parent.content.cut(_.parentOffset,b.parentOffset),j.parent.content.cut(j.parentOffset,y.endA-j.start())))){let R=E(s.state.tr);D.type=="add"?R.addMark(C,A,D.mark):R.removeMark(C,A,D.mark),s.dispatch(R)}else if(_.parent.child(_.index()).isText&&_.index()==b.index()-(b.textOffset?0:1)){let R=_.parent.textBetween(_.parentOffset,b.parentOffset),F=()=>E(s.state.tr.insertText(R,C,A));s.someProp("handleTextInput",O=>O(s,C,A,R,F))||s.dispatch(F())}else s.dispatch(E());else s.dispatch(E())}function vBe(s,t,r){return Math.max(r.anchor,r.head)>t.content.size?null:PEe(s,t.resolve(r.anchor),t.resolve(r.head))}function Jts(s,t){let r=s.firstChild.marks,n=t.firstChild.marks,a=r,i=n,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;ur||D_e(l,!0,!1)0&&(t||s.indexAfter(n)==s.node(n).childCount);)n--,a++,t=!1;if(r){let i=s.node(n).maybeChild(s.indexAfter(n));for(;i&&!i.isLeaf;)i=i.firstChild,a++}return a}function tss(s,t,r,n,a){let i=s.findDiffStart(t,r);if(i==null)return null;let{a:l,b:o}=s.findDiffEnd(t,r+s.size,r+t.size);if(a=="end"){let c=Math.max(0,i-Math.min(l,o));n-=l+c-i}if(l=l?i-n:0;i-=c,i&&i=o?i-n:0;i-=c,i&&i=56320&&t<=57343&&r>=55296&&r<=56319}class Eut{constructor(t,r){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new gts,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=r,this.state=r.state,this.directPlugins=r.plugins||[],this.directPlugins.forEach(kBe),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=jBe(this),wBe(this),this.nodeViews=NBe(this),this.docView=tBe(this.state.doc,_Be(this),L_e(this),this.dom,this),this.domObserver=new Vts(this,(n,a,i,l)=>Qts(this,n,a,i,l)),this.domObserver.start(),yts(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let r in t)this._props[r]=t[r];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&Xke(this);let r=this._props;this._props=t,t.plugins&&(t.plugins.forEach(kBe),this.directPlugins=t.plugins),this.updateStateInner(t.state,r)}setProps(t){let r={};for(let n in this._props)r[n]=this._props[n];r.state=this.state;for(let n in t)r[n]=t[n];this.update(r)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,r){var n;let a=this.state,i=!1,l=!1;t.storedMarks&&this.composing&&(wut(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=r.plugins;if(o||this._props.plugins!=r.plugins||this._props.nodeViews!=r.nodeViews){let x=NBe(this);rss(x,this.nodeViews)&&(this.nodeViews=x,i=!0)}(o||r.handleDOMEvents!=this._props.handleDOMEvents)&&Xke(this),this.editable=jBe(this),wBe(this);let c=L_e(this),d=_Be(this),u=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",m=i||!this.docView.matchesNode(t.doc,d,c);(m||!t.selection.eq(a.selection))&&(l=!0);let f=u=="preserve"&&l&&this.dom.style.overflowAnchor==null&&Ies(this);if(l){this.domObserver.stop();let x=m&&(bg||Vf)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&sss(a.selection,t.selection);if(m){let y=Vf?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Its(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=tBe(t.doc,d,c,this.dom,this)),y&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(x=!0)}x||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&sts(this))?p2(this,x):(dut(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((n=this.dragging)===null||n===void 0)&&n.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():f&&Pes(f)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",r=>r(this)))if(this.state.selection instanceof Ei){let r=this.docView.domAfterPos(this.state.selection.from);r.nodeType==1&&Yze(this,r.getBoundingClientRect(),t)}else Yze(this,this.coordsAtPos(this.state.selection.head,1),t)}}destroyPluginViews(){let t;for(;t=this.pluginViews.pop();)t.destroy&&t.destroy()}updatePluginViews(t){if(!t||t.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let r=0;r0&&ir.ownerDocument.getSelection()),this._root=r}return t||document}updateRoot(){this._root=null}posAtCoords(t){return zes(this,t)}coordsAtPos(t,r=1){return sut(this,t,r)}domAtPos(t,r=0){return this.docView.domFromPos(t,r)}nodeDOM(t){let r=this.docView.descAt(t);return r?r.nodeDOM:null}posAtDOM(t,r,n=-1){let a=this.docView.posFromDOM(t,r,n);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(t,r){return Ves(this,r||this.state,t)}pasteHTML(t,r){return $9(this,"",t,!1,r||new ClipboardEvent("paste"))}pasteText(t,r){return $9(this,t,null,!0,r||new ClipboardEvent("paste"))}serializeForClipboard(t){return LEe(this,t)}destroy(){this.docView&&(vts(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],L_e(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,wes())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return _ts(this,t)}domSelectionRange(){let t=this.domSelection();return t?Ip&&this.root.nodeType===11&&Ces(this.dom.ownerDocument)==this.dom&&Gts(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Eut.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function _Be(s){let t=Object.create(null);return t.class="ProseMirror",t.contenteditable=String(s.editable),s.someProp("attributes",r=>{if(typeof r=="function"&&(r=r(s.state)),r)for(let n in r)n=="class"?t.class+=" "+r[n]:n=="style"?t.style=(t.style?t.style+";":"")+r[n]:!t[n]&&n!="contenteditable"&&n!="nodeName"&&(t[n]=String(r[n]))}),t.translate||(t.translate="no"),[jx.node(0,s.state.doc.content.size,t)]}function wBe(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:jx.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function jBe(s){return!s.someProp("editable",t=>t(s.state)===!1)}function sss(s,t){let r=Math.min(s.$anchor.sharedDepth(s.head),t.$anchor.sharedDepth(t.head));return s.$anchor.start(r)!=t.$anchor.start(r)}function NBe(s){let t=Object.create(null);function r(n){for(let a in n)Object.prototype.hasOwnProperty.call(t,a)||(t[a]=n[a])}return s.someProp("nodeViews",r),s.someProp("markViews",r),t}function rss(s,t){let r=0,n=0;for(let a in s){if(s[a]!=t[a])return!0;r++}for(let a in t)n++;return r!=n}function kBe(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 FS={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:"'"},qme={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},nss=typeof navigator<"u"&&/Mac/.test(navigator.platform),ass=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Bf=0;Bf<10;Bf++)FS[48+Bf]=FS[96+Bf]=String(Bf);for(var Bf=1;Bf<=24;Bf++)FS[Bf+111]="F"+Bf;for(var Bf=65;Bf<=90;Bf++)FS[Bf]=String.fromCharCode(Bf+32),qme[Bf]=String.fromCharCode(Bf);for(var R_e in FS)qme.hasOwnProperty(R_e)||(qme[R_e]=FS[R_e]);function iss(s){var t=nss&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||ass&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",r=!t&&s.key||(s.shiftKey?qme:FS)[s.keyCode]||s.key||"Unidentified";return r=="Esc"&&(r="Escape"),r=="Del"&&(r="Delete"),r=="Left"&&(r="ArrowLeft"),r=="Up"&&(r="ArrowUp"),r=="Right"&&(r="ArrowRight"),r=="Down"&&(r="ArrowDown"),r}const oss=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),lss=typeof navigator<"u"&&/Win/.test(navigator.platform);function css(s){let t=s.split(/-(?!$)/),r=t[t.length-1];r=="Space"&&(r=" ");let n,a,i,l;for(let o=0;os.selection.empty?!1:(t&&t(s.tr.deleteSelection().scrollIntoView()),!0);function Aut(s,t){let{$cursor:r}=s.selection;return!r||(t?!t.endOfTextblock("backward",s):r.parentOffset>0)?null:r}const mss=(s,t,r)=>{let n=Aut(s,r);if(!n)return!1;let a=$Ee(n);if(!a){let l=n.blockRange(),o=l&&P8(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(Lut(s,a,t,-1))return!0;if(n.parent.content.size==0&&(vL(i,"end")||Ei.isSelectable(i)))for(let l=n.depth;;l--){let o=Uge(s.doc,n.before(l),n.after(l),pa.empty);if(o&&o.slice.size1)break}return i.isAtom&&a.depth==n.depth-1?(t&&t(s.tr.delete(a.pos-i.nodeSize,a.pos).scrollIntoView()),!0):!1},fss=(s,t,r)=>{let n=Aut(s,r);if(!n)return!1;let a=$Ee(n);return a?Mut(s,a,t):!1},pss=(s,t,r)=>{let n=Iut(s,r);if(!n)return!1;let a=UEe(n);return a?Mut(s,a,t):!1};function Mut(s,t,r){let n=t.nodeBefore,a=n,i=t.pos-1;for(;!a.isTextblock;i--){if(a.type.spec.isolating)return!1;let 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=Uge(s.doc,i,c,pa.empty);if(!d||d.from!=i||d instanceof Mh&&d.slice.size>=c-i)return!1;if(r){let u=s.tr.step(d);u.setSelection(Oi.create(u.doc,i)),r(u.scrollIntoView())}return!0}function vL(s,t,r=!1){for(let n=s;n;n=t=="start"?n.firstChild:n.lastChild){if(n.isTextblock)return!0;if(r&&n.childCount!=1)return!1}return!1}const xss=(s,t,r)=>{let{$head:n,empty:a}=s.selection,i=n;if(!a)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("backward",s):n.parentOffset>0)return!1;i=$Ee(n)}let l=i&&i.nodeBefore;return!l||!Ei.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Ei.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function $Ee(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 Iut(s,t){let{$cursor:r}=s.selection;return!r||(t?!t.endOfTextblock("forward",s):r.parentOffset{let n=Iut(s,r);if(!n)return!1;let a=UEe(n);if(!a)return!1;let i=a.nodeAfter;if(Lut(s,a,t,1))return!0;if(n.parent.content.size==0&&(vL(i,"start")||Ei.isSelectable(i))){let l=Uge(s.doc,n.before(),n.after(),pa.empty);if(l&&l.slice.size{let{$head:n,empty:a}=s.selection,i=n;if(!a)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("forward",s):n.parentOffset=0;t--){let r=s.node(t);if(s.index(t)+1{let r=s.selection,n=r instanceof Ei,a;if(n){if(r.node.isTextblock||!n4(s.doc,r.from))return!1;a=r.from}else if(a=$ge(s.doc,r.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);n&&i.setSelection(Ei.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},bss=(s,t)=>{let r=s.selection,n;if(r instanceof Ei){if(r.node.isTextblock||!n4(s.doc,r.to))return!1;n=r.to}else if(n=$ge(s.doc,r.to,1),n==null)return!1;return t&&t(s.tr.join(n).scrollIntoView()),!0},_ss=(s,t)=>{let{$from:r,$to:n}=s.selection,a=r.blockRange(n),i=a&&P8(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},wss=(s,t)=>{let{$head:r,$anchor:n}=s.selection;return!r.parent.type.spec.code||!r.sameParent(n)?!1:(t&&t(s.tr.insertText(` `).scrollIntoView()),!0)};function Put(s){for(let t=0;t{let{$head:r,$anchor:n}=s.selection;if(!r.parent.type.spec.code||!r.sameParent(n))return!1;let a=r.node(-1),i=r.indexAfter(-1),l=Put(a.contentMatchAt(i));if(!l||!a.canReplaceWith(i,i,l))return!1;if(t){let o=r.after(),c=s.tr.replaceWith(o,o,l.createAndFill());c.setSelection(Qi.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},Nss=(s,t)=>{let r=s.selection,{$from:n,$to:a}=r;if(r instanceof rv||n.parent.inlineContent||a.parent.inlineContent)return!1;let i=Put(a.parent.contentMatchAt(a.indexAfter()));if(!i||!i.isTextblock)return!1;if(t){let l=(!n.parentOffset&&a.index(){let{$cursor:r}=s.selection;if(!r||r.parent.content.size)return!1;if(r.depth>1&&r.after()!=r.end(-1)){let i=r.before();if(jP(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let n=r.blockRange(),a=n&&P8(n);return a==null?!1:(t&&t(s.tr.lift(n,a).scrollIntoView()),!0)},Sss=(s,t)=>{let{$from:r,to:n}=s.selection,a,i=r.sharedDepth(n);return i==0?!1:(a=r.before(i),t&&t(s.tr.setSelection(Ei.create(s.doc,a))),!0)};function Css(s,t,r){let n=t.nodeBefore,a=t.nodeAfter,i=t.index();return!n||!a||!n.type.compatibleContent(a.type)?!1:!n.content.size&&t.parent.canReplace(i-1,i)?(r&&r(s.tr.delete(t.pos-n.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(i,i+1)||!(a.isTextblock||n4(s.doc,t.pos))?!1:(r&&r(s.tr.join(t.pos).scrollIntoView()),!0)}function Lut(s,t,r,n){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&Css(s,t,r))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(r){let x=t.pos+i.nodeSize,y=Rn.empty;for(let j=l.length-1;j>=0;j--)y=Rn.from(l[j].create(null,y));y=Rn.from(a.copy(y));let _=s.tr.step(new lf(t.pos-1,x,t.pos,x,new pa(y,1,0),l.length,!0)),b=_.doc.resolve(x+2*l.length);b.nodeAfter&&b.nodeAfter.type==a.type&&n4(_.doc,b.pos)&&_.join(b.pos),r(_.scrollIntoView())}return!0}let u=i.type.spec.isolating||n>0&&c?null:Qi.findFrom(t,1),m=u&&u.$from.blockRange(u.$to),f=m&&P8(m);if(f!=null&&f>=t.depth)return r&&r(s.tr.lift(m,f).scrollIntoView()),!0;if(d&&vL(i,"start",!0)&&vL(a,"end")){let x=a,y=[];for(;y.push(x),!x.isTextblock;)x=x.lastChild;let _=i,b=1;for(;!_.isTextblock;_=_.firstChild)b++;if(x.canReplace(x.childCount,x.childCount,_.content)){if(r){let j=Rn.empty;for(let C=y.length-1;C>=0;C--)j=Rn.from(y[C].copy(j));let N=s.tr.step(new lf(t.pos-y.length,t.pos+i.nodeSize,t.pos+b,t.pos+i.nodeSize-b,new pa(j,y.length,0),0,!0));r(N.scrollIntoView())}return!0}}return!1}function Dut(s){return function(t,r){let n=t.selection,a=s<0?n.$from:n.$to,i=a.depth;for(;a.node(i).isInline;){if(!i)return!1;i--}return a.node(i).isTextblock?(r&&r(t.tr.setSelection(Oi.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const Tss=Dut(-1),Ess=Dut(1);function Ass(s,t=null){return function(r,n){let{$from:a,$to:i}=r.selection,l=a.blockRange(i),o=l&&TEe(l,s,t);return o?(n&&n(r.tr.wrap(l,o).scrollIntoView()),!0):!1}}function SBe(s,t=null){return function(r,n){let a=!1;for(let i=0;i{if(a)return!1;if(!(!c.isTextblock||c.hasMarkup(s,t)))if(c.type==s)a=!0;else{let u=r.doc.resolve(d),m=u.index();a=u.parent.canReplaceWith(m,m+1,s)}})}if(!a)return!1;if(n){let i=r.tr;for(let l=0;l=2&&t.$from.node(t.depth-1).type.compatibleContent(r)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let c=l.resolve(t.start-2);i=new Rme(c,c,t.depth),t.endIndex=0;u--)i=Rn.from(r[u].type.create(r[u].attrs,i));s.step(new lf(t.start-(n?2:0),t.end,t.start,t.end,new pa(i,0,0),r.length,!0));let l=0;for(let u=0;ul.childCount>0&&l.firstChild.type==s);return i?r?n.node(i.depth-1).type==s?Dss(t,r,s,i):Rss(t,r,i):!0:!1}}function Dss(s,t,r,n){let a=s.tr,i=n.end,l=n.$to.end(n.depth);i_;y--)x-=a.child(y).nodeSize,n.delete(x-1,x+1);let i=n.doc.resolve(r.start),l=i.nodeAfter;if(n.mapping.map(r.end)!=r.start+i.nodeAfter.nodeSize)return!1;let o=r.startIndex==0,c=r.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?Rn.empty:Rn.from(a))))return!1;let m=i.pos,f=m+l.nodeSize;return n.step(new lf(m-(o?1:0),f+(c?1:0),m+1,f-1,new pa((o?Rn.empty:Rn.from(a.copy(Rn.empty))).append(c?Rn.empty:Rn.from(a.copy(Rn.empty))),o?0:1,c?0:1),o?0:1)),t(n.scrollIntoView()),!0}function Oss(s){return function(t,r){let{$from:n,$to:a}=t.selection,i=n.blockRange(a,d=>d.childCount>0&&d.firstChild.type==s);if(!i)return!1;let l=i.startIndex;if(l==0)return!1;let o=i.parent,c=o.child(l-1);if(c.type!=s)return!1;if(r){let d=c.lastChild&&c.lastChild.type==o.type,u=Rn.from(d?s.create():null),m=new pa(Rn.from(s.create(null,Rn.from(o.type.create(null,u)))),d?3:1,0),f=i.start,x=i.end;r(t.tr.step(new lf(f-(d?3:1),x,f,x,m,1,!0)).scrollIntoView())}return!0}}function Wge(s){const{state:t,transaction:r}=s;let{selection:n}=r,{doc:a}=r,{storedMarks:i}=r;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return i},get selection(){return n},get doc(){return a},get tr(){return n=r.selection,a=r.doc,i=r.storedMarks,r}}}class Kge{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:r,state:n}=this,{view:a}=r,{tr:i}=n,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const m=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),m}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,r=!0){const{rawCommands:n,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&r&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(f=>f===!0)),m={...Object.fromEntries(Object.entries(n).map(([f,x])=>[f,(..._)=>{const b=this.buildProps(d,r),j=x(..._)(b);return o.push(j),m}])),run:u};return m}createCan(t){const{rawCommands:r,state:n}=this,a=!1,i=t||n.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...u)=>d(...u)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,r=!0){const{rawCommands:n,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:Wge({state:i,transaction:t}),dispatch:r?()=>{}:void 0,chain:()=>this.createChain(t,r),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...u)=>d(...u)(o)]))}};return o}}let Fss=class{constructor(){this.callbacks={}}on(t,r){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(r),this}emit(t,...r){const n=this.callbacks[t];return n&&n.forEach(a=>a.apply(this,r)),this}off(t,r){const n=this.callbacks[t];return n&&(r?this.callbacks[t]=n.filter(a=>a!==r):delete this.callbacks[t]),this}once(t,r){const n=(...a)=>{this.off(t,n),r.apply(this,a)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}};function ii(s,t,r){return s.config[t]===void 0&&s.parent?ii(s.parent,t,r):typeof s.config[t]=="function"?s.config[t].bind({...r,parent:s.parent?ii(s.parent,t,r):null}):s.config[t]}function Yge(s){const t=s.filter(a=>a.type==="extension"),r=s.filter(a=>a.type==="node"),n=s.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:r,markExtensions:n}}function Rut(s){const t=[],{nodeExtensions:r,markExtensions:n}=Yge(s),a=[...r,...n],i={default:null,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return s.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage,extensions:a},c=ii(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(m=>{Object.entries(u.attributes).forEach(([f,x])=>{t.push({type:m,name:f,attribute:{...i,...x}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=ii(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([u,m])=>{const f={...i,...m};typeof(f==null?void 0:f.default)=="function"&&(f.default=f.default()),f!=null&&f.isRequired&&(f==null?void 0:f.default)===void 0&&delete f.default,t.push({type:l.name,name:u,attribute:f})})}),t}function uf(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 Yd(...s){return s.filter(t=>!!t).reduce((t,r)=>{const n={...t};return Object.entries(r).forEach(([a,i])=>{if(!n[a]){n[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=n[a]?n[a].split(" "):[],d=o.filter(u=>!c.includes(u));n[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(u=>u.trim()).filter(Boolean):[],c=n[a]?n[a].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[m,f]=u.split(":").map(x=>x.trim());d.set(m,f)}),o.forEach(u=>{const[m,f]=u.split(":").map(x=>x.trim());d.set(m,f)}),n[a]=Array.from(d.entries()).map(([u,m])=>`${u}: ${m}`).join("; ")}else n[a]=i}),n},{})}function Qke(s,t){return t.filter(r=>r.type===s.type.name).filter(r=>r.attribute.rendered).map(r=>r.attribute.renderHTML?r.attribute.renderHTML(s.attrs)||{}:{[r.name]:s.attrs[r.name]}).reduce((r,n)=>Yd(r,n),{})}function Out(s){return typeof s=="function"}function Ro(s,t=void 0,...r){return Out(s)?t?s.bind(t)(...r):s(...r):s}function zss(s={}){return Object.keys(s).length===0&&s.constructor===Object}function Bss(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function CBe(s,t){return"style"in s?s:{...s,getAttrs:r=>{const n=s.getAttrs?s.getAttrs(r):s.attrs;if(n===!1)return!1;const a=t.reduce((i,l)=>{const o=l.attribute.parseHTML?l.attribute.parseHTML(r):Bss(r.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...n,...a}}}}function TBe(s){return Object.fromEntries(Object.entries(s).filter(([t,r])=>t==="attrs"&&zss(r)?!1:r!=null))}function $ss(s,t){var r;const n=Rut(s),{nodeExtensions:a,markExtensions:i}=Yge(s),l=(r=a.find(d=>ii(d,"topNode")))===null||r===void 0?void 0:r.name,o=Object.fromEntries(a.map(d=>{const u=n.filter(j=>j.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:t},f=s.reduce((j,N)=>{const C=ii(N,"extendNodeSchema",m);return{...j,...C?C(d):{}}},{}),x=TBe({...f,content:Ro(ii(d,"content",m)),marks:Ro(ii(d,"marks",m)),group:Ro(ii(d,"group",m)),inline:Ro(ii(d,"inline",m)),atom:Ro(ii(d,"atom",m)),selectable:Ro(ii(d,"selectable",m)),draggable:Ro(ii(d,"draggable",m)),code:Ro(ii(d,"code",m)),whitespace:Ro(ii(d,"whitespace",m)),linebreakReplacement:Ro(ii(d,"linebreakReplacement",m)),defining:Ro(ii(d,"defining",m)),isolating:Ro(ii(d,"isolating",m)),attrs:Object.fromEntries(u.map(j=>{var N;return[j.name,{default:(N=j==null?void 0:j.attribute)===null||N===void 0?void 0:N.default}]}))}),y=Ro(ii(d,"parseHTML",m));y&&(x.parseDOM=y.map(j=>CBe(j,u)));const _=ii(d,"renderHTML",m);_&&(x.toDOM=j=>_({node:j,HTMLAttributes:Qke(j,u)}));const b=ii(d,"renderText",m);return b&&(x.toText=b),[d.name,x]})),c=Object.fromEntries(i.map(d=>{const u=n.filter(b=>b.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:t},f=s.reduce((b,j)=>{const N=ii(j,"extendMarkSchema",m);return{...b,...N?N(d):{}}},{}),x=TBe({...f,inclusive:Ro(ii(d,"inclusive",m)),excludes:Ro(ii(d,"excludes",m)),group:Ro(ii(d,"group",m)),spanning:Ro(ii(d,"spanning",m)),code:Ro(ii(d,"code",m)),attrs:Object.fromEntries(u.map(b=>{var j;return[b.name,{default:(j=b==null?void 0:b.attribute)===null||j===void 0?void 0:j.default}]}))}),y=Ro(ii(d,"parseHTML",m));y&&(x.parseDOM=y.map(b=>CBe(b,u)));const _=ii(d,"renderHTML",m);return _&&(x.toDOM=b=>_({mark:b,HTMLAttributes:Qke(b,u)})),[d.name,x]}));return new Adt({topNode:l,nodes:o,marks:c})}function F_e(s,t){return t.nodes[s]||t.marks[s]||null}function EBe(s,t){return Array.isArray(t)?t.some(r=>(typeof r=="string"?r:r.name)===s.name):t}function qEe(s,t){const r=QA.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(r),a.innerHTML}const Uss=(s,t=500)=>{let r="";const n=s.parentOffset;return s.parent.nodesBetween(Math.max(0,n-t),n,(a,i,l,o)=>{var c,d;const 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%";r+=a.isAtom&&!a.isText?u:u.slice(0,Math.max(0,n-i))}),r};function VEe(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class Zge{constructor(t){this.find=t.find,this.handler=t.handler}}const qss=(s,t)=>{if(VEe(t))return t.exec(s);const r=t(s);if(!r)return null;const n=[r.text];return n.index=r.index,n.input=s,n.data=r.data,r.replaceWith&&(r.text.includes(r.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),n.push(r.replaceWith)),n};function Sq(s){var t;const{editor:r,from:n,to:a,text:i,rules:l,plugin:o}=s,{view:c}=r;if(c.composing)return!1;const d=c.state.doc.resolve(n);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(f=>f.type.spec.code))return!1;let u=!1;const m=Uss(d)+i;return l.forEach(f=>{if(u)return;const x=qss(m,f.find);if(!x)return;const y=c.state.tr,_=Wge({state:c.state,transaction:y}),b={from:n-(x[0].length-i.length),to:a},{commands:j,chain:N,can:C}=new Kge({editor:r,state:_});f.handler({state:_,range:b,match:x,commands:j,chain:N,can:C})===null||!y.steps.length||(y.setMeta(o,{transform:y,from:n,to:a,text:i}),c.dispatch(y),u=!0)}),u}function Vss(s){const{editor:t,rules:r}=s,n=new Tm({state:{init(){return null},apply(a,i,l){const o=a.getMeta(n);if(o)return o;const c=a.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=qEe(Rn.from(u),l.schema);const{from:m}=c,f=m+u.length;Sq({editor:t,from:m,to:f,text:u,rules:r,plugin:n})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return Sq({editor:t,from:i,to:l,text:o,rules:r,plugin:n})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&Sq({editor:t,from:i.pos,to:i.pos,text:"",rules:r,plugin:n})}),!1)},handleKeyDown(a,i){if(i.key!=="Enter")return!1;const{$cursor:l}=a.state.selection;return l?Sq({editor:t,from:l.pos,to:l.pos,text:` `,rules:r,plugin:n}):!1}},isInputRules:!0});return n}function Hss(s){return Object.prototype.toString.call(s).slice(8,-1)}function Cq(s){return Hss(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function Xge(s,t){const r={...s};return Cq(s)&&Cq(t)&&Object.keys(t).forEach(n=>{Cq(t[n])&&Cq(s[n])?r[n]=Xge(s[n],t[n]):r[n]=t[n]}),r}class F1{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=Ro(ii(this,"addOptions",{name:this.name}))),this.storage=Ro(ii(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new F1(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>Xge(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new F1(t);return r.parent=this,this.child=r,r.name=t.name?t.name:r.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Ro(ii(r,"addOptions",{name:r.name})),r.storage=Ro(ii(r,"addStorage",{name:r.name,options:r.options})),r}static handleExit({editor:t,mark:r}){const{tr:n}=t.state,a=t.state.selection.$from;if(a.pos===a.end()){const l=a.marks();if(!!!l.find(d=>(d==null?void 0:d.type.name)===r.name))return!1;const c=l.find(d=>(d==null?void 0:d.type.name)===r.name);return c&&n.removeStoredMark(c),n.insertText(" ",a.pos),t.view.dispatch(n),!0}return!1}}function Gss(s){return typeof s=="number"}class Wss{constructor(t){this.find=t.find,this.handler=t.handler}}const Kss=(s,t,r)=>{if(VEe(t))return[...s.matchAll(t)];const n=t(s,r);return n?n.map(a=>{const i=[a.text];return i.index=a.index,i.input=s,i.data=a.data,a.replaceWith&&(a.text.includes(a.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),i.push(a.replaceWith)),i}):[]};function Yss(s){const{editor:t,state:r,from:n,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new Kge({editor:t,state:r}),m=[];return r.doc.nodesBetween(n,a,(x,y)=>{if(!x.isTextblock||x.type.spec.code)return;const _=Math.max(n,y),b=Math.min(a,y+x.content.size),j=x.textBetween(_-y,b-y,void 0,"");Kss(j,i.find,l).forEach(C=>{if(C.index===void 0)return;const A=_+C.index+1,E=A+C[0].length,D={from:r.tr.mapping.map(A),to:r.tr.mapping.map(E)},R=i.handler({state:r,range:D,match:C,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});m.push(R)})}),m.every(x=>x!==null)}let Tq=null;const Zss=s=>{var t;const r=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(t=r.clipboardData)===null||t===void 0||t.setData("text/html",s),r};function Xss(s){const{editor:t,rules:r}=s;let n=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:m,to:f,rule:x,pasteEvt:y})=>{const _=u.tr,b=Wge({state:u,transaction:_});if(!(!Yss({editor:t,state:b,from:Math.max(m-1,0),to:f.b-1,rule:x,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 r.map(u=>new Tm({view(m){const f=y=>{var _;n=!((_=m.dom.parentElement)===null||_===void 0)&&_.contains(y.target)?m.dom.parentElement:null,n&&(Tq=t)},x=()=>{Tq&&(Tq=null)};return window.addEventListener("dragstart",f),window.addEventListener("dragend",x),{destroy(){window.removeEventListener("dragstart",f),window.removeEventListener("dragend",x)}}},props:{handleDOMEvents:{drop:(m,f)=>{if(i=n===m.dom.parentElement,o=f,!i){const x=Tq;x!=null&&x.isEditable&&setTimeout(()=>{const y=x.state.selection;y&&x.commands.deleteRange({from:y.from,to:y.to})},10)}return!1},paste:(m,f)=>{var x;const y=(x=f.clipboardData)===null||x===void 0?void 0:x.getData("text/html");return l=f,a=!!(y!=null&&y.includes("data-pm-slice")),!1}}},appendTransaction:(m,f,x)=>{const y=m[0],_=y.getMeta("uiEvent")==="paste"&&!a,b=y.getMeta("uiEvent")==="drop"&&!i,j=y.getMeta("applyPasteRules"),N=!!j;if(!_&&!b&&!N)return;if(N){let{text:E}=j;typeof E=="string"?E=E:E=qEe(Rn.from(E),x.schema);const{from:D}=j,R=D+E.length,F=Zss(E);return c({rule:u,state:x,from:D,to:{b:R},pasteEvt:F})}const C=f.doc.content.findDiffStart(x.doc.content),A=f.doc.content.findDiffEnd(x.doc.content);if(!(!Gss(C)||!A||C===A.b))return c({rule:u,state:x,from:C,to:A,pasteEvt:l})}}))}function Qss(s){const t=s.filter((r,n)=>s.indexOf(r)!==n);return Array.from(new Set(t))}class kI{constructor(t,r){this.splittableMarks=[],this.editor=r,this.extensions=kI.resolve(t),this.schema=$ss(this.extensions,r),this.setupExtensions()}static resolve(t){const r=kI.sort(kI.flatten(t)),n=Qss(r.map(a=>a.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(a=>`'${a}'`).join(", ")}]. This can lead to issues.`),r}static flatten(t){return t.map(r=>{const n={name:r.name,options:r.options,storage:r.storage},a=ii(r,"addExtensions",n);return a?[r,...this.flatten(a())]:r}).flat(10)}static sort(t){return t.sort((n,a)=>{const i=ii(n,"priority")||100,l=ii(a,"priority")||100;return i>l?-1:i{const n={name:r.name,options:r.options,storage:r.storage,editor:this.editor,type:F_e(r.name,this.schema)},a=ii(r,"addCommands",n);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,r=kI.sort([...this.extensions].reverse()),n=[],a=[],i=r.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:F_e(l.name,this.schema)},c=[],d=ii(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&ii(l,"exitable",o)&&(u.ArrowRight=()=>F1.handleExit({editor:t,mark:l})),d){const _=Object.fromEntries(Object.entries(d()).map(([b,j])=>[b,()=>j({editor:t})]));u={...u,..._}}const m=uss(u);c.push(m);const f=ii(l,"addInputRules",o);EBe(l,t.options.enableInputRules)&&f&&n.push(...f());const x=ii(l,"addPasteRules",o);EBe(l,t.options.enablePasteRules)&&x&&a.push(...x());const y=ii(l,"addProseMirrorPlugins",o);if(y){const _=y();c.push(..._)}return c}).flat();return[Vss({editor:t,rules:n}),...Xss({editor:t,rules:a}),...i]}get attributes(){return Rut(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:r}=Yge(this.extensions);return Object.fromEntries(r.filter(n=>!!ii(n,"addNodeView")).map(n=>{const a=this.attributes.filter(c=>c.type===n.name),i={name:n.name,options:n.options,storage:n.storage,editor:t,type:uf(n.name,this.schema)},l=ii(n,"addNodeView",i);if(!l)return[];const o=(c,d,u,m,f)=>{const x=Qke(c,a);return l()({node:c,view:d,getPos:u,decorations:m,innerDecorations:f,editor:t,extension:n,HTMLAttributes:x})};return[n.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var r;this.editor.extensionStorage[t.name]=t.storage;const n={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:F_e(t.name,this.schema)};t.type==="mark"&&(!((r=Ro(ii(t,"keepOnSplit",n)))!==null&&r!==void 0)||r)&&this.splittableMarks.push(t.name);const a=ii(t,"onBeforeCreate",n),i=ii(t,"onCreate",n),l=ii(t,"onUpdate",n),o=ii(t,"onSelectionUpdate",n),c=ii(t,"onTransaction",n),d=ii(t,"onFocus",n),u=ii(t,"onBlur",n),m=ii(t,"onDestroy",n);a&&this.editor.on("beforeCreate",a),i&&this.editor.on("create",i),l&&this.editor.on("update",l),o&&this.editor.on("selectionUpdate",o),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),u&&this.editor.on("blur",u),m&&this.editor.on("destroy",m)})}}class tp{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=Ro(ii(this,"addOptions",{name:this.name}))),this.storage=Ro(ii(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new tp(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>Xge(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new tp({...this.config,...t});return r.parent=this,this.child=r,r.name=t.name?t.name:r.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Ro(ii(r,"addOptions",{name:r.name})),r.storage=Ro(ii(r,"addStorage",{name:r.name,options:r.options})),r}}function Fut(s,t,r){const{from:n,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=r||{};let o="";return s.nodesBetween(n,a,(c,d,u,m)=>{var f;c.isBlock&&d>n&&(o+=i);const x=l==null?void 0:l[c.type.name];if(x)return u&&(o+=x({node:c,pos:d,parent:u,index:m,range:t})),!1;c.isText&&(o+=(f=c==null?void 0:c.text)===null||f===void 0?void 0:f.slice(Math.max(n,d)-d,a-d))}),o}function zut(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,r])=>[t,r.spec.toText]))}const Jss=tp.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Tm({key:new Rp("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:t,schema:r}=s,{doc:n,selection:a}=t,{ranges:i}=a,l=Math.min(...i.map(u=>u.$from.pos)),o=Math.max(...i.map(u=>u.$to.pos)),c=zut(r);return Fut(n,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),ers=()=>({editor:s,view:t})=>(requestAnimationFrame(()=>{var r;s.isDestroyed||(t.dom.blur(),(r=window==null?void 0:window.getSelection())===null||r===void 0||r.removeAllRanges())}),!0),trs=(s=!1)=>({commands:t})=>t.setContent("",s),srs=()=>({state:s,tr:t,dispatch:r})=>{const{selection:n}=t,{ranges:a}=n;return r&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,m=d.resolve(u.map(c)),f=d.resolve(u.map(c+o.nodeSize)),x=m.blockRange(f);if(!x)return;const y=P8(x);if(o.type.isTextblock){const{defaultType:_}=m.parent.contentMatchAt(m.index());t.setNodeMarkup(x.start,_)}(y||y===0)&&t.lift(x,y)})}),!0},rrs=s=>t=>s(t),nrs=()=>({state:s,dispatch:t})=>Nss(s,t),ars=(s,t)=>({editor:r,tr:n})=>{const{state:a}=r,i=a.doc.slice(s.from,s.to);n.deleteRange(s.from,s.to);const l=n.mapping.map(t);return n.insert(l,i.content),n.setSelection(new Oi(n.doc.resolve(Math.max(l-1,0)))),!0},irs=()=>({tr:s,dispatch:t})=>{const{selection:r}=s,n=r.$anchor.node();if(n.content.size>0)return!1;const a=s.selection.$anchor;for(let i=a.depth;i>0;i-=1)if(a.node(i).type===n.type){if(t){const o=a.before(i),c=a.after(i);s.delete(o,c).scrollIntoView()}return!0}return!1},ors=s=>({tr:t,state:r,dispatch:n})=>{const a=uf(s,r.schema),i=t.selection.$anchor;for(let l=i.depth;l>0;l-=1)if(i.node(l).type===a){if(n){const c=i.before(l),d=i.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},lrs=s=>({tr:t,dispatch:r})=>{const{from:n,to:a}=s;return r&&t.delete(n,a),!0},crs=()=>({state:s,dispatch:t})=>hss(s,t),drs=()=>({commands:s})=>s.keyboardShortcut("Enter"),urs=()=>({state:s,dispatch:t})=>jss(s,t);function Vme(s,t,r={strict:!0}){const n=Object.keys(t);return n.length?n.every(a=>r.strict?t[a]===s[a]:VEe(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function But(s,t,r={}){return s.find(n=>n.type===t&&Vme(Object.fromEntries(Object.keys(r).map(a=>[a,n.attrs[a]])),r))}function ABe(s,t,r={}){return!!But(s,t,r)}function HEe(s,t,r){var n;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)||(r=r||((n=a.node.marks[0])===null||n===void 0?void 0:n.attrs),!But([...a.node.marks],t,r)))return;let l=a.index,o=s.start()+a.offset,c=l+1,d=o+a.node.nodeSize;for(;l>0&&ABe([...s.parent.child(l-1).marks],t,r);)l-=1,o-=s.parent.child(l).nodeSize;for(;c({tr:r,state:n,dispatch:a})=>{const i=i4(s,n.schema),{doc:l,selection:o}=r,{$from:c,from:d,to:u}=o;if(a){const m=HEe(c,i,t);if(m&&m.from<=d&&m.to>=u){const f=Oi.create(l,m.from,m.to);r.setSelection(f)}}return!0},mrs=s=>t=>{const r=typeof s=="function"?s(t):s;for(let n=0;n({editor:r,view:n,tr:a,dispatch:i})=>{t={scrollIntoView:!0,...t};const l=()=>{(Hme()||MBe())&&n.dom.focus(),requestAnimationFrame(()=>{r.isDestroyed||(n.focus(),frs()&&!Hme()&&!MBe()&&n.dom.focus({preventScroll:!0}))})};if(n.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!$ut(r.state.selection))return l(),!0;const o=Uut(a.doc,s)||r.state.selection,c=r.state.selection.eq(o);return i&&(c||a.setSelection(o),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},xrs=(s,t)=>r=>s.every((n,a)=>t(n,{...r,index:a})),grs=(s,t)=>({tr:r,commands:n})=>n.insertContentAt({from:r.selection.from,to:r.selection.to},s,t),qut=s=>{const t=s.childNodes;for(let r=t.length-1;r>=0;r-=1){const n=t[r];n.nodeType===3&&n.nodeValue&&/^(\n\s\s|\n)$/.test(n.nodeValue)?s.removeChild(n):n.nodeType===1&&qut(n)}return s};function Eq(s){const t=`${s}`,r=new window.DOMParser().parseFromString(t,"text/html").body;return qut(r)}function q9(s,t,r){if(s instanceof vS||s instanceof Rn)return s;r={slice:!0,parseOptions:{},...r};const n=typeof s=="object"&&s!==null,a=typeof s=="string";if(n)try{if(Array.isArray(s)&&s.length>0)return Rn.fromArray(s.map(o=>t.nodeFromJSON(o)));const l=t.nodeFromJSON(s);return r.errorOnInvalidContent&&l.check(),l}catch(i){if(r.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",s,"Error:",i),q9("",t,r)}if(a){if(r.errorOnInvalidContent){let l=!1,o="";const c=new Adt({topNode:t.spec.topNode,marks:t.spec.marks,nodes:t.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:d=>(l=!0,o=typeof d=="string"?d:d.outerHTML,null)}]}})});if(r.slice?w7.fromSchema(c).parseSlice(Eq(s),r.parseOptions):w7.fromSchema(c).parse(Eq(s),r.parseOptions),r.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=w7.fromSchema(t);return r.slice?i.parseSlice(Eq(s),r.parseOptions).content:i.parse(Eq(s),r.parseOptions)}return q9("",t,r)}function yrs(s,t,r){const n=s.steps.length-1;if(n{l===0&&(l=u)}),s.setSelection(Qi.near(s.doc.resolve(l),r))}const vrs=s=>!("type"in s),brs=(s,t,r)=>({tr:n,dispatch:a,editor:i})=>{var l;if(a){r={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...r};let o;const c=b=>{i.emit("contentError",{editor:i,error:b,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...r.parseOptions};if(!r.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{q9(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(b){c(b)}try{o=q9(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=r.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(b){return c(b),!1}let{from:u,to:m}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},f=!0,x=!0;if((vrs(o)?o:[o]).forEach(b=>{b.check(),f=f?b.isText&&b.marks.length===0:!1,x=x?b.isBlock:!1}),u===m&&x){const{parent:b}=n.doc.resolve(u);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(u-=1,m+=1)}let _;if(f){if(Array.isArray(t))_=t.map(b=>b.text||"").join("");else if(t instanceof Rn){let b="";t.forEach(j=>{j.text&&(b+=j.text)}),_=b}else typeof t=="object"&&t&&t.text?_=t.text:_=t;n.insertText(_,u,m)}else _=o,n.replaceWith(u,m,_);r.updateSelection&&yrs(n,n.steps.length-1,-1),r.applyInputRules&&n.setMeta("applyInputRules",{from:u,text:_}),r.applyPasteRules&&n.setMeta("applyPasteRules",{from:u,text:_})}return!0},_rs=()=>({state:s,dispatch:t})=>vss(s,t),wrs=()=>({state:s,dispatch:t})=>bss(s,t),jrs=()=>({state:s,dispatch:t})=>mss(s,t),Nrs=()=>({state:s,dispatch:t})=>gss(s,t),krs=()=>({state:s,dispatch:t,tr:r})=>{try{const n=$ge(s.doc,s.selection.$from.pos,-1);return n==null?!1:(r.join(n,2),t&&t(r),!0)}catch{return!1}},Srs=()=>({state:s,dispatch:t,tr:r})=>{try{const n=$ge(s.doc,s.selection.$from.pos,1);return n==null?!1:(r.join(n,2),t&&t(r),!0)}catch{return!1}},Crs=()=>({state:s,dispatch:t})=>fss(s,t),Trs=()=>({state:s,dispatch:t})=>pss(s,t);function Vut(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Ers(s){const t=s.split(/-(?!$)/);let r=t[t.length-1];r==="Space"&&(r=" ");let n,a,i,l;for(let o=0;o({editor:t,view:r,tr:n,dispatch:a})=>{const i=Ers(s).split(/-(?!$)/),l=i.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),o=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{r.someProp("handleKeyDown",d=>d(r,o))});return c==null||c.steps.forEach(d=>{const u=d.map(n.mapping);u&&a&&n.maybeStep(u)}),!0};function V9(s,t,r={}){const{from:n,to:a,empty:i}=s.selection,l=t?uf(t,s.schema):null,o=[];s.doc.nodesBetween(n,a,(m,f)=>{if(m.isText)return;const x=Math.max(n,f),y=Math.min(a,f+m.nodeSize);o.push({node:m,from:x,to:y})});const c=a-n,d=o.filter(m=>l?l.name===m.node.type.name:!0).filter(m=>Vme(m.node.attrs,r,{strict:!1}));return i?!!d.length:d.reduce((m,f)=>m+f.to-f.from,0)>=c}const Mrs=(s,t={})=>({state:r,dispatch:n})=>{const a=uf(s,r.schema);return V9(r,a,t)?_ss(r,n):!1},Irs=()=>({state:s,dispatch:t})=>kss(s,t),Prs=s=>({state:t,dispatch:r})=>{const n=uf(s,t.schema);return Lss(n)(t,r)},Lrs=()=>({state:s,dispatch:t})=>wss(s,t);function Qge(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function IBe(s,t){const r=typeof t=="string"?[t]:t;return Object.keys(s).reduce((n,a)=>(r.includes(a)||(n[a]=s[a]),n),{})}const Drs=(s,t)=>({tr:r,state:n,dispatch:a})=>{let i=null,l=null;const o=Qge(typeof s=="string"?s:s.name,n.schema);return o?(o==="node"&&(i=uf(s,n.schema)),o==="mark"&&(l=i4(s,n.schema)),a&&r.selection.ranges.forEach(c=>{n.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,u)=>{i&&i===d.type&&r.setNodeMarkup(u,void 0,IBe(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(m=>{l===m.type&&r.addMark(u,u+d.nodeSize,l.create(IBe(m.attrs,t)))})})}),!0):!1},Rrs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),Ors=()=>({tr:s,dispatch:t})=>{if(t){const r=new rv(s.doc);s.setSelection(r)}return!0},Frs=()=>({state:s,dispatch:t})=>xss(s,t),zrs=()=>({state:s,dispatch:t})=>yss(s,t),Brs=()=>({state:s,dispatch:t})=>Sss(s,t),$rs=()=>({state:s,dispatch:t})=>Ess(s,t),Urs=()=>({state:s,dispatch:t})=>Tss(s,t);function Jke(s,t,r={},n={}){return q9(s,t,{slice:!1,parseOptions:r,errorOnInvalidContent:n.errorOnInvalidContent})}const qrs=(s,t=!1,r={},n={})=>({editor:a,tr:i,dispatch:l,commands:o})=>{var c,d;const{doc:u}=i;if(r.preserveWhitespace!=="full"){const m=Jke(s,a.schema,r,{errorOnInvalidContent:(c=n.errorOnInvalidContent)!==null&&c!==void 0?c:a.options.enableContentCheck});return l&&i.replaceWith(0,u.content.size,m).setMeta("preventUpdate",!t),!0}return l&&i.setMeta("preventUpdate",!t),o.insertContentAt({from:0,to:u.content.size},s,{parseOptions:r,errorOnInvalidContent:(d=n.errorOnInvalidContent)!==null&&d!==void 0?d:a.options.enableContentCheck})};function Hut(s,t){const r=i4(t,s.schema),{from:n,to:a,empty:i}=s.selection,l=[];i?(s.storedMarks&&l.push(...s.storedMarks),l.push(...s.selection.$head.marks())):s.doc.nodesBetween(n,a,c=>{l.push(...c.marks)});const o=l.find(c=>c.type.name===r.name);return o?{...o.attrs}:{}}function Vrs(s,t){const r=new EEe(s);return t.forEach(n=>{n.steps.forEach(a=>{r.step(a)})}),r}function Hrs(s){for(let t=0;t{r(a)&&n.push({node:a,pos:i})}),n}function Gut(s,t){for(let r=s.depth;r>0;r-=1){const n=s.node(r);if(t(n))return{pos:r>0?s.before(r):0,start:s.start(r),depth:r,node:n}}}function GEe(s){return t=>Gut(t.$from,s)}function Wrs(s,t){const r={from:0,to:s.content.size};return Fut(s,r,t)}function Krs(s,t){const r=uf(t,s.schema),{from:n,to:a}=s.selection,i=[];s.doc.nodesBetween(n,a,o=>{i.push(o)});const l=i.reverse().find(o=>o.type.name===r.name);return l?{...l.attrs}:{}}function Wut(s,t){const r=Qge(typeof t=="string"?t:t.name,s.schema);return r==="node"?Krs(s,t):r==="mark"?Hut(s,t):{}}function Yrs(s,t=JSON.stringify){const r={};return s.filter(n=>{const a=t(n);return Object.prototype.hasOwnProperty.call(r,a)?!1:r[a]=!0})}function Zrs(s){const t=Yrs(s);return t.length===1?t:t.filter((r,n)=>!t.filter((i,l)=>l!==n).some(i=>r.oldRange.from>=i.oldRange.from&&r.oldRange.to<=i.oldRange.to&&r.newRange.from>=i.newRange.from&&r.newRange.to<=i.newRange.to))}function Xrs(s){const{mapping:t,steps:r}=s,n=[];return t.maps.forEach((a,i)=>{const l=[];if(a.ranges.length)a.forEach((o,c)=>{l.push({from:o,to:c})});else{const{from:o,to:c}=r[i];if(o===void 0||c===void 0)return;l.push({from:o,to:c})}l.forEach(({from:o,to:c})=>{const d=t.slice(i).map(o,-1),u=t.slice(i).map(c),m=t.invert().map(d,-1),f=t.invert().map(u);n.push({oldRange:{from:m,to:f},newRange:{from:d,to:u}})})}),Zrs(n)}function WEe(s,t,r){const n=[];return s===t?r.resolve(s).marks().forEach(a=>{const i=r.resolve(s),l=HEe(i,a.type);l&&n.push({mark:a,...l})}):r.nodesBetween(s,t,(a,i)=>{!a||(a==null?void 0:a.nodeSize)===void 0||n.push(...a.marks.map(l=>({from:i,to:i+a.nodeSize,mark:l})))}),n}function Jue(s,t,r){return Object.fromEntries(Object.entries(r).filter(([n])=>{const a=s.find(i=>i.type===t&&i.name===n);return a?a.attribute.keepOnSplit:!1}))}function eSe(s,t,r={}){const{empty:n,ranges:a}=s.selection,i=t?i4(t,s.schema):null;if(n)return!!(s.storedMarks||s.selection.$from.marks()).filter(m=>i?i.name===m.type.name:!0).find(m=>Vme(m.attrs,r,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:m,$to:f})=>{const x=m.pos,y=f.pos;s.doc.nodesBetween(x,y,(_,b)=>{if(!_.isText&&!_.marks.length)return;const j=Math.max(x,b),N=Math.min(y,b+_.nodeSize),C=N-j;l+=C,o.push(..._.marks.map(A=>({mark:A,from:j,to:N})))})}),l===0)return!1;const c=o.filter(m=>i?i.name===m.mark.type.name:!0).filter(m=>Vme(m.mark.attrs,r,{strict:!1})).reduce((m,f)=>m+f.to-f.from,0),d=o.filter(m=>i?m.mark.type!==i&&m.mark.type.excludes(i):!0).reduce((m,f)=>m+f.to-f.from,0);return(c>0?c+d:c)>=l}function Qrs(s,t,r={}){if(!t)return V9(s,null,r)||eSe(s,null,r);const n=Qge(t,s.schema);return n==="node"?V9(s,t,r):n==="mark"?eSe(s,t,r):!1}function PBe(s,t){const{nodeExtensions:r}=Yge(t),n=r.find(l=>l.name===s);if(!n)return!1;const a={name:n.name,options:n.options,storage:n.storage},i=Ro(ii(n,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function KEe(s,{checkChildren:t=!0,ignoreWhitespace:r=!1}={}){var n;if(r){if(s.type.name==="hardBreak")return!0;if(s.isText)return/^\s*$/m.test((n=s.text)!==null&&n!==void 0?n:"")}if(s.isText)return!s.text;if(s.isAtom||s.isLeaf)return!1;if(s.content.childCount===0)return!0;if(t){let a=!0;return s.content.forEach(i=>{a!==!1&&(KEe(i,{ignoreWhitespace:r,checkChildren:t})||(a=!1))}),a}return!1}function Jrs(s){return s instanceof Ei}function ens(s,t,r){var n;const{selection:a}=t;let i=null;if($ut(a)&&(i=a.$cursor),i){const o=(n=s.storedMarks)!==null&&n!==void 0?n:i.marks();return!!r.isInSet(o)||!o.some(c=>c.type.excludes(r))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(r):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,m,f)=>{if(d)return!1;if(u.isInline){const x=!f||f.type.allowsMarkType(r),y=!!r.isInSet(u.marks)||!u.marks.some(_=>_.type.excludes(r));d=x&&y}return!d}),d})}const tns=(s,t={})=>({tr:r,state:n,dispatch:a})=>{const{selection:i}=r,{empty:l,ranges:o}=i,c=i4(s,n.schema);if(a)if(l){const d=Hut(n,c);r.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,m=d.$to.pos;n.doc.nodesBetween(u,m,(f,x)=>{const y=Math.max(x,u),_=Math.min(x+f.nodeSize,m);f.marks.find(j=>j.type===c)?f.marks.forEach(j=>{c===j.type&&r.addMark(y,_,c.create({...j.attrs,...t}))}):r.addMark(y,_,c.create(t))})});return ens(n,r,c)},sns=(s,t)=>({tr:r})=>(r.setMeta(s,t),!0),rns=(s,t={})=>({state:r,dispatch:n,chain:a})=>{const i=uf(s,r.schema);let l;return r.selection.$anchor.sameParent(r.selection.$head)&&(l=r.selection.$anchor.parent.attrs),i.isTextblock?a().command(({commands:o})=>SBe(i,{...l,...t})(r)?!0:o.clearNodes()).command(({state:o})=>SBe(i,{...l,...t})(o,n)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},nns=s=>({tr:t,dispatch:r})=>{if(r){const{doc:n}=t,a=tE(s,0,n.content.size),i=Ei.create(n,a);t.setSelection(i)}return!0},ans=s=>({tr:t,dispatch:r})=>{if(r){const{doc:n}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Oi.atStart(n).from,o=Oi.atEnd(n).to,c=tE(a,l,o),d=tE(i,l,o),u=Oi.create(n,c,d);t.setSelection(u)}return!0},ins=s=>({state:t,dispatch:r})=>{const n=uf(s,t.schema);return Oss(n)(t,r)};function LBe(s,t){const r=s.storedMarks||s.selection.$to.parentOffset&&s.selection.$from.marks();if(r){const n=r.filter(a=>t==null?void 0:t.includes(a.type.name));s.tr.ensureMarks(n)}}const ons=({keepMarks:s=!0}={})=>({tr:t,state:r,dispatch:n,editor:a})=>{const{selection:i,doc:l}=t,{$from:o,$to:c}=i,d=a.extensionManager.attributes,u=Jue(d,o.node().type.name,o.node().attrs);if(i instanceof Ei&&i.node.isBlock)return!o.parentOffset||!jP(l,o.pos)?!1:(n&&(s&&LBe(r,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const m=c.parentOffset===c.parent.content.size,f=o.depth===0?void 0:Hrs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let x=m&&f?[{type:f,attrs:u}]:void 0,y=jP(t.doc,t.mapping.map(o.pos),1,x);if(!x&&!y&&jP(t.doc,t.mapping.map(o.pos),1,f?[{type:f}]:void 0)&&(y=!0,x=f?[{type:f,attrs:u}]:void 0),n){if(y&&(i instanceof Oi&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,x),f&&!m&&!o.parentOffset&&o.parent.type!==f)){const _=t.mapping.map(o.before()),b=t.doc.resolve(_);o.node(-1).canReplaceWith(b.index(),b.index()+1,f)&&t.setNodeMarkup(t.mapping.map(o.before()),f)}s&&LBe(r,a.extensionManager.splittableMarks),t.scrollIntoView()}return y},lns=(s,t={})=>({tr:r,state:n,dispatch:a,editor:i})=>{var l;const o=uf(s,n.schema),{$from:c,$to:d}=n.selection,u=n.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const m=c.node(-1);if(m.type!==o)return!1;const f=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=Rn.empty;const N=c.index(-1)?1:c.index(-2)?2:3;for(let F=c.depth-N;F>=c.depth-3;F-=1)j=Rn.from(c.node(F).copy(j));const C=c.indexAfter(-1){if(R>-1)return!1;F.isTextblock&&F.content.size===0&&(R=O+1)}),R>-1&&r.setSelection(Oi.near(r.doc.resolve(R))),r.scrollIntoView()}return!0}const x=d.pos===c.end()?m.contentMatchAt(0).defaultType:null,y={...Jue(f,m.type.name,m.attrs),...t},_={...Jue(f,c.node().type.name,c.node().attrs),...t};r.delete(c.pos,d.pos);const b=x?[{type:o,attrs:y},{type:x,attrs:_}]:[{type:o,attrs:y}];if(!jP(r.doc,c.pos,2))return!1;if(a){const{selection:j,storedMarks:N}=n,{splittableMarks:C}=i.extensionManager,A=N||j.$to.parentOffset&&j.$from.marks();if(r.split(c.pos,2,b).scrollIntoView(),!A||!a)return!0;const E=A.filter(D=>C.includes(D.type.name));r.ensureMarks(E)}return!0},z_e=(s,t)=>{const r=GEe(l=>l.type===t)(s.selection);if(!r)return!0;const n=s.doc.resolve(Math.max(0,r.pos-1)).before(r.depth);if(n===void 0)return!0;const a=s.doc.nodeAt(n);return r.node.type===(a==null?void 0:a.type)&&n4(s.doc,r.pos)&&s.join(r.pos),!0},B_e=(s,t)=>{const r=GEe(l=>l.type===t)(s.selection);if(!r)return!0;const n=s.doc.resolve(r.start).after(r.depth);if(n===void 0)return!0;const a=s.doc.nodeAt(n);return r.node.type===(a==null?void 0:a.type)&&n4(s.doc,n)&&s.join(n),!0},cns=(s,t,r,n={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:m,splittableMarks:f}=a.extensionManager,x=uf(s,l.schema),y=uf(t,l.schema),{selection:_,storedMarks:b}=l,{$from:j,$to:N}=_,C=j.blockRange(N),A=b||_.$to.parentOffset&&_.$from.marks();if(!C)return!1;const E=GEe(D=>PBe(D.type.name,m))(_);if(C.depth>=1&&E&&C.depth-E.depth<=1){if(E.node.type===x)return d.liftListItem(y);if(PBe(E.node.type.name,m)&&x.validContent(E.node.content)&&o)return c().command(()=>(i.setNodeMarkup(E.pos,x),!0)).command(()=>z_e(i,x)).command(()=>B_e(i,x)).run()}return!r||!A||!o?c().command(()=>u().wrapInList(x,n)?!0:d.clearNodes()).wrapInList(x,n).command(()=>z_e(i,x)).command(()=>B_e(i,x)).run():c().command(()=>{const D=u().wrapInList(x,n),R=A.filter(F=>f.includes(F.type.name));return i.ensureMarks(R),D?!0:d.clearNodes()}).wrapInList(x,n).command(()=>z_e(i,x)).command(()=>B_e(i,x)).run()},dns=(s,t={},r={})=>({state:n,commands:a})=>{const{extendEmptyMarkRange:i=!1}=r,l=i4(s,n.schema);return eSe(n,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},uns=(s,t,r={})=>({state:n,commands:a})=>{const i=uf(s,n.schema),l=uf(t,n.schema),o=V9(n,i,r);let c;return n.selection.$anchor.sameParent(n.selection.$head)&&(c=n.selection.$anchor.parent.attrs),o?a.setNode(l,c):a.setNode(i,{...c,...r})},hns=(s,t={})=>({state:r,commands:n})=>{const a=uf(s,r.schema);return V9(r,a,t)?n.lift(a):n.wrapIn(a,t)},mns=()=>({state:s,dispatch:t})=>{const r=s.plugins;for(let n=0;n=0;c-=1)l.step(o.steps[c].invert(o.docs[c]));if(i.text){const c=l.doc.resolve(i.from).marks();l.replaceWith(i.from,i.to,s.schema.text(i.text,c))}else l.delete(i.from,i.to)}return!0}}return!1},fns=()=>({tr:s,dispatch:t})=>{const{selection:r}=s,{empty:n,ranges:a}=r;return n||t&&a.forEach(i=>{s.removeMark(i.$from.pos,i.$to.pos)}),!0},pns=(s,t={})=>({tr:r,state:n,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=r,c=i4(s,n.schema),{$from:d,empty:u,ranges:m}=o;if(!a)return!0;if(u&&l){let{from:f,to:x}=o;const y=(i=d.marks().find(b=>b.type===c))===null||i===void 0?void 0:i.attrs,_=HEe(d,c,y);_&&(f=_.from,x=_.to),r.removeMark(f,x,c)}else m.forEach(f=>{r.removeMark(f.$from.pos,f.$to.pos,c)});return r.removeStoredMark(c),!0},xns=(s,t={})=>({tr:r,state:n,dispatch:a})=>{let i=null,l=null;const o=Qge(typeof s=="string"?s:s.name,n.schema);return o?(o==="node"&&(i=uf(s,n.schema)),o==="mark"&&(l=i4(s,n.schema)),a&&r.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let m,f,x,y;r.selection.empty?n.doc.nodesBetween(d,u,(_,b)=>{i&&i===_.type&&(x=Math.max(b,d),y=Math.min(b+_.nodeSize,u),m=b,f=_)}):n.doc.nodesBetween(d,u,(_,b)=>{b=d&&b<=u&&(i&&i===_.type&&r.setNodeMarkup(b,void 0,{..._.attrs,...t}),l&&_.marks.length&&_.marks.forEach(j=>{if(l===j.type){const N=Math.max(b,d),C=Math.min(b+_.nodeSize,u);r.addMark(N,C,l.create({...j.attrs,...t}))}}))}),f&&(m!==void 0&&r.setNodeMarkup(m,void 0,{...f.attrs,...t}),l&&f.marks.length&&f.marks.forEach(_=>{l===_.type&&r.addMark(x,y,l.create({..._.attrs,...t}))}))}),!0):!1},gns=(s,t={})=>({state:r,dispatch:n})=>{const a=uf(s,r.schema);return Ass(a,t)(r,n)},yns=(s,t={})=>({state:r,dispatch:n})=>{const a=uf(s,r.schema);return Mss(a,t)(r,n)};var vns=Object.freeze({__proto__:null,blur:ers,clearContent:trs,clearNodes:srs,command:rrs,createParagraphNear:nrs,cut:ars,deleteCurrentNode:irs,deleteNode:ors,deleteRange:lrs,deleteSelection:crs,enter:drs,exitCode:urs,extendMarkRange:hrs,first:mrs,focus:prs,forEach:xrs,insertContent:grs,insertContentAt:brs,joinBackward:jrs,joinDown:wrs,joinForward:Nrs,joinItemBackward:krs,joinItemForward:Srs,joinTextblockBackward:Crs,joinTextblockForward:Trs,joinUp:_rs,keyboardShortcut:Ars,lift:Mrs,liftEmptyBlock:Irs,liftListItem:Prs,newlineInCode:Lrs,resetAttributes:Drs,scrollIntoView:Rrs,selectAll:Ors,selectNodeBackward:Frs,selectNodeForward:zrs,selectParentNode:Brs,selectTextblockEnd:$rs,selectTextblockStart:Urs,setContent:qrs,setMark:tns,setMeta:sns,setNode:rns,setNodeSelection:nns,setTextSelection:ans,sinkListItem:ins,splitBlock:ons,splitListItem:lns,toggleList:cns,toggleMark:dns,toggleNode:uns,toggleWrap:hns,undoInputRule:mns,unsetAllMarks:fns,unsetMark:pns,updateAttributes:xns,wrapIn:gns,wrapInList:yns});const bns=tp.create({name:"commands",addCommands(){return{...vns}}}),_ns=tp.create({name:"drop",addProseMirrorPlugins(){return[new Tm({key:new Rp("tiptapDrop"),props:{handleDrop:(s,t,r,n)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:r,moved:n})}}})]}}),wns=tp.create({name:"editable",addProseMirrorPlugins(){return[new Tm({key:new Rp("editable"),props:{editable:()=>this.editor.options.editable}})]}}),jns=new Rp("focusEvents"),Nns=tp.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new Tm({key:jns,props:{handleDOMEvents:{focus:(t,r)=>{s.isFocused=!0;const n=s.state.tr.setMeta("focus",{event:r}).setMeta("addToHistory",!1);return t.dispatch(n),!1},blur:(t,r)=>{s.isFocused=!1;const n=s.state.tr.setMeta("blur",{event:r}).setMeta("addToHistory",!1);return t.dispatch(n),!1}}}})]}}),kns=tp.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:m}=c,{pos:f,parent:x}=m,y=m.parent.isTextblock&&f>0?o.doc.resolve(f-1):m,_=y.parent.type.spec.isolating,b=m.pos-m.parentOffset,j=_&&y.parent.childCount===1?b===m.pos:Qi.atStart(d).from===f;return!u||!x.type.isTextblock||x.textContent.length||!j||j&&m.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...n},i={...n,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Hme()||Vut()?i:a},addProseMirrorPlugins(){return[new Tm({key:new Rp("clearDocument"),appendTransaction:(s,t,r)=>{if(s.some(_=>_.getMeta("composition")))return;const n=s.some(_=>_.docChanged)&&!t.doc.eq(r.doc),a=s.some(_=>_.getMeta("preventClearDocument"));if(!n||a)return;const{empty:i,from:l,to:o}=t.selection,c=Qi.atStart(t.doc).from,d=Qi.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!KEe(r.doc))return;const f=r.tr,x=Wge({state:r,transaction:f}),{commands:y}=new Kge({editor:this.editor,state:x});if(y.clearNodes(),!!f.steps.length)return f}})]}}),Sns=tp.create({name:"paste",addProseMirrorPlugins(){return[new Tm({key:new Rp("tiptapPaste"),props:{handlePaste:(s,t,r)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:r})}}})]}}),Cns=tp.create({name:"tabindex",addProseMirrorPlugins(){return[new Tm({key:new Rp("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class qT{get name(){return this.node.type.name}constructor(t,r,n=!1,a=null){this.currentNode=null,this.actualDepth=null,this.isBlock=n,this.resolvedPos=t,this.editor=r,this.currentNode=a}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var t;return(t=this.actualDepth)!==null&&t!==void 0?t:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(t){let r=this.from,n=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}r=this.from+1,n=this.to-1}this.editor.commands.insertContentAt({from:r,to:n},t)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const t=this.resolvedPos.start(this.resolvedPos.depth-1),r=this.resolvedPos.doc.resolve(t);return new qT(r,this.editor)}get before(){let t=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return t.depth!==this.depth&&(t=this.resolvedPos.doc.resolve(this.from-3)),new qT(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 qT(t,this.editor)}get children(){const t=[];return this.node.content.forEach((r,n)=>{const a=r.isBlock&&!r.isTextblock,i=r.isAtom&&!r.isText,l=this.pos+n+(i?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const o=this.resolvedPos.doc.resolve(l);if(!a&&o.depth<=this.depth)return;const c=new qT(o,this.editor,a,a?r:null);a&&(c.actualDepth=this.depth+1),t.push(new qT(o,this.editor,a,a?r:null))}),t}get firstChild(){return this.children[0]||null}get lastChild(){const t=this.children;return t[t.length-1]||null}closest(t,r={}){let n=null,a=this.parent;for(;a&&!n;){if(a.node.type.name===t)if(Object.keys(r).length>0){const i=a.node.attrs,l=Object.keys(r);for(let o=0;o{n&&a.length>0||(l.node.type.name===t&&i.every(c=>r[c]===l.node.attrs[c])&&a.push(l),!(n&&a.length>0)&&(a=a.concat(l.querySelectorAll(t,r,n))))}),a}setAttribute(t){const{tr:r}=this.editor.state;r.setNodeMarkup(this.from,void 0,{...this.node.attrs,...t}),this.editor.view.dispatch(r)}}const Tns=`.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 Ens(s,t,r){const n=document.querySelector("style[data-tiptap-style]");if(n!==null)return n;const a=document.createElement("style");return t&&a.setAttribute("nonce",t),a.setAttribute("data-tiptap-style",""),a.innerHTML=s,document.getElementsByTagName("head")[0].appendChild(a),a}class Ans extends Fss{constructor(t={}){super(),this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.options={element:document.createElement("div"),content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("contentError",this.options.onContentError),this.createView(),this.injectCSS(),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:n,moved:a})=>this.options.onDrop(r,n,a)),this.on("paste",({event:r,slice:n})=>this.options.onPaste(r,n)),window.setTimeout(()=>{this.isDestroyed||(this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&document&&(this.css=Ens(Tns,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.view||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,r=!0){this.setOptions({editable:t}),r&&this.emit("update",{editor:this,transaction:this.state.tr})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get state(){return this.view.state}registerPlugin(t,r){const n=Out(r)?r(t,[...this.state.plugins]):[...this.state.plugins,t],a=this.state.reconfigure({plugins:n});return this.view.updateState(a),a}unregisterPlugin(t){if(this.isDestroyed)return;const r=this.state.plugins;let n=r;if([].concat(t).forEach(i=>{const l=typeof i=="string"?`${i}$`:i.key;n=n.filter(o=>!o.key.startsWith(l))}),r.length===n.length)return;const a=this.state.reconfigure({plugins:n});return this.view.updateState(a),a}createExtensionManager(){var t,r;const a=[...this.options.enableCoreExtensions?[wns,Jss.configure({blockSeparator:(r=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||r===void 0?void 0:r.blockSeparator}),bns,Nns,kns,Cns,_ns,Sns].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 kI(a,this)}createCommandManager(){this.commandManager=new Kge({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let r;try{r=Jke(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(l){if(!(l instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(l.message))throw l;this.emit("contentError",{editor:this,error:l,disableCollaboration:()=>{this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(o=>o.name!=="collaboration"),this.createExtensionManager()}}),r=Jke(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const n=Uut(r,this.options.autofocus);this.view=new Eut(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:NI.create({doc:r,selection:n||void 0})});const a=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(a),this.createNodeViews(),this.prependClass();const i=this.view.dom;i.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`tiptap ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const r=this.capturedTransaction;return this.capturedTransaction=null,r}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(l=>{var o;return(o=this.capturedTransaction)===null||o===void 0?void 0:o.step(l)});return}const r=this.state.apply(t),n=!this.state.selection.eq(r.selection);this.emit("beforeTransaction",{editor:this,transaction:t,nextState:r}),this.view.updateState(r),this.emit("transaction",{editor:this,transaction:t}),n&&this.emit("selectionUpdate",{editor:this,transaction:t});const a=t.getMeta("focus"),i=t.getMeta("blur");a&&this.emit("focus",{editor:this,event:a.event,transaction:t}),i&&this.emit("blur",{editor:this,event:i.event,transaction:t}),!(!t.docChanged||t.getMeta("preventUpdate"))&&this.emit("update",{editor:this,transaction:t})}getAttributes(t){return Wut(this.state,t)}isActive(t,r){const n=typeof t=="string"?t:null,a=typeof t=="string"?r:t;return Qrs(this.state,n,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return qEe(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:r=` `,textSerializers:n={}}=t||{};return Wrs(this.state.doc,{blockSeparator:r,textSerializers:{...zut(this.schema),...n}})}get isEmpty(){return KEe(this.state.doc)}getCharacterCount(){return console.warn('[tiptap warn]: "editor.getCharacterCount()" is deprecated. Please use "editor.storage.characterCount.characters()" instead.'),this.state.doc.content.size-2}destroy(){if(this.emit("destroy"),this.view){const t=this.view.dom;t&&t.editor&&delete t.editor,this.view.destroy()}this.removeAllListeners()}get isDestroyed(){var t;return!(!((t=this.view)===null||t===void 0)&&t.docView)}$node(t,r){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelector(t,r))||null}$nodes(t,r){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelectorAll(t,r))||null}$pos(t){const r=this.state.doc.resolve(t);return new qT(r,this)}get $doc(){return this.$pos(0)}}function bL(s){return new Zge({find:s.find,handler:({state:t,range:r,match:n})=>{const a=Ro(s.getAttributes,void 0,n);if(a===!1||a===null)return null;const{tr:i}=t,l=n[n.length-1],o=n[0];if(l){const c=o.search(/\S/),d=r.from+o.indexOf(l),u=d+l.length;if(WEe(r.from,r.to,t.doc).filter(x=>x.mark.type.excluded.find(_=>_===s.type&&_!==x.mark.type)).filter(x=>x.to>d).length)return null;ur.from&&i.delete(r.from+c,d);const f=r.from+c+l.length;i.addMark(r.from+c,f,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function Kut(s){return new Zge({find:s.find,handler:({state:t,range:r,match:n})=>{const a=Ro(s.getAttributes,void 0,n)||{},{tr:i}=t,l=r.from;let o=r.to;const c=s.type.create(a);if(n[1]){const d=n[0].lastIndexOf(n[1]);let u=l+d;u>o?u=o:o=u+n[1].length;const m=n[0][n[0].length-1];i.insertText(m,l+n[0].length-1),i.replaceWith(u,o,c)}else if(n[0]){const d=s.type.isInline?l:l-1;i.insert(d,s.type.create(a)).delete(i.mapping.map(l),i.mapping.map(o))}i.scrollIntoView()}})}function tSe(s){return new Zge({find:s.find,handler:({state:t,range:r,match:n})=>{const a=t.doc.resolve(r.from),i=Ro(s.getAttributes,void 0,n)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),s.type))return null;t.tr.delete(r.from,r.to).setBlockType(r.from,r.from,s.type,i)}})}function H9(s){return new Zge({find:s.find,handler:({state:t,range:r,match:n,chain:a})=>{const i=Ro(s.getAttributes,void 0,n)||{},l=t.tr.delete(r.from,r.to),c=l.doc.resolve(r.from).blockRange(),d=c&&TEe(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:m,storedMarks:f}=t,{splittableMarks:x}=s.editor.extensionManager,y=f||m.$to.parentOffset&&m.$from.marks();if(y){const _=y.filter(b=>x.includes(b.type.name));l.ensureMarks(_)}}if(s.keepAttributes){const m=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(m,i).run()}const u=l.doc.resolve(r.from-1).nodeBefore;u&&u.type===s.type&&n4(l.doc,r.from-1)&&(!s.joinPredicate||s.joinPredicate(n,u))&&l.join(r.from-1)}})}let Op=class sSe{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=Ro(ii(this,"addOptions",{name:this.name}))),this.storage=Ro(ii(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new sSe(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>Xge(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new sSe(t);return r.parent=this,this.child=r,r.name=t.name?t.name:r.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${r.name}".`),r.options=Ro(ii(r,"addOptions",{name:r.name})),r.storage=Ro(ii(r,"addStorage",{name:r.name,options:r.options})),r}};function TA(s){return new Wss({find:s.find,handler:({state:t,range:r,match:n,pasteEvent:a})=>{const i=Ro(s.getAttributes,void 0,n,a);if(i===!1||i===null)return null;const{tr:l}=t,o=n[n.length-1],c=n[0];let d=r.to;if(o){const u=c.search(/\S/),m=r.from+c.indexOf(o),f=m+o.length;if(WEe(r.from,r.to,t.doc).filter(y=>y.mark.type.excluded.find(b=>b===s.type&&b!==y.mark.type)).filter(y=>y.to>m).length)return null;fr.from&&l.delete(r.from+u,m),d=r.from+u+o.length,l.addMark(r.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function Mns(s,t){const{selection:r}=s,{$from:n}=r;if(r instanceof Ei){const i=n.index();return n.parent.canReplaceWith(i,i+1,t)}let a=n.depth;for(;a>=0;){const i=n.index(a);if(n.node(a).contentMatchAt(i).matchType(t))return!0;a-=1}return!1}function Ins(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Yut={exports:{}},$_e={};/** * @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 DBe;function Pns(){if(DBe)return $_e;DBe=1;var s=Ct;function t(m,f){return m===f&&(m!==0||1/m===1/f)||m!==m&&f!==f}var r=typeof Object.is=="function"?Object.is:t,n=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(m,f){var x=f(),y=n({inst:{value:x,getSnapshot:f}}),_=y[0].inst,b=y[1];return i(function(){_.value=x,_.getSnapshot=f,c(_)&&b({inst:_})},[m,x,f]),a(function(){return c(_)&&b({inst:_}),m(function(){c(_)&&b({inst:_})})},[m]),l(x),x}function c(m){var f=m.getSnapshot;m=m.value;try{var x=f();return!r(m,x)}catch{return!0}}function d(m,f){return f()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return $_e.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,$_e}Yut.exports=Pns();var YEe=Yut.exports;const Lns=(...s)=>t=>{s.forEach(r=>{typeof r=="function"?r(t):r&&(r.current=t)})},Dns=({contentComponent:s})=>{const t=YEe.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Ct.createElement(Ct.Fragment,null,Object.values(t))};function Rns(){const s=new Set;let t={};return{subscribe(r){return s.add(r),()=>{s.delete(r)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(r,n){t={...t,[r]:a5e.createPortal(n.reactElement,n.element,r)},s.forEach(a=>a())},removeRenderer(r){const n={...t};delete n[r],t=n,s.forEach(a=>a())}}}class Ons extends Ct.Component{constructor(t){var r;super(t),this.editorContentRef=Ct.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((r=t.editor)===null||r===void 0)&&r.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const r=this.editorContentRef.current;r.append(...t.options.element.childNodes),t.setOptions({element:r}),t.contentComponent=Rns(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(n=>n.hasContentComponentInitialized?n:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){const t=this.props.editor;if(!t||(this.initialized=!1,t.isDestroyed||t.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),t.contentComponent=null,!t.options.element.firstChild))return;const r=document.createElement("div");r.append(...t.options.element.childNodes),t.setOptions({element:r})}render(){const{editor:t,innerRef:r,...n}=this.props;return Ct.createElement(Ct.Fragment,null,Ct.createElement("div",{ref:Lns(r,this.editorContentRef),...n}),(t==null?void 0:t.contentComponent)&&Ct.createElement(Dns,{contentComponent:t.contentComponent}))}}const Fns=k.forwardRef((s,t)=>{const r=Ct.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Ct.createElement(Ons,{key:r,innerRef:t,...s})}),ZEe=Ct.memo(Fns);var zns=function s(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!s(t[a],r[a]))return!1;return!0}if(t instanceof Map&&r instanceof Map){if(t.size!==r.size)return!1;for(a of t.entries())if(!r.has(a[0]))return!1;for(a of t.entries())if(!s(a[1],r.get(a[0])))return!1;return!0}if(t instanceof Set&&r instanceof Set){if(t.size!==r.size)return!1;for(a of t.entries())if(!r.has(a[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(t[a]!==r[a])return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var l=i[a];if(!(l==="_owner"&&t.$$typeof)&&!s(t[l],r[l]))return!1}return!0}return t!==t&&r!==r},Bns=Ins(zns),Zut={exports:{}},U_e={};/** * @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 RBe;function $ns(){if(RBe)return U_e;RBe=1;var s=Ct,t=YEe;function r(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var n=typeof Object.is=="function"?Object.is:r,a=t.useSyncExternalStore,i=s.useRef,l=s.useEffect,o=s.useMemo,c=s.useDebugValue;return U_e.useSyncExternalStoreWithSelector=function(d,u,m,f,x){var y=i(null);if(y.current===null){var _={hasValue:!1,value:null};y.current=_}else _=y.current;y=o(function(){function j(D){if(!N){if(N=!0,C=D,D=f(D),x!==void 0&&_.hasValue){var R=_.value;if(x(R,D))return A=R}return A=D}if(R=A,n(C,D))return R;var F=f(D);return x!==void 0&&x(R,F)?R:(C=D,A=F)}var N=!1,C,A,E=m===void 0?null:m;return[function(){return j(u())},E===null?void 0:function(){return j(E())}]},[u,m,f,x]);var b=a(d,y[0],y[1]);return l(function(){_.hasValue=!0,_.value=b},[b]),c(b),b},U_e}Zut.exports=$ns();var Uns=Zut.exports;const qns=typeof window<"u"?k.useLayoutEffect:k.useEffect;class Vns{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const r=()=>{this.transactionNumber+=1,this.subscribers.forEach(a=>a())},n=this.editor;return n.on("transaction",r),()=>{n.off("transaction",r)}}}}function Hns(s){var t;const[r]=k.useState(()=>new Vns(s.editor)),n=Uns.useSyncExternalStoreWithSelector(r.subscribe,r.getSnapshot,r.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:Bns);return qns(()=>r.watch(s.editor),[s.editor,r]),k.useDebugValue(n),n}const Gns=!1,rSe=typeof window>"u",Wns=rSe||!!(typeof window<"u"&&window.next);class XEe{constructor(t){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=t,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(t){this.editor=t,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(r=>r())}getInitialEditor(){if(this.options.current.immediatelyRender===void 0)return rSe||Wns?null:this.createEditor();if(this.options.current.immediatelyRender&&rSe&&Gns)throw new Error("Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches.");return this.options.current.immediatelyRender?this.createEditor():null}createEditor(){const t={...this.options.current,onBeforeCreate:(...n)=>{var a,i;return(i=(a=this.options.current).onBeforeCreate)===null||i===void 0?void 0:i.call(a,...n)},onBlur:(...n)=>{var a,i;return(i=(a=this.options.current).onBlur)===null||i===void 0?void 0:i.call(a,...n)},onCreate:(...n)=>{var a,i;return(i=(a=this.options.current).onCreate)===null||i===void 0?void 0:i.call(a,...n)},onDestroy:(...n)=>{var a,i;return(i=(a=this.options.current).onDestroy)===null||i===void 0?void 0:i.call(a,...n)},onFocus:(...n)=>{var a,i;return(i=(a=this.options.current).onFocus)===null||i===void 0?void 0:i.call(a,...n)},onSelectionUpdate:(...n)=>{var a,i;return(i=(a=this.options.current).onSelectionUpdate)===null||i===void 0?void 0:i.call(a,...n)},onTransaction:(...n)=>{var a,i;return(i=(a=this.options.current).onTransaction)===null||i===void 0?void 0:i.call(a,...n)},onUpdate:(...n)=>{var a,i;return(i=(a=this.options.current).onUpdate)===null||i===void 0?void 0:i.call(a,...n)},onContentError:(...n)=>{var a,i;return(i=(a=this.options.current).onContentError)===null||i===void 0?void 0:i.call(a,...n)},onDrop:(...n)=>{var a,i;return(i=(a=this.options.current).onDrop)===null||i===void 0?void 0:i.call(a,...n)},onPaste:(...n)=>{var a,i;return(i=(a=this.options.current).onPaste)===null||i===void 0?void 0:i.call(a,...n)}};return new Ans(t)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(t){return this.subscriptions.add(t),()=>{this.subscriptions.delete(t)}}static compareOptions(t,r){return Object.keys(t).every(n=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(n)?!0:n==="extensions"&&t.extensions&&r.extensions?t.extensions.length!==r.extensions.length?!1:t.extensions.every((a,i)=>{var l;return a===((l=r.extensions)===null||l===void 0?void 0:l[i])}):t[n]===r[n])}onRender(t){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&t.length===0?XEe.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(t),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(t){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=t;return}if(this.previousDeps.length===t.length&&this.previousDeps.every((n,a)=>n===t[a]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=t}scheduleDestroy(){const t=this.instanceId,r=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===t){r&&r.setOptions(this.options.current);return}r&&!r.isDestroyed&&(r.destroy(),this.instanceId===t&&this.setEditor(null))},1)}}function QEe(s={},t=[]){const r=k.useRef(s);r.current=s;const[n]=k.useState(()=>new XEe(r)),a=YEe.useSyncExternalStore(n.subscribe,n.getEditor,n.getServerSnapshot);return k.useDebugValue(a),k.useEffect(n.onRender(t)),Hns({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const Kns=k.createContext({editor:null});Kns.Consumer;const Yns=k.createContext({onDragStart:void 0}),Zns=()=>k.useContext(Yns);Ct.forwardRef((s,t)=>{const{onDragStart:r}=Zns(),n=s.as||"div";return Ct.createElement(n,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:r,style:{whiteSpace:"normal",...s.style}})});const Xns=/^\s*>\s$/,Qns=Op.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",Yd(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[H9({find:Xns,type:this.type})]}}),Jns=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,eas=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,tas=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,sas=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,ras=F1.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",Yd(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[bL({find:Jns,type:this.type}),bL({find:tas,type:this.type})]},addPasteRules(){return[TA({find:eas,type:this.type}),TA({find:sas,type:this.type})]}}),nas="listItem",OBe="textStyle",FBe=/^\s*([-+*])\s$/,aas=Op.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",Yd(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(nas,this.editor.getAttributes(OBe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=H9({find:FBe,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=H9({find:FBe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(OBe),editor:this.editor})),[s]}}),ias=/(^|[^`])`([^`]+)`(?!`)/,oas=/(^|[^`])`([^`]+)`(?!`)/g,las=F1.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Yd(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[bL({find:ias,type:this.type})]},addPasteRules(){return[TA({find:oas,type:this.type})]}}),cas=/^```([a-z]+)?[\s\n]$/,das=/^~~~([a-z]+)?[\s\n]$/,uas=Op.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:s=>{var t;const{languageClassPrefix:r}=this.options,i=[...((t=s.firstElementChild)===null||t===void 0?void 0:t.classList)||[]].filter(l=>l.startsWith(r)).map(l=>l.replace(r,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:t}){return["pre",Yd(this.options.HTMLAttributes,t),["code",{class:s.attrs.language?this.options.languageClassPrefix+s.attrs.language:null},0]]},addCommands(){return{setCodeBlock:s=>({commands:t})=>t.setNode(this.name,s),toggleCodeBlock:s=>({commands:t})=>t.toggleNode(this.name,"paragraph",s)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:s,$anchor:t}=this.editor.state.selection,r=t.pos===1;return!s||t.parent.type.name!==this.name?!1:r||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=s,{selection:r}=t,{$from:n,empty:a}=r;if(!a||n.parent.type!==this.type)return!1;const i=n.parentOffset===n.parent.nodeSize-2,l=n.parent.textContent.endsWith(` `);return!i||!l?!1:s.chain().command(({tr:o})=>(o.delete(n.pos-2,n.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=s,{selection:r,doc:n}=t,{$from:a,empty:i}=r;if(!i||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const o=a.after();return o===void 0?!1:n.nodeAt(o)?s.commands.command(({tr:d})=>(d.setSelection(Qi.near(n.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[tSe({find:cas,type:this.type,getAttributes:s=>({language:s[1]})}),tSe({find:das,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new Tm({key:new Rp("codeBlockVSCodeHandler"),props:{handlePaste:(s,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;const r=t.clipboardData.getData("text/plain"),n=t.clipboardData.getData("vscode-editor-data"),a=n?JSON.parse(n):void 0,i=a==null?void 0:a.mode;if(!r||!i)return!1;const{tr:l,schema:o}=s.state,c=o.text(r.replace(/\r\n?/g,` `));return l.replaceSelectionWith(this.type.create({language:i},c)),l.selection.$from.parent.type!==this.type&&l.setSelection(Oi.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),has=Op.create({name:"doc",topNode:!0,content:"block+"});function mas(s={}){return new Tm({view(t){return new fas(t,s)}})}class fas{constructor(t,r){var n;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(n=r.width)!==null&&n!==void 0?n:1,this.color=r.color===!1?void 0:r.color||"black",this.class=r.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:r})=>this.editorView.dom.removeEventListener(t,r))}update(t,r){this.cursorPos!=null&&r.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),r=!t.parent.inlineContent,n,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(r){let m=t.nodeBefore,f=t.nodeAfter;if(m||f){let x=this.editorView.nodeDOM(this.cursorPos-(m?m.nodeSize:0));if(x){let y=x.getBoundingClientRect(),_=m?y.bottom:y.top;m&&f&&(_=(_+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let b=this.width/2*o;n={left:y.left,right:y.right,top:_-b,bottom:_+b}}}}if(!n){let m=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*l;n={left:m.left-f,right:m.left+f,top:m.top,bottom:m.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",r),this.element.classList.toggle("prosemirror-dropcursor-inline",!r);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let m=c.getBoundingClientRect(),f=m.width/c.offsetWidth,x=m.height/c.offsetHeight;d=m.left-c.scrollLeft*f,u=m.top-c.scrollTop*x}this.element.style.left=(n.left-d)/l+"px",this.element.style.top=(n.top-u)/o+"px",this.element.style.width=(n.right-n.left)/l+"px",this.element.style.height=(n.bottom-n.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let r=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),n=r&&r.inside>=0&&this.editorView.state.doc.nodeAt(r.inside),a=n&&n.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,r,t):a;if(r&&!i){let l=r.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=$dt(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 pas=tp.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[mas(this.options)]}});class zu extends Qi{constructor(t){super(t,t)}map(t,r){let n=t.resolve(r.map(this.head));return zu.valid(n)?new zu(n):Qi.near(n)}content(){return pa.empty}eq(t){return t instanceof zu&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,r){if(typeof r.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new zu(t.resolve(r.pos))}getBookmark(){return new JEe(this.anchor)}static valid(t){let r=t.parent;if(r.inlineContent||!xas(t)||!gas(t))return!1;let n=r.type.spec.allowGapCursor;if(n!=null)return n;let a=r.contentMatchAt(t.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(t,r,n=!1){e:for(;;){if(!n&&zu.valid(t))return t;let a=t.pos,i=null;for(let l=t.depth;;l--){let o=t.node(l);if(r>0?t.indexAfter(l)0){i=o.child(r>0?t.indexAfter(l):t.index(l)-1);break}else if(l==0)return null;a+=r;let c=t.doc.resolve(a);if(zu.valid(c))return c}for(;;){let l=r>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Ei.isSelectable(i)){t=t.doc.resolve(a+i.nodeSize*r),n=!1;continue e}break}i=l,a+=r;let o=t.doc.resolve(a);if(zu.valid(o))return o}return null}}}zu.prototype.visible=!1;zu.findFrom=zu.findGapCursorFrom;Qi.jsonID("gapcursor",zu);class JEe{constructor(t){this.pos=t}map(t){return new JEe(t.map(this.pos))}resolve(t){let r=t.resolve(this.pos);return zu.valid(r)?new zu(r):Qi.near(r)}}function Xut(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function xas(s){for(let t=s.depth;t>=0;t--){let r=s.index(t),n=s.node(t);if(r==0){if(n.type.spec.isolating)return!0;continue}for(let a=n.child(r-1);;a=a.lastChild){if(a.childCount==0&&!a.inlineContent||Xut(a.type))return!0;if(a.inlineContent)return!1}}return!0}function gas(s){for(let t=s.depth;t>=0;t--){let r=s.indexAfter(t),n=s.node(t);if(r==n.childCount){if(n.type.spec.isolating)return!0;continue}for(let a=n.child(r);;a=a.firstChild){if(a.childCount==0&&!a.inlineContent||Xut(a.type))return!0;if(a.inlineContent)return!1}}return!0}function yas(){return new Tm({props:{decorations:was,createSelectionBetween(s,t,r){return t.pos==r.pos&&zu.valid(r)?new zu(r):null},handleClick:bas,handleKeyDown:vas,handleDOMEvents:{beforeinput:_as}}})}const vas=BEe({ArrowLeft:Aq("horiz",-1),ArrowRight:Aq("horiz",1),ArrowUp:Aq("vert",-1),ArrowDown:Aq("vert",1)});function Aq(s,t){const r=s=="vert"?t>0?"down":"up":t>0?"right":"left";return function(n,a,i){let l=n.selection,o=t>0?l.$to:l.$from,c=l.empty;if(l instanceof Oi){if(!i.endOfTextblock(r)||o.depth==0)return!1;c=!1,o=n.doc.resolve(t>0?o.after():o.before())}let d=zu.findGapCursorFrom(o,t,c);return d?(a&&a(n.tr.setSelection(new zu(d))),!0):!1}}function bas(s,t,r){if(!s||!s.editable)return!1;let n=s.state.doc.resolve(t);if(!zu.valid(n))return!1;let a=s.posAtCoords({left:r.clientX,top:r.clientY});return a&&a.inside>-1&&Ei.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new zu(n))),!0)}function _as(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof zu))return!1;let{$from:r}=s.state.selection,n=r.parent.contentMatchAt(r.index()).findWrapping(s.state.schema.nodes.text);if(!n)return!1;let a=Rn.empty;for(let l=n.length-1;l>=0;l--)a=Rn.from(n[l].createAndFill(null,a));let i=s.state.tr.replace(r.pos,r.pos,new pa(a,0,0));return i.setSelection(Oi.near(i.doc.resolve(r.pos+1))),s.dispatch(i),!1}function was(s){if(!(s.selection instanceof zu))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",Fu.create(s.doc,[jx.widget(s.selection.head,t,{key:"gapcursor"})])}const jas=tp.create({name:"gapCursor",addProseMirrorPlugins(){return[yas()]},extendNodeSchema(s){var t;const r={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Ro(ii(s,"allowGapCursor",r)))!==null&&t!==void 0?t:null}}}),Nas=Op.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",Yd(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:r,editor:n})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=r;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=n.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&l){const m=c.filter(f=>o.includes(f.type.name));d.ensureMarks(m)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),kas=Op.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]}`,Yd(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=>tSe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var Gme=200,cf=function(){};cf.prototype.append=function(t){return t.length?(t=cf.from(t),!this.length&&t||t.length=r?cf.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,r))};cf.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};cf.prototype.forEach=function(t,r,n){r===void 0&&(r=0),n===void 0&&(n=this.length),r<=n?this.forEachInner(t,r,n,0):this.forEachInvertedInner(t,r,n,0)};cf.prototype.map=function(t,r,n){r===void 0&&(r=0),n===void 0&&(n=this.length);var a=[];return this.forEach(function(i,l){return a.push(t(i,l))},r,n),a};cf.from=function(t){return t instanceof cf?t:t&&t.length?new Qut(t):cf.empty};var Qut=function(s){function t(n){s.call(this),this.values=n}s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t;var r={length:{configurable:!0},depth:{configurable:!0}};return t.prototype.flatten=function(){return this.values},t.prototype.sliceInner=function(a,i){return a==0&&i==this.length?this:new t(this.values.slice(a,i))},t.prototype.getInner=function(a){return this.values[a]},t.prototype.forEachInner=function(a,i,l,o){for(var c=i;c=l;c--)if(a(this.values[c],o+c)===!1)return!1},t.prototype.leafAppend=function(a){if(this.length+a.length<=Gme)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=Gme)return new t(a.flatten().concat(this.values))},r.length.get=function(){return this.values.length},r.depth.get=function(){return 0},Object.defineProperties(t.prototype,r),t}(cf);cf.empty=new Qut([]);var Sas=function(s){function t(r,n){s.call(this),this.left=r,this.right=n,this.length=r.length+n.length,this.depth=Math.max(r.depth,n.depth)+1}return s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t,t.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},t.prototype.getInner=function(n){return no&&this.right.forEachInner(n,Math.max(a-o,0),Math.min(this.length,i)-o,l+o)===!1)return!1},t.prototype.forEachInvertedInner=function(n,a,i,l){var o=this.left.length;if(a>o&&this.right.forEachInvertedInner(n,a-o,Math.max(i,o)-o,l+o)===!1||i=i?this.right.slice(n-i,a-i):this.left.slice(n,i).append(this.right.slice(0,a-i))},t.prototype.leafAppend=function(n){var a=this.right.leafAppend(n);if(a)return new t(this.left,a)},t.prototype.leafPrepend=function(n){var a=this.left.leafPrepend(n);if(a)return new t(a,this.right)},t.prototype.appendInner=function(n){return this.left.depth>=Math.max(this.right.depth,n.depth)+1?new t(this.left,new t(this.right,n)):new t(this,n)},t}(cf);const Cas=500;class y1{constructor(t,r){this.items=t,this.eventCount=r}popEvent(t,r){if(this.eventCount==0)return null;let n=this.items.length;for(;;n--)if(this.items.get(n-1).selection){--n;break}let a,i;r&&(a=this.remapping(n,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],u=[];return this.items.forEach((m,f)=>{if(!m.step){a||(a=this.remapping(n,f+1),i=a.maps.length),i--,u.push(m);return}if(a){u.push(new Gb(m.map));let x=m.step.map(a.slice(i)),y;x&&l.maybeStep(x).doc&&(y=l.mapping.maps[l.mapping.maps.length-1],d.push(new Gb(y,void 0,void 0,d.length+u.length))),i--,y&&a.appendMap(y,i)}else l.maybeStep(m.step);if(m.selection)return o=a?m.selection.map(a.slice(i)):m.selection,c=new y1(this.items.slice(0,n).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:l,selection:o}}addTransform(t,r,n,a){let i=[],l=this.eventCount,o=this.items,c=!a&&o.length?o.get(o.length-1):null;for(let u=0;uEas&&(o=Tas(o,d),l-=d),new y1(o.append(i),l)}remapping(t,r){let n=new F9;return this.items.forEach((a,i)=>{let l=a.mirrorOffset!=null&&i-a.mirrorOffset>=t?n.maps.length-a.mirrorOffset:void 0;n.appendMap(a.map,l)},t,r),n}addMaps(t){return this.eventCount==0?this:new y1(this.items.append(t.map(r=>new Gb(r))),this.eventCount)}rebased(t,r){if(!this.eventCount)return this;let n=[],a=Math.max(0,this.items.length-r),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(f=>{f.selection&&o--},a);let c=r;this.items.forEach(f=>{let x=i.getMirror(--c);if(x==null)return;l=Math.min(l,x);let y=i.maps[x];if(f.step){let _=t.steps[x].invert(t.docs[x]),b=f.selection&&f.selection.map(i.slice(c+1,x));b&&o++,n.push(new Gb(y,_,b))}else n.push(new Gb(y))},a);let d=[];for(let f=r;fCas&&(m=m.compress(this.items.length-n.length)),m}emptyItemCount(){let t=0;return this.items.forEach(r=>{r.step||t++}),t}compress(t=this.items.length){let r=this.remapping(0,t),n=r.maps.length,a=[],i=0;return this.items.forEach((l,o)=>{if(o>=t)a.push(l),l.selection&&i++;else if(l.step){let c=l.step.map(r.slice(n)),d=c&&c.getMap();if(n--,d&&r.appendMap(d,n),c){let u=l.selection&&l.selection.map(r.slice(n));u&&i++;let m=new Gb(d.invert(),c,u),f,x=a.length-1;(f=a.length&&a[x].merge(m))?a[x]=f:a.push(m)}}else l.map&&n--},this.items.length,0),new y1(cf.from(a.reverse()),i)}}y1.empty=new y1(cf.empty,0);function Tas(s,t){let r;return s.forEach((n,a)=>{if(n.selection&&t--==0)return r=a,!1}),s.slice(r)}class Gb{constructor(t,r,n,a){this.map=t,this.step=r,this.selection=n,this.mirrorOffset=a}merge(t){if(this.step&&t.step&&!t.selection){let r=t.step.merge(this.step);if(r)return new Gb(r.getMap().invert(),r,this.selection)}}}class ik{constructor(t,r,n,a,i){this.done=t,this.undone=r,this.prevRanges=n,this.prevTime=a,this.prevComposition=i}}const Eas=20;function Aas(s,t,r,n){let a=r.getMeta(eA),i;if(a)return a.historyState;r.getMeta(Pas)&&(s=new ik(s.done,s.undone,null,0,-1));let l=r.getMeta("appendedTransaction");if(r.steps.length==0)return s;if(l&&l.getMeta(eA))return l.getMeta(eA).redo?new ik(s.done.addTransform(r,void 0,n,ehe(t)),s.undone,zBe(r.mapping.maps),s.prevTime,s.prevComposition):new ik(s.done,s.undone.addTransform(r,void 0,n,ehe(t)),null,s.prevTime,s.prevComposition);if(r.getMeta("addToHistory")!==!1&&!(l&&l.getMeta("addToHistory")===!1)){let o=r.getMeta("composition"),c=s.prevTime==0||!l&&s.prevComposition!=o&&(s.prevTime<(r.time||0)-n.newGroupDelay||!Mas(r,s.prevRanges)),d=l?q_e(s.prevRanges,r.mapping):zBe(r.mapping.maps);return new ik(s.done.addTransform(r,c?t.selection.getBookmark():void 0,n,ehe(t)),y1.empty,d,r.time,o??s.prevComposition)}else return(i=r.getMeta("rebased"))?new ik(s.done.rebased(r,i),s.undone.rebased(r,i),q_e(s.prevRanges,r.mapping),s.prevTime,s.prevComposition):new ik(s.done.addMaps(r.mapping.maps),s.undone.addMaps(r.mapping.maps),q_e(s.prevRanges,r.mapping),s.prevTime,s.prevComposition)}function Mas(s,t){if(!t)return!1;if(!s.docChanged)return!0;let r=!1;return s.mapping.maps[0].forEach((n,a)=>{for(let i=0;i=t[i]&&(r=!0)}),r}function zBe(s){let t=[];for(let r=s.length-1;r>=0&&t.length==0;r--)s[r].forEach((n,a,i,l)=>t.push(i,l));return t}function q_e(s,t){if(!s)return null;let r=[];for(let n=0;n{let a=eA.getState(r);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(n){let i=Ias(a,r,s);i&&n(t?i.scrollIntoView():i)}return!0}}const eht=Jut(!1,!0),tht=Jut(!0,!0),Das=tp.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>eht(s,t),redo:()=>({state:s,dispatch:t})=>tht(s,t)}},addProseMirrorPlugins(){return[Las(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()}}}),Ras=Op.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Yd(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!Mns(t,t.schema.nodes[this.name]))return!1;const{selection:r}=t,{$from:n,$to:a}=r,i=s();return n.parentOffset===0?i.insertContentAt({from:Math.max(n.pos-1,0),to:a.pos},{type:this.name}):Jrs(r)?i.insertContentAt(a.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({tr:l,dispatch:o})=>{var c;if(o){const{$to:d}=l.selection,u=d.end();if(d.nodeAfter)d.nodeAfter.isTextblock?l.setSelection(Oi.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Ei.create(l.doc,d.pos)):l.setSelection(Oi.create(l.doc,d.pos));else{const m=(c=d.parent.type.contentMatch.defaultType)===null||c===void 0?void 0:c.create();m&&(l.insert(u,m),l.setSelection(Oi.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Kut({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Oas=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Fas=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,zas=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Bas=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,$as=F1.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",Yd(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[bL({find:Oas,type:this.type}),bL({find:zas,type:this.type})]},addPasteRules(){return[TA({find:Fas,type:this.type}),TA({find:Bas,type:this.type})]}}),Uas=Op.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Yd(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)}}}),qas="listItem",$Be="textStyle",UBe=/^(\d+)\.\s$/,Vas=Op.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:s=>s.hasAttribute("start")?parseInt(s.getAttribute("start")||"",10):1},type:{default:null,parseHTML:s=>s.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:s}){const{start:t,...r}=s;return t===1?["ol",Yd(this.options.HTMLAttributes,r),0]:["ol",Yd(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(qas,this.editor.getAttributes($Be)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=H9({find:UBe,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:(t,r)=>r.childCount+r.attrs.start===+t[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(s=H9({find:UBe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes($Be)}),joinPredicate:(t,r)=>r.childCount+r.attrs.start===+t[1],editor:this.editor})),[s]}}),Has=Op.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Yd(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Gas=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Was=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Kas=F1.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",Yd(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[bL({find:Gas,type:this.type})]},addPasteRules(){return[TA({find:Was,type:this.type})]}}),Yas=Op.create({name:"text",group:"inline"}),eAe=tp.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(ras.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(Qns.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(aas.configure(this.options.bulletList)),this.options.code!==!1&&s.push(las.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(uas.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(has.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(pas.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(jas.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(Nas.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(kas.configure(this.options.heading)),this.options.history!==!1&&s.push(Das.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(Ras.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push($as.configure(this.options.italic)),this.options.listItem!==!1&&s.push(Uas.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(Vas.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(Has.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(Kas.configure(this.options.strike)),this.options.text!==!1&&s.push(Yas.configure(this.options.text)),s}}),Zas="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Xas="ελ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",nSe="numeric",aSe="ascii",iSe="alpha",S7="asciinumeric",RO="alphanumeric",oSe="domain",sht="emoji",Qas="scheme",Jas="slashscheme",H_e="whitespace";function eis(s,t){return s in t||(t[s]=[]),t[s]}function sE(s,t,r){t[nSe]&&(t[S7]=!0,t[RO]=!0),t[aSe]&&(t[S7]=!0,t[iSe]=!0),t[S7]&&(t[RO]=!0),t[iSe]&&(t[RO]=!0),t[RO]&&(t[oSe]=!0),t[sht]&&(t[oSe]=!0);for(const n in t){const a=eis(n,r);a.indexOf(s)<0&&a.push(s)}}function tis(s,t){const r={};for(const n in t)t[n].indexOf(s)>=0&&(r[n]=!0);return r}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,r=t.j[s];if(r)return r;for(let n=0;ns.ta(t,r,n,a),Au=(s,t,r,n,a)=>s.tr(t,r,n,a),qBe=(s,t,r,n,a)=>s.ts(t,r,n,a),Bn=(s,t,r,n,a)=>s.tt(t,r,n,a),kj="WORD",lSe="UWORD",rht="ASCIINUMERICAL",nht="ALPHANUMERICAL",G9="LOCALHOST",cSe="TLD",dSe="UTLD",the="SCHEME",rI="SLASH_SCHEME",tAe="NUM",uSe="WS",sAe="NL",C7="OPENBRACE",T7="CLOSEBRACE",Wme="OPENBRACKET",Kme="CLOSEBRACKET",Yme="OPENPAREN",Zme="CLOSEPAREN",Xme="OPENANGLEBRACKET",Qme="CLOSEANGLEBRACKET",Jme="FULLWIDTHLEFTPAREN",efe="FULLWIDTHRIGHTPAREN",tfe="LEFTCORNERBRACKET",sfe="RIGHTCORNERBRACKET",rfe="LEFTWHITECORNERBRACKET",nfe="RIGHTWHITECORNERBRACKET",afe="FULLWIDTHLESSTHAN",ife="FULLWIDTHGREATERTHAN",ofe="AMPERSAND",lfe="APOSTROPHE",cfe="ASTERISK",ok="AT",dfe="BACKSLASH",ufe="BACKTICK",hfe="CARET",vk="COLON",rAe="COMMA",mfe="DOLLAR",Wb="DOT",ffe="EQUALS",nAe="EXCLAMATION",Ty="HYPHEN",E7="PERCENT",pfe="PIPE",xfe="PLUS",gfe="POUND",A7="QUERY",aAe="QUOTE",aht="FULLWIDTHMIDDLEDOT",iAe="SEMI",Kb="SLASH",M7="TILDE",yfe="UNDERSCORE",iht="EMOJI",vfe="SYM";var oht=Object.freeze({__proto__:null,ALPHANUMERICAL:nht,AMPERSAND:ofe,APOSTROPHE:lfe,ASCIINUMERICAL:rht,ASTERISK:cfe,AT:ok,BACKSLASH:dfe,BACKTICK:ufe,CARET:hfe,CLOSEANGLEBRACKET:Qme,CLOSEBRACE:T7,CLOSEBRACKET:Kme,CLOSEPAREN:Zme,COLON:vk,COMMA:rAe,DOLLAR:mfe,DOT:Wb,EMOJI:iht,EQUALS:ffe,EXCLAMATION:nAe,FULLWIDTHGREATERTHAN:ife,FULLWIDTHLEFTPAREN:Jme,FULLWIDTHLESSTHAN:afe,FULLWIDTHMIDDLEDOT:aht,FULLWIDTHRIGHTPAREN:efe,HYPHEN:Ty,LEFTCORNERBRACKET:tfe,LEFTWHITECORNERBRACKET:rfe,LOCALHOST:G9,NL:sAe,NUM:tAe,OPENANGLEBRACKET:Xme,OPENBRACE:C7,OPENBRACKET:Wme,OPENPAREN:Yme,PERCENT:E7,PIPE:pfe,PLUS:xfe,POUND:gfe,QUERY:A7,QUOTE:aAe,RIGHTCORNERBRACKET:sfe,RIGHTWHITECORNERBRACKET:nfe,SCHEME:the,SEMI:iAe,SLASH:Kb,SLASH_SCHEME:rI,SYM:vfe,TILDE:M7,TLD:cSe,UNDERSCORE:yfe,UTLD:dSe,UWORD:lSe,WORD:kj,WS:uSe});const pj=/[a-z]/,KR=new RegExp("\\p{L}","u"),G_e=new RegExp("\\p{Emoji}","u"),xj=/\d/,W_e=/\s/,VBe="\r",K_e=` `,sis="️",ris="‍",Y_e="";let Mq=null,Iq=null;function nis(s=[]){const t={};ig.groups=t;const r=new ig;Mq==null&&(Mq=HBe(Zas)),Iq==null&&(Iq=HBe(Xas)),Bn(r,"'",lfe),Bn(r,"{",C7),Bn(r,"}",T7),Bn(r,"[",Wme),Bn(r,"]",Kme),Bn(r,"(",Yme),Bn(r,")",Zme),Bn(r,"<",Xme),Bn(r,">",Qme),Bn(r,"(",Jme),Bn(r,")",efe),Bn(r,"「",tfe),Bn(r,"」",sfe),Bn(r,"『",rfe),Bn(r,"』",nfe),Bn(r,"<",afe),Bn(r,">",ife),Bn(r,"&",ofe),Bn(r,"*",cfe),Bn(r,"@",ok),Bn(r,"`",ufe),Bn(r,"^",hfe),Bn(r,":",vk),Bn(r,",",rAe),Bn(r,"$",mfe),Bn(r,".",Wb),Bn(r,"=",ffe),Bn(r,"!",nAe),Bn(r,"-",Ty),Bn(r,"%",E7),Bn(r,"|",pfe),Bn(r,"+",xfe),Bn(r,"#",gfe),Bn(r,"?",A7),Bn(r,'"',aAe),Bn(r,"/",Kb),Bn(r,";",iAe),Bn(r,"~",M7),Bn(r,"_",yfe),Bn(r,"\\",dfe),Bn(r,"・",aht);const n=Au(r,xj,tAe,{[nSe]:!0});Au(n,xj,n);const a=Au(n,pj,rht,{[S7]:!0}),i=Au(n,KR,nht,{[RO]:!0}),l=Au(r,pj,kj,{[aSe]:!0});Au(l,xj,a),Au(l,pj,l),Au(a,xj,a),Au(a,pj,a);const o=Au(r,KR,lSe,{[iSe]:!0});Au(o,pj),Au(o,xj,i),Au(o,KR,o),Au(i,xj,i),Au(i,pj),Au(i,KR,i);const c=Bn(r,K_e,sAe,{[H_e]:!0}),d=Bn(r,VBe,uSe,{[H_e]:!0}),u=Au(r,W_e,uSe,{[H_e]:!0});Bn(r,Y_e,u),Bn(d,K_e,c),Bn(d,Y_e,u),Au(d,W_e,u),Bn(u,VBe),Bn(u,K_e),Au(u,W_e,u),Bn(u,Y_e,u);const m=Au(r,G_e,iht,{[sht]:!0});Bn(m,"#"),Au(m,G_e,m),Bn(m,sis,m);const f=Bn(m,ris);Bn(f,"#"),Au(f,G_e,m);const x=[[pj,l],[xj,a]],y=[[pj,null],[KR,o],[xj,i]];for(let _=0;__[0]>b[0]?1:-1);for(let _=0;_=0?N[oSe]=!0:pj.test(b)?xj.test(b)?N[S7]=!0:N[aSe]=!0:N[nSe]=!0,qBe(r,b,b,N)}return qBe(r,"localhost",G9,{ascii:!0}),r.jd=new ig(vfe),{start:r,tokens:Object.assign({groups:t},oht)}}function lht(s,t){const r=ais(t.replace(/[A-Z]/g,o=>o.toLowerCase())),n=r.length,a=[];let i=0,l=0;for(;l=0&&(m+=r[l].length,f++),d+=r[l].length,i+=r[l].length,l++;i-=m,l-=f,d-=m,a.push({t:u.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function ais(s){const t=[],r=s.length;let n=0;for(;n56319||n+1===r||(i=s.charCodeAt(n+1))<56320||i>57343?s[n]:s.slice(n,n+2);t.push(l),n+=l.length}return t}function zN(s,t,r,n,a){let i;const l=t.length;for(let o=0;o=0;)i++;if(i>0){t.push(r.join(""));for(let l=parseInt(s.substring(n,n+i),10);l>0;l--)r.pop();n+=i}else r.push(s[n]),n++}return t}const W9={defaultProtocol:"http",events:null,format:GBe,formatHref:GBe,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function oAe(s,t=null){let r=Object.assign({},W9);s&&(r=Object.assign(r,s instanceof oAe?s.o:s));const n=r.ignoreTags,a=[];for(let i=0;ir?n.substring(0,r)+"…":n},toFormattedHref(s){return s.get("formatHref",this.toHref(s.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(s=W9.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(s),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(s){return{type:this.t,value:this.toFormattedString(s),isLink:this.isLink,href:this.toFormattedHref(s),start:this.startIndex(),end:this.endIndex()}},validate(s){return s.get("validate",this.toString(),this)},render(s){const t=this,r=this.toHref(s.get("defaultProtocol")),n=s.get("formatHref",r,this),a=s.get("tagName",r,t),i=this.toFormattedString(s),l={},o=s.get("className",r,t),c=s.get("target",r,t),d=s.get("rel",r,t),u=s.getObj("attributes",r,t),m=s.getObj("events",r,t);return l.href=n,o&&(l.class=o),c&&(l.target=c),d&&(l.rel=d),u&&Object.assign(l,u),{tagName:a,attributes:l,content:i,eventListeners:m}}};function Jge(s,t){class r extends cht{constructor(a,i){super(a,i),this.t=s}}for(const n in t)r.prototype[n]=t[n];return r.t=s,r}const WBe=Jge("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),KBe=Jge("text"),iis=Jge("nl"),Pq=Jge("url",{isLink:!0,toHref(s=W9.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==G9&&s[1].t===vk}}),_y=s=>new ig(s);function ois({groups:s}){const t=s.domain.concat([ofe,cfe,ok,dfe,ufe,hfe,mfe,ffe,Ty,tAe,E7,pfe,xfe,gfe,Kb,vfe,M7,yfe]),r=[lfe,vk,rAe,Wb,nAe,E7,A7,aAe,iAe,Xme,Qme,C7,T7,Kme,Wme,Yme,Zme,Jme,efe,tfe,sfe,rfe,nfe,afe,ife],n=[ofe,lfe,cfe,dfe,ufe,hfe,mfe,ffe,Ty,C7,T7,E7,pfe,xfe,gfe,A7,Kb,vfe,M7,yfe],a=_y(),i=Bn(a,M7);Do(i,n,i),Do(i,s.domain,i);const l=_y(),o=_y(),c=_y();Do(a,s.domain,l),Do(a,s.scheme,o),Do(a,s.slashscheme,c),Do(l,n,i),Do(l,s.domain,l);const d=Bn(l,ok);Bn(i,ok,d),Bn(o,ok,d),Bn(c,ok,d);const u=Bn(i,Wb);Do(u,n,i),Do(u,s.domain,i);const m=_y();Do(d,s.domain,m),Do(m,s.domain,m);const f=Bn(m,Wb);Do(f,s.domain,m);const x=_y(WBe);Do(f,s.tld,x),Do(f,s.utld,x),Bn(d,G9,x);const y=Bn(m,Ty);Bn(y,Ty,y),Do(y,s.domain,m),Do(x,s.domain,m),Bn(x,Wb,f),Bn(x,Ty,y);const _=Bn(x,vk);Do(_,s.numeric,WBe);const b=Bn(l,Ty),j=Bn(l,Wb);Bn(b,Ty,b),Do(b,s.domain,l),Do(j,n,i),Do(j,s.domain,l);const N=_y(Pq);Do(j,s.tld,N),Do(j,s.utld,N),Do(N,s.domain,l),Do(N,n,i),Bn(N,Wb,j),Bn(N,Ty,b),Bn(N,ok,d);const C=Bn(N,vk),A=_y(Pq);Do(C,s.numeric,A);const E=_y(Pq),D=_y();Do(E,t,E),Do(E,r,D),Do(D,t,E),Do(D,r,D),Bn(N,Kb,E),Bn(A,Kb,E);const R=Bn(o,vk),F=Bn(c,vk),O=Bn(F,Kb),B=Bn(O,Kb);Do(o,s.domain,l),Bn(o,Wb,j),Bn(o,Ty,b),Do(c,s.domain,l),Bn(c,Wb,j),Bn(c,Ty,b),Do(R,s.domain,E),Bn(R,Kb,E),Bn(R,A7,E),Do(B,s.domain,E),Do(B,t,E),Bn(B,Kb,E);const K=[[C7,T7],[Wme,Kme],[Yme,Zme],[Xme,Qme],[Jme,efe],[tfe,sfe],[rfe,nfe],[afe,ife]];for(let Z=0;Z=0&&f++,a++,u++;if(f<0)a-=u,a0&&(i.push(Z_e(KBe,t,l)),l=[]),a-=f,u-=f;const x=m.t,y=r.slice(a-u,a);i.push(Z_e(x,t,y))}}return l.length>0&&i.push(Z_e(KBe,t,l)),i}function Z_e(s,t,r){const n=r[0].s,a=r[r.length-1].e,i=t.slice(n,a);return new s(i,r)}const cis=typeof console<"u"&&console&&console.warn||(()=>{}),dis="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",wd={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function uis(){return ig.groups={},wd.scanner=null,wd.parser=null,wd.tokenQueue=[],wd.pluginQueue=[],wd.customSchemes=[],wd.initialized=!1,wd}function YBe(s,t=!1){if(wd.initialized&&cis(`linkifyjs: already initialized - will not register custom scheme "${s}" ${dis}`),!/^[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`);wd.customSchemes.push([s,t])}function his(){wd.scanner=nis(wd.customSchemes);for(let s=0;s{const a=t.some(d=>d.docChanged)&&!r.doc.eq(n.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!a||i)return;const{tr:l}=n,o=Vrs(r.doc,[...t]);if(Xrs(o).forEach(({newRange:d})=>{const u=Grs(n.doc,d,x=>x.isTextblock);let m,f;if(u.length>1)m=u[0],f=n.doc.textBetween(m.pos,m.pos+m.node.nodeSize,void 0," ");else if(u.length){const x=n.doc.textBetween(d.from,d.to," "," ");if(!fis.test(x))return;m=u[0],f=n.doc.textBetween(m.pos,d.to,void 0," ")}if(m&&f){const x=f.split(mis).filter(Boolean);if(x.length<=0)return!1;const y=x[x.length-1],_=m.pos+f.lastIndexOf(y);if(!y)return!1;const b=lAe(y).map(j=>j.toObject(s.defaultProtocol));if(!xis(b))return!1;b.filter(j=>j.isLink).map(j=>({...j,from:_+j.start+1,to:_+j.end+1})).filter(j=>n.schema.marks.code?!n.doc.rangeHasMark(j.from,j.to,n.schema.marks.code):!0).filter(j=>s.validate(j.value)).filter(j=>s.shouldAutoLink(j.value)).forEach(j=>{WEe(j.from,j.to,n.doc).some(N=>N.mark.type===s.type)||l.addMark(j.from,j.to,s.type.create({href:j.href}))})}}),!!l.steps.length)return l}})}function yis(s){return new Tm({key:new Rp("handleClickLink"),props:{handleClick:(t,r,n)=>{var a,i;if(n.button!==0||!t.editable)return!1;let l=n.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(f=>f.nodeName==="A"))return!1;const c=Wut(t.state,s.type.name),d=n.target,u=(a=d==null?void 0:d.href)!==null&&a!==void 0?a:c.href,m=(i=d==null?void 0:d.target)!==null&&i!==void 0?i:c.target;return d&&u?(window.open(u,m),!0):!1}}})}function vis(s){return new Tm({key:new Rp("handlePasteLink"),props:{handlePaste:(t,r,n)=>{const{state:a}=t,{selection:i}=a,{empty:l}=i;if(l)return!1;let o="";n.content.forEach(d=>{o+=d.textContent});const c=dht(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 fC(s,t){const r=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return t&&t.forEach(n=>{const a=typeof n=="string"?n:n.scheme;a&&r.push(a)}),!s||s.replace(pis,"").match(new RegExp(`^(?:(?:${r.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const dAe=F1.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"){YBe(s);return}YBe(s.scheme,s.optionalSlashes)})},onDestroy(){uis()},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)=>!!fC(s,t.protocols),validate:s=>!!s,shouldAutoLink:s=>!!s}},addAttributes(){return{href:{default:null,parseHTML(s){return s.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class}}},parseHTML(){return[{tag:"a[href]",getAttrs:s=>{const t=s.getAttribute("href");return!t||!this.options.isAllowedUri(t,{defaultValidate:r=>!!fC(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:s}){return this.options.isAllowedUri(s.href,{defaultValidate:t=>!!fC(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Yd(this.options.HTMLAttributes,s),0]:["a",Yd(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:r}=s;return this.options.isAllowedUri(r,{defaultValidate:n=>!!fC(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().setMark(this.name,s).setMeta("preventAutolink",!0).run():!1},toggleLink:s=>({chain:t})=>{const{href:r}=s;return this.options.isAllowedUri(r,{defaultValidate:n=>!!fC(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().toggleMark(this.name,s,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run():!1},unsetLink:()=>({chain:s})=>s().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[TA({find:s=>{const t=[];if(s){const{protocols:r,defaultProtocol:n}=this.options,a=dht(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!fC(l,r),protocols:r,defaultProtocol:n}));a.length&&a.forEach(i=>t.push({text:i.value,data:{href:i.href},index:i.start}))}return t},type:this.type,getAttributes:s=>{var t;return{href:(t=s.data)===null||t===void 0?void 0:t.href}}})]},addProseMirrorPlugins(){const s=[],{protocols:t,defaultProtocol:r}=this.options;return this.options.autolink&&s.push(gis({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:n=>this.options.isAllowedUri(n,{defaultValidate:a=>!!fC(a,t),protocols:t,defaultProtocol:r}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(yis({type:this.type})),this.options.linkOnPaste&&s.push(vis({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),uAe=tp.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:s=>{const t=s.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:s=>s.textAlign?{style:`text-align: ${s.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:s=>({commands:t})=>this.options.alignments.includes(s)?this.options.types.map(r=>t.updateAttributes(r,{textAlign:s})).every(r=>r):!1,unsetTextAlign:()=>({commands:s})=>this.options.types.map(t=>s.resetAttributes(t,"textAlign")).every(t=>t),toggleTextAlign:s=>({editor:t,commands:r})=>this.options.alignments.includes(s)?t.isActive({textAlign:s})?r.unsetTextAlign():r.setTextAlign(s):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),bis=s=>{if(!s.children.length)return;const t=s.querySelectorAll("span");t&&t.forEach(r=>{var n,a;const i=r.getAttribute("style"),l=(a=(n=r.parentElement)===null||n===void 0?void 0:n.closest("span"))===null||a===void 0?void 0:a.getAttribute("style");r.setAttribute("style",`${l};${i}`)})},hAe=F1.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&bis(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",Yd(this.options.HTMLAttributes,s),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:s})=>{const{selection:t}=s;return s.doc.nodesBetween(t.from,t.to,(r,n)=>{if(r.isTextblock)return!0;r.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(i=>!!i))||s.removeMark(n,n+r.nodeSize,this.type)}),!0}}}}),_is=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,wis=Op.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",Yd(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[Kut({find:_is,type:this.type,getAttributes:s=>{const[,,t,r,n]=s;return{src:r,alt:t,title:n}}})]}});let hSe,mSe;if(typeof WeakMap<"u"){let s=new WeakMap;hSe=t=>s.get(t),mSe=(t,r)=>(s.set(t,r),r)}else{const s=[];let r=0;hSe=n=>{for(let a=0;a(r==10&&(r=0),s[r++]=n,s[r++]=a)}var Bu=class{constructor(s,t,r,n){this.width=s,this.height=t,this.map=r,this.problems=n}findCell(s){for(let t=0;t=r){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:j-C});break}const A=a+C*t;for(let E=0;En&&(i+=d.attrs.colspan)}}for(let l=0;l1&&(r=!0)}t==-1?t=i:t!=i&&(t=Math.max(t,i))}return t}function kis(s,t,r){s.problems||(s.problems=[]);const n={};for(let a=0;a0;t--)if(s.node(t).type.spec.tableRole=="row")return s.node(0).resolve(s.before(t+1));return null}function Cis(s){for(let t=s.depth;t>0;t--){const r=s.node(t).type.spec.tableRole;if(r==="cell"||r==="header_cell")return s.node(t)}return null}function q1(s){const t=s.selection.$head;for(let r=t.depth;r>0;r--)if(t.node(r).type.spec.tableRole=="row")return!0;return!1}function e0e(s){const t=s.selection;if("$anchorCell"in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if("node"in t&&t.node&&t.node.type.spec.tableRole=="cell")return t.$anchor;const r=EA(t.$head)||Tis(t.$head);if(r)return r;throw new RangeError(`No cell found around position ${t.head}`)}function Tis(s){for(let t=s.nodeAfter,r=s.pos;t;t=t.firstChild,r++){const n=t.type.spec.tableRole;if(n=="cell"||n=="header_cell")return s.doc.resolve(r)}for(let t=s.nodeBefore,r=s.pos;t;t=t.lastChild,r--){const n=t.type.spec.tableRole;if(n=="cell"||n=="header_cell")return s.doc.resolve(r-t.nodeSize)}}function fSe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function Eis(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function mAe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function uht(s,t,r){const n=s.node(-1),a=Bu.get(n),i=s.start(-1),l=a.nextCell(s.pos-i,t,r);return l==null?null:s.node(0).resolve(i+l)}function AA(s,t,r=1){const n={...s,colspan:s.colspan-r};return n.colwidth&&(n.colwidth=n.colwidth.slice(),n.colwidth.splice(t,r),n.colwidth.some(a=>a>0)||(n.colwidth=null)),n}function hht(s,t,r=1){const n={...s,colspan:s.colspan+r};if(n.colwidth){n.colwidth=n.colwidth.slice();for(let a=0;au!=r.pos-i);c.unshift(r.pos-i);const d=c.map(u=>{const m=n.nodeAt(u);if(!m)throw new RangeError(`No cell with offset ${u} found`);const f=i+u+1;return new Gdt(o.resolve(f),o.resolve(f+m.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=r}map(t,r){const n=t.resolve(r.map(this.$anchorCell.pos)),a=t.resolve(r.map(this.$headCell.pos));if(fSe(n)&&fSe(a)&&mAe(n,a)){const i=this.$anchorCell.node(-1)!=n.node(-1);return i&&this.isRowSelection()?Sj.rowSelection(n,a):i&&this.isColSelection()?Sj.colSelection(n,a):new Sj(n,a)}return Oi.between(n,a)}content(){const t=this.$anchorCell.node(-1),r=Bu.get(t),n=this.$anchorCell.start(-1),a=r.rectBetween(this.$anchorCell.pos-n,this.$headCell.pos-n),i={},l=[];for(let c=a.top;c0||b>0){let j=y.attrs;if(_>0&&(j=AA(j,0,_)),b>0&&(j=AA(j,j.colspan-b,b)),x.lefta.bottom){const j={...y.attrs,rowspan:Math.min(x.bottom,a.bottom)-Math.max(x.top,a.top)};x.top0)return!1;const n=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=r+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(n,a)==this.$headCell.node(-1).childCount}static colSelection(t,r=t){const n=t.node(-1),a=Bu.get(n),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(r.pos-i),c=t.node(0);return l.top<=o.top?(l.top>0&&(t=c.resolve(i+a.map[l.left])),o.bottom0&&(r=c.resolve(i+a.map[o.left])),l.bottom0)return!1;const l=a+this.$anchorCell.nodeAfter.attrs.colspan,o=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(l,o)==r.width}eq(t){return t instanceof Sj&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,r=t){const n=t.node(-1),a=Bu.get(n),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(r.pos-i),c=t.node(0);return l.left<=o.left?(l.left>0&&(t=c.resolve(i+a.map[l.top*a.width])),o.right0&&(r=c.resolve(i+a.map[o.top*a.width])),l.right{t.push(jx.node(n,n+r.nodeSize,{class:"selectedCell"}))}),Fu.create(s.doc,t)}function Pis({$from:s,$to:t}){if(s.pos==t.pos||s.pos=0&&!(s.after(a+1)=0&&!(t.before(i+1)>t.start(i));i--,n--);return r==n&&/row|table/.test(s.node(a).type.spec.tableRole)}function Lis({$from:s,$to:t}){let r,n;for(let a=s.depth;a>0;a--){const i=s.node(a);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){r=i;break}}for(let a=t.depth;a>0;a--){const i=t.node(a);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){n=i;break}}return r!==n&&t.parentOffset===0}function Dis(s,t,r){const n=(t||s).selection,a=(t||s).doc;let i,l;if(n instanceof Ei&&(l=n.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=cd.create(a,n.from);else if(l=="row"){const o=a.resolve(n.from+1);i=cd.rowSelection(o,o)}else if(!r){const o=Bu.get(n.node),c=n.from+1,d=c+o.map[o.width*o.height-1];i=cd.create(a,c+1,d)}}else n instanceof Oi&&Pis(n)?i=Oi.create(a,n.from):n instanceof Oi&&Lis(n)&&(i=Oi.create(a,n.$from.start(),n.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const Ris=new Rp("fix-tables");function fht(s,t,r,n){const a=s.childCount,i=t.childCount;e:for(let l=0,o=0;l{a.type.spec.tableRole=="table"&&(r=Ois(s,a,i,r))};return t?t.doc!=s.doc&&fht(t.doc,s.doc,0,n):s.doc.descendants(n),r}function Ois(s,t,r,n){const a=Bu.get(t);if(!a.problems)return n;n||(n=s.tr);const i=[];for(let c=0;c0){let x="cell";u.firstChild&&(x=u.firstChild.type.spec.tableRole);const y=[];for(let b=0;b0?-1:0;Ais(t,n,a+i)&&(i=a==0||a==t.width?null:0);for(let l=0;l0&&a0&&t.map[o-1]==c||a0?-1:0;Uis(t,n,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,u=t.width*a;d0&&a0&&m==t.map[u-t.width]){const f=r.nodeAt(m).attrs;s.setNodeMarkup(s.mapping.slice(o).map(m+n),null,{...f,rowspan:f.rowspan-1}),d+=f.colspan-1}else if(a0&&r[i]==r[i-1]||n.right0&&r[a]==r[a-s]||n.bottom0){const u=c+1+d.content.size,m=ZBe(d)?c+1:u;i.replaceWith(m+n.tableStart,u+n.tableStart,o)}i.setSelection(new cd(i.doc.resolve(c+n.tableStart))),t(i)}return!0}function QBe(s,t){const r=Pp(s.schema);return Kis(({node:n})=>r[n.type.spec.tableRole])(s,t)}function Kis(s){return(t,r)=>{const n=t.selection;let a,i;if(n instanceof cd){if(n.$anchorCell.pos!=n.$headCell.pos)return!1;a=n.$anchorCell.nodeAfter,i=n.$anchorCell.pos}else{var l;if(a=Cis(n.$from),!a)return!1;i=(l=EA(n.$from))===null||l===void 0?void 0:l.pos}if(a==null||i==null||a.attrs.colspan==1&&a.attrs.rowspan==1)return!1;if(r){let o=a.attrs;const c=[],d=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});const u=iw(t),m=t.tr;for(let x=0;x{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),n(i)}return!0}}function Zis(s){return function(t,r){if(!q1(t))return!1;if(r){const n=Pp(t.schema),a=iw(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 x=f+i.tableStart,y=l.doc.nodeAt(x);y&&l.setNodeMarkup(x,m,y.attrs)}),n(l)}return!0}}K9("row",{useDeprecatedLogic:!0});K9("column",{useDeprecatedLogic:!0});const Xis=K9("cell",{useDeprecatedLogic:!0});function Qis(s,t){if(t<0){const r=s.nodeBefore;if(r)return s.pos-r.nodeSize;for(let n=s.index(-1)-1,a=s.before();n>=0;n--){const i=s.node(-1).child(n),l=i.lastChild;if(l)return a-1-l.nodeSize;a-=i.nodeSize}}else{if(s.index()0;n--)if(r.node(n).type.spec.tableRole=="table")return t&&t(s.tr.delete(r.before(n),r.after(n)).scrollIntoView()),!0;return!1}function Lq(s,t){const r=s.selection;if(!(r instanceof cd))return!1;if(t){const n=s.tr,a=Pp(s.schema).cell.createAndFill().content;r.forEachCell((i,l)=>{i.content.eq(a)||n.replace(n.mapping.map(l+1),n.mapping.map(l+i.nodeSize-1),new pa(a,0,0))}),n.docChanged&&t(n)}return!0}function eos(s){if(s.size===0)return null;let{content:t,openStart:r,openEnd:n}=s;for(;t.childCount==1&&(r>0&&n>0||t.child(0).type.spec.tableRole=="table");)r--,n--,t=t.child(0).content;const a=t.child(0),i=a.type.spec.tableRole,l=a.type.schema,o=[];if(i=="row")for(let c=0;c=0;l--){const{rowspan:o,colspan:c}=i.child(l).attrs;for(let d=a;d=t.length&&t.push(Rn.empty),r[a]n&&(f=f.type.createChecked(AA(f.attrs,f.attrs.colspan,u+f.attrs.colspan-n),f.content)),d.push(f),u+=f.attrs.colspan;for(let x=1;xa&&(m=m.type.create({...m.attrs,rowspan:Math.max(1,a-m.attrs.rowspan)},m.content)),c.push(m)}i.push(Rn.from(c))}r=i,t=a}return{width:s,height:t,rows:r}}function ros(s,t,r,n,a,i,l){const o=s.doc.type.schema,c=Pp(o);let d,u;if(a>t.width)for(let m=0,f=0;mt.height){const m=[];for(let y=0,_=(t.height-1)*t.width;y=t.width?!1:r.nodeAt(t.map[_+y]).type==c.header_cell;m.push(b?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const f=c.row.create(null,Rn.from(m)),x=[];for(let y=t.height;y{if(!a)return!1;const i=r.selection;if(i instanceof cd)return she(r,n,Qi.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=yht(a,s,t);if(l==null)return!1;if(s=="horiz")return she(r,n,Qi.near(r.doc.resolve(i.head+t),t));{const o=r.doc.resolve(l),c=uht(o,s,t);let d;return c?d=Qi.near(c,1):t<0?d=Qi.near(r.doc.resolve(o.before(-1)),-1):d=Qi.near(r.doc.resolve(o.after(-1)),1),she(r,n,d)}}}function Rq(s,t){return(r,n,a)=>{if(!a)return!1;const i=r.selection;let l;if(i instanceof cd)l=i;else{const c=yht(a,s,t);if(c==null)return!1;l=new cd(r.doc.resolve(c))}const o=uht(l.$headCell,s,t);return o?she(r,n,new cd(l.$anchorCell,o)):!1}}function aos(s,t){const r=s.state.doc,n=EA(r.resolve(t));return n?(s.dispatch(s.state.tr.setSelection(new cd(n))),!0):!1}function ios(s,t,r){if(!q1(s.state))return!1;let n=eos(r);const a=s.state.selection;if(a instanceof cd){n||(n={width:1,height:1,rows:[Rn.from(pSe(Pp(s.state.schema).cell,r))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=Bu.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return n=sos(n,o.right-o.left,o.bottom-o.top),r$e(s.state,s.dispatch,l,o,n),!0}else if(n){const i=e0e(s.state),l=i.start(-1);return r$e(s.state,s.dispatch,l,Bu.get(i.node(-1)).findCell(i.pos-l),n),!0}else return!1}function oos(s,t){var r;if(t.button!=0||t.ctrlKey||t.metaKey)return;const n=n$e(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof cd)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&n&&(a=EA(s.state.selection.$anchor))!=null&&((r=X_e(s,t))===null||r===void 0?void 0:r.pos)!=a.pos)i(a,t),t.preventDefault();else if(!n)return;function i(c,d){let u=X_e(s,d);const m=bk.getState(s.state)==null;if(!u||!mAe(c,u))if(m)u=c;else return;const f=new cd(c,u);if(m||!s.state.selection.eq(f)){const x=s.state.tr.setSelection(f);m&&x.setMeta(bk,c.pos),s.dispatch(x)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),bk.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(bk,-1))}function o(c){const d=c,u=bk.getState(s.state);let m;if(u!=null)m=s.state.doc.resolve(u);else if(n$e(s,d.target)!=n&&(m=X_e(s,t),!m))return l();m&&i(m,d)}s.root.addEventListener("mouseup",l),s.root.addEventListener("dragstart",l),s.root.addEventListener("mousemove",o)}function yht(s,t,r){if(!(s.state.selection instanceof Oi))return null;const{$head:n}=s.state.selection;for(let a=n.depth-1;a>=0;a--){const i=n.node(a);if((r<0?n.index(a):n.indexAfter(a))!=(r<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){const l=n.before(a),o=t=="vert"?r>0?"down":"up":r>0?"right":"left";return s.endOfTextblock(o)?l:null}}return null}function n$e(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function X_e(s,t){const r=s.posAtCoords({left:t.clientX,top:t.clientY});if(!r)return null;let{inside:n,pos:a}=r;return n>=0&&EA(s.state.doc.resolve(n))||EA(s.state.doc.resolve(a))}var los=class{constructor(t,r){this.node=t,this.defaultCellMinWidth=r,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${r}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),xSe(t,this.colgroup,this.table,r),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,xSe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function xSe(s,t,r,n,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let m=0,f=0;mnew n(m,r,f)),new dos(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=b0.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{uos(l,o,s,a)},mouseleave:l=>{hos(l)},mousedown:(l,o)=>{mos(l,o,t,r)}},decorations:l=>{const o=b0.getState(l);if(o&&o.activeHandle>-1)return yos(l,o.activeHandle)},nodeViews:{}}});return i}var dos=class rhe{constructor(t,r){this.activeHandle=t,this.dragging=r}apply(t){const r=this,n=t.getMeta(b0);if(n&&n.setHandle!=null)return new rhe(n.setHandle,!1);if(n&&n.setDragging!==void 0)return new rhe(r.activeHandle,n.setDragging);if(r.activeHandle>-1&&t.docChanged){let a=t.mapping.map(r.activeHandle,-1);return fSe(t.doc.resolve(a))||(a=-1),new rhe(a,r.dragging)}return r}};function uos(s,t,r,n){if(!s.editable)return;const a=b0.getState(s.state);if(a&&!a.dragging){const i=pos(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=r?l=a$e(s,t,"left",r):c-t.clientX<=r&&(l=a$e(s,t,"right",r))}if(l!=a.activeHandle){if(!n&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=Bu.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}vht(s,l)}}}function hos(s){if(!s.editable)return;const t=b0.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&vht(s,-1)}function mos(s,t,r,n){var a;if(!s.editable)return!1;const i=(a=s.dom.ownerDocument.defaultView)!==null&&a!==void 0?a:window,l=b0.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=fos(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(b0,{setDragging:{startX:t.clientX,startWidth:c}}));function d(m){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const f=b0.getState(s.state);f!=null&&f.dragging&&(xos(s,f.activeHandle,i$e(f.dragging,m,r)),s.dispatch(s.state.tr.setMeta(b0,{setDragging:null})))}function u(m){if(!m.which)return d(m);const f=b0.getState(s.state);if(f&&f.dragging){const x=i$e(f.dragging,m,r);o$e(s,f.activeHandle,x,n)}}return o$e(s,l.activeHandle,c,n),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function fos(s,t,{colspan:r,colwidth:n}){const a=n&&n[n.length-1];if(a)return a;const i=s.domAtPos(t);let l=i.node.childNodes[i.offset].offsetWidth,o=r;if(n)for(let c=0;c{const n=s.nodes[r];n.spec.tableRole&&(t[n.spec.tableRole]=n)}),s.cached.tableNodeTypes=t,t}function jos(s,t,r,n,a){const i=wos(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!Nos(t))return!1;let r=0;const n=Gut(t.ranges[0].$from,i=>i.type.name==="table");return n==null||n.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(r+=1)}),r===t.ranges.length?(s.commands.deleteTable(),!0):!1},kos=Op.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:bos,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:s,HTMLAttributes:t}){const{colgroup:r,tableWidth:n,tableMinWidth:a}=_os(s,this.options.cellMinWidth),i=["table",Yd(this.options.HTMLAttributes,t,{style:n?`width: ${n}`:`min-width: ${a}`}),r,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},i]:i},addCommands(){return{insertTable:({rows:s=3,cols:t=3,withHeaderRow:r=!0}={})=>({tr:n,dispatch:a,editor:i})=>{const l=jos(i.schema,s,t,r);if(a){const o=n.selection.from+1;n.replaceSelectionWith(l).scrollIntoView().setSelection(Oi.near(n.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>Fis(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>zis(s,t),deleteColumn:()=>({state:s,dispatch:t})=>$is(s,t),addRowBefore:()=>({state:s,dispatch:t})=>qis(s,t),addRowAfter:()=>({state:s,dispatch:t})=>Vis(s,t),deleteRow:()=>({state:s,dispatch:t})=>Gis(s,t),deleteTable:()=>({state:s,dispatch:t})=>Jis(s,t),mergeCells:()=>({state:s,dispatch:t})=>XBe(s,t),splitCell:()=>({state:s,dispatch:t})=>QBe(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>K9("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>K9("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>Xis(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>XBe(s,t)?!0:QBe(s,t),setCellAttribute:(s,t)=>({state:r,dispatch:n})=>Yis(s,t)(r,n),goToNextCell:()=>({state:s,dispatch:t})=>e$e(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>e$e(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&pht(s),!0),setCellSelection:s=>({tr:t,dispatch:r})=>{if(r){const n=cd.create(t.doc,s.anchorCell,s.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:Oq,"Mod-Backspace":Oq,Delete:Oq,"Mod-Delete":Oq}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[cos({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],vos({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Ro(ii(s,"tableRole",t))}}}),Sos=Op.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",Yd(this.options.HTMLAttributes,s),0]}}),Cos=Op.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(n=>parseInt(n,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:s}){return["td",Yd(this.options.HTMLAttributes,s),0]}}),Tos=Op.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(n=>parseInt(n,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:s}){return["th",Yd(this.options.HTMLAttributes,s),0]}});function V1({content:s,onChange:t,placeholder:r="Enter content...",minHeight:n="150px",compact:a=!1}){const[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,u]=k.useState(!0),m=QEe({extensions:[eAe,dAe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),uAe.configure({types:["heading","paragraph"]}),hAe,wis.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}),kos.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}),Sos.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null}}}}),Cos.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}}}}),Tos.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":r},handlePaste:(_,b)=>{var N;const j=(N=b.clipboardData)==null?void 0:N.items;if(!j)return!1;for(const C of Array.from(j))if(C.type.startsWith("image/")){b.preventDefault();const A=C.getAsFile();if(!A)continue;const E=new FileReader;return E.onload=D=>{var F;const R=(F=D.target)==null?void 0:F.result;_.dispatch(_.state.tr.replaceSelectionWith(_.state.schema.nodes.image.create({src:R})))},E.readAsDataURL(A),!0}return!1}}});k.useEffect(()=>{m&&s!==m.getHTML()&&m.commands.setContent(s)},[s,m]);const f=()=>{if(!m)return;const _=m.getAttributes("link").href||"",b=m.getAttributes("link").target;c(_),u(b==="_blank"),l(!0)},x=()=>{m&&(o===""?m.chain().focus().extendMarkRange("link").unsetLink().run():m.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},y=()=>{m&&m.chain().focus().extendMarkRange("link").unsetLink().run()};return m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleHeading({level:1}).run(),className:m.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(KI,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleHeading({level:2}).run(),className:m.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(YI,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleBold().run(),className:m.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(Jk,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleItalic().run(),className:m.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(rS,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleBulletList().run(),className:m.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(Zf,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleOrderedList().run(),className:m.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(T1,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("left").run(),className:m.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(NE,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("center").run(),className:m.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(jE,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("right").run(),className:m.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx(kE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:f,className:m.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(tl,{className:"h-4 w-4"})}),m.isActive("link")&&e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:y,title:"Remove Link",children:e.jsx(tl,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().undo().run(),disabled:!m.can().undo(),title:"Undo",children:e.jsx(hS,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().redo().run(),disabled:!m.can().redo(),title:"Redo",children:e.jsx(cS,{className:"h-4 w-4"})})]}),e.jsx(ZEe,{editor:m,className:"prose prose-sm max-w-none p-3 focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror_img]:max-w-none [&_.ProseMirror_table]:border-none [&_.ProseMirror_table]:border-collapse [&_.ProseMirror_td]:border-none [&_.ProseMirror_td]:p-0 [&_.ProseMirror_td]:align-top [&_.ProseMirror_th]:border-none [&_.ProseMirror_th]:p-0 [&_.ProseMirror_tr]:border-none",style:{minHeight:n}})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"link-url",children:"URL"}),e.jsx(Ne,{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(Rr,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(ce,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(q,{type:"button",onClick:x,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var Eos=Object.defineProperty,Aos=(s,t,r)=>t in s?Eos(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,Fd=(s,t,r)=>Aos(s,typeof t!="symbol"?t+"":t,r);const bfe={x:0,y:0,width:0,height:0,unit:"px"},C6=(s,t,r)=>Math.min(Math.max(s,t),r),Mos=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),d$e=(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 Ios(s,t,r,n){const a=Yb(s,r,n);return s.width&&(a.height=a.width/t),s.height&&(a.width=a.height*t),a.y+a.height>n&&(a.height=n-a.y,a.width=a.height*t),a.x+a.width>r&&(a.width=r-a.x,a.height=a.width/t),s.unit==="%"?lk(a,r,n):a}function Pos(s,t,r){const n=Yb(s,t,r);return n.x=(t-n.width)/2,n.y=(r-n.height)/2,s.unit==="%"?lk(n,t,r):n}function lk(s,t,r){return s.unit==="%"?{...bfe,...s,unit:"%"}:{unit:"%",x:s.x?s.x/t*100:0,y:s.y?s.y/r*100:0,width:s.width?s.width/t*100:0,height:s.height?s.height/r*100:0}}function Yb(s,t,r){return s.unit?s.unit==="px"?{...bfe,...s,unit:"px"}:{unit:"px",x:s.x?s.x*t/100:0,y:s.y?s.y*r/100:0,width:s.width?s.width*t/100:0,height:s.height?s.height*r/100:0}:{...bfe,...s,unit:"px"}}function u$e(s,t,r,n,a,i=0,l=0,o=n,c=a){const d={...s};let u=Math.min(i,n),m=Math.min(l,a),f=Math.min(o,n),x=Math.min(c,a);t&&(t>1?(u=l?l*t:u,m=u/t,f=o*t):(m=i?i/t:m,u=m*t,x=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,m),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);const y=n-(d.x+d.width);y<0&&(d.x=Math.min(d.x,n-u),d.width+=y);const _=a-(d.y+d.height);if(_<0&&(d.y=Math.min(d.y,a-m),d.height+=_),d.widthf&&((r==="sw"||r=="nw")&&(d.x-=f-d.width),d.width=f),d.height>x&&((r==="nw"||r=="ne")&&(d.y-=x-d.height),d.height=x),t){const b=d.width/d.height;if(bt){const j=Math.max(d.height*t,u);(r==="sw"||r=="nw")&&(d.x-=j-d.width),d.width=j}}return d}function Los(s,t,r,n){const a={...s};return t==="ArrowLeft"?n==="nw"?(a.x-=r,a.y-=r,a.width+=r,a.height+=r):n==="w"?(a.x-=r,a.width+=r):n==="sw"?(a.x-=r,a.width+=r,a.height+=r):n==="ne"?(a.y+=r,a.width-=r,a.height-=r):n==="e"?a.width-=r:n==="se"&&(a.width-=r,a.height-=r):t==="ArrowRight"&&(n==="nw"?(a.x+=r,a.y+=r,a.width-=r,a.height-=r):n==="w"?(a.x+=r,a.width-=r):n==="sw"?(a.x+=r,a.width-=r,a.height-=r):n==="ne"?(a.y-=r,a.width+=r,a.height+=r):n==="e"?a.width+=r:n==="se"&&(a.width+=r,a.height+=r)),t==="ArrowUp"?n==="nw"?(a.x-=r,a.y-=r,a.width+=r,a.height+=r):n==="n"?(a.y-=r,a.height+=r):n==="ne"?(a.y-=r,a.width+=r,a.height+=r):n==="sw"?(a.x+=r,a.width-=r,a.height-=r):n==="s"?a.height-=r:n==="se"&&(a.width-=r,a.height-=r):t==="ArrowDown"&&(n==="nw"?(a.x+=r,a.y+=r,a.width-=r,a.height-=r):n==="n"?(a.y+=r,a.height-=r):n==="ne"?(a.y+=r,a.width-=r,a.height-=r):n==="sw"?(a.x-=r,a.width+=r,a.height+=r):n==="s"?a.height+=r:n==="se"&&(a.width+=r,a.height+=r)),a}const T6={capture:!0,passive:!1};let Dos=0;const QN=class t1 extends k.PureComponent{constructor(){super(...arguments),Fd(this,"docMoveBound",!1),Fd(this,"mouseDownOnCrop",!1),Fd(this,"dragStarted",!1),Fd(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),Fd(this,"componentRef",k.createRef()),Fd(this,"mediaRef",k.createRef()),Fd(this,"resizeObserver"),Fd(this,"initChangeCalled",!1),Fd(this,"instanceId",`rc-${Dos++}`),Fd(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),Fd(this,"onCropPointerDown",t=>{const{crop:r,disabled:n}=this.props,a=this.getBox();if(!r)return;const i=Yb(r,a.width,a.height);if(n)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const l=t.target.dataset.ord,o=!!l;let c=t.clientX,d=t.clientY,u=i.x,m=i.y;if(l){const f=t.clientX-a.x,x=t.clientY-a.y;let y=0,_=0;l==="ne"||l=="e"?(y=f-(i.x+i.width),_=x-i.y,u=i.x,m=i.y+i.height):l==="se"||l==="s"?(y=f-(i.x+i.width),_=x-(i.y+i.height),u=i.x,m=i.y):l==="sw"||l=="w"?(y=f-i.x,_=x-(i.y+i.height),u=i.x+i.width,m=i.y):(l==="nw"||l=="n")&&(y=f-i.x,_=x-i.y,u=i.x+i.width,m=i.y+i.height),c=u+a.x+y,d=m+a.y+_}this.evData={startClientX:c,startClientY:d,startCropX:u,startCropY:m,clientX:t.clientX,clientY:t.clientY,isResize:o,ord:l},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),Fd(this,"onComponentPointerDown",t=>{const{crop:r,disabled:n,locked:a,keepSelection:i,onChange:l}=this.props,o=this.getBox();if(n||a||i&&r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const c=t.clientX-o.x,d=t.clientY-o.y,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(Yb(u,o.width,o.height),lk(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),Fd(this,"onDocPointerMove",t=>{const{crop:r,disabled:n,onChange:a,onDragStart:i}=this.props,l=this.getBox();if(n||!r||!this.mouseDownOnCrop)return;t.cancelable&&t.preventDefault(),this.dragStarted||(this.dragStarted=!0,i&&i(t));const{evData:o}=this;o.clientX=t.clientX,o.clientY=t.clientY;let c;o.isResize?c=this.resizeCrop():c=this.dragCrop(),d$e(r,c)||a(Yb(c,l.width,l.height),lk(c,l.width,l.height))}),Fd(this,"onComponentKeyDown",t=>{const{crop:r,disabled:n,onChange:a,onComplete:i}=this.props;if(n)return;const l=t.key;let o=!1;if(!r)return;const c=this.getBox(),d=this.makePixelCrop(c),u=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?t1.nudgeStepLarge:t.shiftKey?t1.nudgeStepMedium:t1.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=C6(d.x,0,c.width-d.width),d.y=C6(d.y,0,c.height-d.height);const m=Yb(d,c.width,c.height),f=lk(d,c.width,c.height);a(m,f),i&&i(m,f)}}),Fd(this,"onHandlerKeyDown",(t,r)=>{const{aspect:n=0,crop:a,disabled:i,minWidth:l=0,minHeight:o=0,maxWidth:c,maxHeight:d,onChange:u,onComplete:m}=this.props,f=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 x=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?t1.nudgeStepLarge:t.shiftKey?t1.nudgeStepMedium:t1.nudgeStep,y=Yb(a,f.width,f.height),_=Los(y,t.key,x,r),b=u$e(_,n,r,f.width,f.height,l,o,c,d);if(!d$e(a,b)){const j=lk(b,f.width,f.height);u(b,j),m&&m(b,j)}}),Fd(this,"onDocPointerDone",t=>{const{crop:r,disabled:n,onComplete:a,onDragEnd:i}=this.props,l=this.getBox();this.unbindDocMove(),!(n||!r)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,i&&i(t),a&&a(Yb(r,l.width,l.height),lk(r,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),Fd(this,"onDragFocus",()=>{var t;(t=this.componentRef.current)==null||t.scrollTo(0,0)})}get document(){return document}getBox(){const t=this.mediaRef.current;if(!t)return{x:0,y:0,width:0,height:0};const{x:r,y:n,width:a,height:i}=t.getBoundingClientRect();return{x:r,y:n,width:a,height:i}}componentDidUpdate(t){const{crop:r,onComplete:n}=this.props;if(n&&!t.crop&&r){const{width:a,height:i}=this.getBox();a&&i&&n(Yb(r,a,i),lk(r,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,T6),this.document.addEventListener("pointerup",this.onDocPointerDone,T6),this.document.addEventListener("pointercancel",this.onDocPointerDone,T6),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,T6),this.document.removeEventListener("pointerup",this.onDocPointerDone,T6),this.document.removeEventListener("pointercancel",this.onDocPointerDone,T6),this.docMoveBound=!1)}getCropStyle(){const{crop:t}=this.props;if(t)return{top:`${t.y}${t.unit}`,left:`${t.x}${t.unit}`,width:`${t.width}${t.unit}`,height:`${t.height}${t.unit}`}}dragCrop(){const{evData:t}=this,r=this.getBox(),n=this.makePixelCrop(r),a=t.clientX-t.startClientX,i=t.clientY-t.startClientY;return n.x=C6(t.startCropX+a,0,r.width-n.width),n.y=C6(t.startCropY+i,0,r.height-n.height),n}getPointRegion(t,r,n,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&r?c=r==="nw"||r==="n"||r==="ne":c=o1?i?[i,i/r]:[l*r,l]:l?[l*r,l]:[i,i/r]}resizeCrop(){const{evData:t}=this,{aspect:r=0,maxWidth:n,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,r,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),u=t.ord||d;let m=t.clientX-t.startClientX,f=t.clientY-t.startClientY;(l&&u==="nw"||u==="w"||u==="sw")&&(m=Math.min(m,-l)),(o&&u==="nw"||u==="n"||u==="ne")&&(f=Math.min(f,-o));const x={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(x.x=t.startCropX,x.width=m,r?(x.height=x.width/r,x.y=t.startCropY-x.height):(x.height=Math.abs(f),x.y=t.startCropY-x.height)):d==="se"?(x.x=t.startCropX,x.y=t.startCropY,x.width=m,r?x.height=x.width/r:x.height=f):d==="sw"?(x.x=t.startCropX+m,x.y=t.startCropY,x.width=Math.abs(m),r?x.height=x.width/r:x.height=f):d==="nw"&&(x.x=t.startCropX+m,x.width=Math.abs(m),r?(x.height=x.width/r,x.y=t.startCropY-x.height):(x.height=Math.abs(f),x.y=t.startCropY+f));const y=u$e(x,r,d,i.width,i.height,l,o,n,a);return r||t1.xyOrds.indexOf(u)>-1?c=y:t1.xOrds.indexOf(u)>-1?(c.x=y.x,c.width=y.width):t1.yOrds.indexOf(u)>-1&&(c.y=y.y,c.height=y.height),c.x=C6(c.x,0,i.width-c.width),c.y=C6(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=t1.defaultProps.ariaLabels,disabled:r,locked:n,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"},!r&&!n&&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 r={...bfe,...this.props.crop||{}};return Yb(r,t.width,t.height)}render(){const{aspect:t,children:r,circularCrop:n,className:a,crop:i,disabled:l,locked:o,style:c,ruleOfThirds:d}=this.props,{cropIsActive:u,newCropIsBeingDrawn:m}=this.state,f=i?this.renderCropSelection():null,x=Mos("ReactCrop",a,u&&"ReactCrop--active",l&&"ReactCrop--disabled",o&&"ReactCrop--locked",m&&"ReactCrop--new-crop",i&&t&&"ReactCrop--fixed-aspect",i&&n&&"ReactCrop--circular-crop",i&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&i&&!i.width&&!i.height&&"ReactCrop--invisible-crop",n&&"ReactCrop--no-animate");return Ct.createElement("div",{ref:this.componentRef,className:x,style:c},Ct.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),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"}),n?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,f)}};Fd(QN,"xOrds",["e","w"]),Fd(QN,"yOrds",["n","s"]),Fd(QN,"xyOrds",["nw","ne","se","sw"]),Fd(QN,"nudgeStep",1),Fd(QN,"nudgeStepMedium",10),Fd(QN,"nudgeStepLarge",100),Fd(QN,"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 Ros=QN;function Oos(s,t,r){return Pos(Ios({unit:"%",width:90},r,s,t),s,t)}const fAe=({open:s,onClose:t,imageSrc:r,onCropComplete:n,aspectRatio:a=1})=>{const i=k.useRef(null),[l,o]=k.useState(),[c,d]=k.useState(),[u,m]=k.useState(1),[f,x]=k.useState(0),y=k.useCallback(j=>{const{width:N,height:C}=j.currentTarget;o(Oos(N,C,a))},[a]),_=k.useCallback(async()=>{const j=i.current;if(!j||!c)return;const N=document.createElement("canvas"),C=N.getContext("2d");if(!C)return;const A=j.naturalWidth/j.width,E=j.naturalHeight/j.height,D=400;N.width=D,N.height=D,C.imageSmoothingQuality="high";const R=c.x*A,F=c.y*E,O=c.width*A,B=c.height*E,K=f*Math.PI/180,Z=N.width/2,Q=N.height/2;return C.save(),C.translate(Z,Q),C.rotate(K),C.scale(u,u),C.translate(-Z,-Q),C.drawImage(j,R,F,O,B,0,0,D,D),C.restore(),new Promise((W,te)=>{N.toBlob(ne=>{ne?W(ne):te(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,f]),b=async()=>{try{const j=await _();j&&(n(j),t())}catch(j){console.error("Error cropping image:",j)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(_s,{children:e.jsx(bs,{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(Ros,{crop:l,onChange:(j,N)=>o(N),onComplete:j=>d(j),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:r,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${f}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(hP,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(nf,{value:[u],min:.5,max:3,step:.1,onValueChange:([j])=>m(j),className:"flex-1"}),e.jsx(mS,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(qE,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(nf,{value:[f],min:-180,max:180,step:1,onValueChange:([j])=>x(j),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[f,"°"]})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(q,{onClick:b,children:"Save Photo"})]})]})})},Fos=()=>{const{user:s}=Cs(),{toast:t}=Ba(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(null);k.useEffect(()=>{s&&c()},[s]);const c=async()=>{n(!0);try{const{data:m}=await U.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();m&&o({status:m.subscription_status||"none",productId:m.subscription_product_id,endDate:m.subscription_end_date,isGrandfathered:m.is_grandfathered||!1})}catch(m){console.error("Error loading subscription:",m)}finally{n(!1)}},d=async()=>{i(!0);try{const{data:{session:m}}=await U.auth.getSession();if(!m)throw new Error("Not authenticated");const{data:f,error:x}=await U.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${m.access_token}`}});if(x)throw x;f!=null&&f.url&&window.open(f.url,"_blank")}catch(m){console.error("Error opening customer portal:",m),t({title:"Error",description:m.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(Xe,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(Xe,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(Xe,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(Xe,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(Xe,{variant:"secondary",children:"Canceled"});default:return e.jsx(Xe,{variant:"outline",children:"No Subscription"})}};return r?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(S0,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(S0,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Ur,{children:"Manage your subscription and billing"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Status"}),e.jsx("div",{className:"mt-1",children: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(q,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(un,{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."})]})]})},zos=()=>{const{user:s}=Cs(),t=qr(),{toast:r}=Ba(),[n]=ic(),a=n.get("setup")==="true",i=n.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=pct(),[m,f]=k.useState(!1),[x,y]=k.useState(""),[_,b]=k.useState(!1),[j,N]=k.useState(!1),[C,A]=k.useState(""),[E,D]=k.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[R,F]=k.useState(!1),[O,B]=k.useState(!1),[K,Z]=k.useState(!1),[Q,W]=k.useState({newPassword:"",confirmPassword:""});k.useEffect(()=>{s&&te()},[s]),k.useEffect(()=>{i&&s&&setTimeout(()=>{var de;(de=document.getElementById("change-password-section"))==null||de.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const te=async()=>{var de,fe,je,xe;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:Ee,error:Me}=await U.from("profiles").select("name, email, phone, digest_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Me)throw console.error("Profile query error:",Me),Me;if(Ee){console.log("Profile loaded successfully:",Ee);const Ie=((de=Ee.brokerages)==null?void 0:de.name)||"";F(!!Ee.brokerage_id),D({name:Ee.name||"",email:Ee.email||"",phone:Ee.phone||"",title:Ee.title||"",bio:Ee.bio||"",areas_served:Ee.areas_served||"",years_experience:((fe=Ee.years_experience)==null?void 0:fe.toString())||"",brokerage_name:Ee.brokerage_id?Ie:Ee.brokerage_name||"",instagram_url:Ee.instagram_url||"",facebook_url:Ee.facebook_url||"",linkedin_url:Ee.linkedin_url||"",email_signature:Ee.email_signature||"",use_email_signature:Ee.use_email_signature||!1}),B(Ee.digest_opt_out||!1)}else console.warn("No profile found for user"),D({name:((je=s.user_metadata)==null?void 0:je.name)||((xe=s.email)==null?void 0:xe.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:Oe}=await U.storage.from("avatars").list(`${s.id}`);if(Oe&&Oe.length>0){const{data:Ie}=U.storage.from("avatars").getPublicUrl(`${s.id}/${Oe[0].name}`);y(Ie.publicUrl)}}catch(Ee){console.error("Error loading profile:",Ee),r({title:"Error",description:Ee.message||"Failed to load profile",variant:"destructive"})}},ne=de=>{var xe;const fe=(xe=de.target.files)==null?void 0:xe[0];if(!fe)return;const je=new FileReader;je.onloadend=()=>{A(je.result),N(!0)},je.readAsDataURL(fe),de.target.value=""},ae=async de=>{if(s){b(!0);try{const{data:fe}=await U.storage.from("avatars").list(`${s.id}`);fe&&fe.length>0&&await U.storage.from("avatars").remove(fe.map(Ie=>`${s.id}/${Ie.name}`));const xe=`${s.id}/avatar.jpg`,{error:Ee}=await U.storage.from("avatars").upload(xe,de,{upsert:!0,contentType:"image/jpeg"});if(Ee)throw Ee;const{data:Me}=U.storage.from("avatars").getPublicUrl(xe),Oe=Me.publicUrl;y(`${Oe}?t=${Date.now()}`),await U.from("profiles").update({avatar_url:Oe}).eq("id",s.id),r({title:"Success",description:"Profile photo updated successfully"})}catch(fe){console.error("Error uploading avatar:",fe),r({title:"Error",description:fe.message||"Failed to upload photo",variant:"destructive"})}finally{b(!1)}}},ue=async()=>{if(!E.name.trim()||!E.email.trim()){r({title:"Error",description:"Name and email are required",variant:"destructive"});return}f(!0);try{const{error:de}=await U.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,...R?{}:{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(de)throw de;r({title:"Success",description:"Profile updated successfully"})}catch(de){console.error("Error updating profile:",de),r({title:"Error",description:de.message||"Failed to update profile",variant:"destructive"})}finally{f(!1)}},me=async()=>{if(!Q.newPassword){r({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(Q.newPassword.length<6){r({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(Q.newPassword!==Q.confirmPassword){r({title:"Error",description:"Passwords do not match",variant:"destructive"});return}f(!0);try{const{error:de}=await U.auth.updateUser({password:Q.newPassword});if(de)throw de;r({title:"Success",description:"Password updated successfully"}),W({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(de){console.error("Error updating password:",de),r({title:"Error",description:de.message||"Failed to update password",variant:"destructive"})}finally{f(!1)}};return e.jsx(ws,{title:a?"Complete Your Profile":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"mx-auto max-w-4xl",children:[!a&&!i&&e.jsx("div",{className:"mb-6",children:e.jsxs(q,{variant:"outline",onClick:()=>{var de;(de=document.getElementById("change-password-section"))==null||de.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(PE,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Profile Photo"}),e.jsx(Ur,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Pe,{className:"flex items-center gap-6",children:[e.jsxs(Wn,{className:"h-24 w-24",children:[e.jsx(Xa,{src:x}),e.jsx(Kn,{className:"text-2xl",children:E.name.split(" ").map(de=>de[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:ne,disabled:_}),e.jsxs(q,{variant:"outline",onClick:()=>{var de;return(de=document.getElementById("avatar-upload"))==null?void 0:de.click()},disabled:_,children:[e.jsx(ka,{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(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Personal Information"}),e.jsx(Ur,{children:"Update your profile details"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",value:E.name,onChange:de=>D({...E,name:de.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",value:E.email,onChange:de=>D({...E,email:de.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"phone",children:"Phone Number"}),e.jsx(Ne,{id:"phone",type:"tel",value:E.phone,onChange:de=>D({...E,phone:de.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(ce,{htmlFor:"title",children:"Job Title"}),e.jsx(Ne,{id:"title",value:E.title,onChange:de=>D({...E,title:de.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"bio",children:"Bio"}),e.jsx(pr,{id:"bio",value:E.bio,onChange:de=>D({...E,bio:de.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(ce,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(Ne,{id:"areas_served",value:E.areas_served,onChange:de=>D({...E,areas_served:de.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(Ne,{id:"years_experience",type:"number",min:"0",value:E.years_experience,onChange:de=>D({...E,years_experience:de.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{htmlFor:"brokerage_name",children:["Brokerage ",R&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(Ne,{id:"brokerage_name",value:E.brokerage_name,onChange:de=>D({...E,brokerage_name:de.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:R,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:R?"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(ce,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(Ne,{value:E.linkedin_url,onChange:de=>D({...E,linkedin_url:de.target.value}),placeholder:"LinkedIn URL"}),e.jsx(Ne,{value:E.instagram_url,onChange:de=>D({...E,instagram_url:de.target.value}),placeholder:"Instagram URL"}),e.jsx(Ne,{value:E.facebook_url,onChange:de=>D({...E,facebook_url:de.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(q,{onClick:ue,disabled:m,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(t_,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Ur,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Use email signature in all emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:E.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(Rr,{checked:E.use_email_signature,onCheckedChange:de=>D({...E,use_email_signature:de})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Signature"}),e.jsx(V1,{content:E.email_signature,onChange:de=>D({...E,email_signature:de}),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(q,{onClick:ue,disabled:m,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsxs(ke,{id:"change-password-section",children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:a?"Set Your Password":"Change Password"}),e.jsx(Ur,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"newPassword",children:"New Password"}),e.jsx(Ne,{id:"newPassword",type:"password",value:Q.newPassword,onChange:de=>W({...Q,newPassword:de.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(Ne,{id:"confirmPassword",type:"password",value:Q.confirmPassword,onChange:de=>W({...Q,confirmPassword:de.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(q,{onClick:me,disabled:m,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(q,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[o?e.jsx(ym,{className:"h-5 w-5"}):e.jsx(b_,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Ur,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Pe,{children:l?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(Rr,{checked:o,onCheckedChange:de=>{de?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(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[O?e.jsx(eP,{className:"h-5 w-5"}):e.jsx(Ks,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Ur,{children:"Manage your email subscription settings"})]}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:O?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(Rr,{checked:!O,onCheckedChange:async de=>{Z(!0);try{const{error:fe}=await U.from("profiles").update({digest_opt_out:!de}).eq("id",s==null?void 0:s.id);if(fe)throw fe;B(!de),r({title:de?"Subscribed":"Unsubscribed",description:de?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(fe){r({title:"Error",description:fe.message||"Failed to update preference",variant:"destructive"})}finally{Z(!1)}},disabled:K})]})})]}),e.jsx(CJt,{}),e.jsx(Fos,{})]}),e.jsx(fAe,{open:j,onClose:()=>N(!1),imageSrc:C,onCropComplete:ae,aspectRatio:1})]})})};var Bos="AspectRatio",bht=k.forwardRef((s,t)=>{const{ratio:r=1/1,style:n,...a}=s;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/r}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(Yn.div,{...a,ref:t,style:{...n,position:"absolute",top:0,right:0,bottom:0,left:0}})})});bht.displayName=Bos;var $os=bht;const Uos=$os;function qos(){const{user:s}=Cs(),t=is(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),{data:l,isLoading:o}=pt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:_}=await U.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(_)throw _;return y},enabled:!!s&&a}),c=Mt({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:b}=await U.from("profiles").update({calendar_token:_}).eq("id",s==null?void 0:s.id);if(b)throw b;return _},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),he.success("Calendar subscription URL generated!")},onError:y=>{he.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),n(!0),he.success("Calendar URL copied to clipboard!"),setTimeout(()=>n(!1),2e3))},m=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},f=()=>{if(d){const y=d.replace("https://","webcal://"),_=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(y)}`;window.open(_,"_blank")}},x=()=>{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(vs,{open:a,onOpenChange:i,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:"gap-2",children:[e.jsx(vn,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(an,{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(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):d?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Your Calendar URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(q,{variant:"outline",size:"icon",onClick:u,children:r?e.jsx(la,{className:"h-4 w-4 text-green-500"}):e.jsx(si,{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(q,{variant:"outline",className:"w-full justify-start gap-2",onClick:m,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),"Add to Apple Calendar",e.jsx(un,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(q,{variant:"outline",className:"w-full justify-start gap-2",onClick:f,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(un,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(q,{variant:"outline",className:"w-full justify-start gap-2",onClick:x,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(un,{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(q,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vn,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const Vos={first_timer:fa,regular:c2,dedicated:Uc,veteran:wo,streak_master:ld,century:wo},Hos={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 h$e(s){return s===1?e.jsx(wo,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(c2,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Uc,{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 _ht({showUserStats:s=!0,compact:t=!1,brokerageId:r,title:n="Event Leaderboard"}){const{user:a}=Cs(),{data:i,isLoading:l}=Uct(t?5:10,r),{data:o}=qct(a==null?void 0:a.id),{data:c}=Hct(a==null?void 0:a.id),{data:d}=Vct(a==null?void 0:a.id);return l?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(wo,{className:"h-5 w-5 text-yellow-500"}),n]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,m)=>e.jsx(dr,{className:"h-12 w-full"},m))})})]}):e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(wo,{className:"h-5 w-5 text-yellow-500"}),n]})}),e.jsxs(Pe,{children:[s&&o&&e.jsxs("div",{className:"mb-4 p-3 rounded-lg bg-primary/5 border border-primary/10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Your Stats"}),c&&e.jsxs(Xe,{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(ld,{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 m=Vos[u.badge_type]||fa;return e.jsxs(Xe,{variant:"outline",className:`text-xs ${Hos[u.badge_type]||""}`,title:u.badge_description||"",children:[e.jsx(m,{className:"h-3 w-3 mr-1"}),u.badge_name]},u.id)}),d.length>4&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(ta,{defaultValue:"points",className:"w-full",children:[e.jsxs(ea,{className:"w-full mb-3",children:[e.jsx(rs,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(rs,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(fs,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,m)=>{var f,x,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":""} ${m===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:h$e(m+1)}),e.jsx(Wn,{className:"h-8 w-8",children:e.jsx(Kn,{className:"text-xs",children:((x=(f=u.profile)==null?void 0:f.name)==null?void 0:x.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(fs,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,m)=>m.total_events_attended-u.total_events_attended).map((u,m)=>{var f,x,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":""} ${m===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:h$e(m+1)}),e.jsx(Wn,{className:"h-8 w-8",children:e.jsx(Kn,{className:"text-xs",children:((x=(f=u.profile)==null?void 0:f.name)==null?void 0:x.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 Gos(){const s=qr(),{user:t,isAdmin:r}=Cs(),n=is(),{data:a,isLoading:i}=pt({queryKey:["public-events"],queryFn:async()=>{const{data:_,error:b}=await U.from("events").select("*").order("event_date",{ascending:!0});if(b)throw b;return _}}),{data:l}=pt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:_,error:b}=await U.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(b)throw b;return _},enabled:!!t}),{data:o}=pt({queryKey:["event-registration-counts"],queryFn:async()=>{let _=[],b=0;const j=1e3;for(;;){const{data:C,error:A}=await U.from("event_registrations").select("event_id").range(b,b+j-1);if(A)throw A;if(!C||C.length===0||(_=_.concat(C),C.length{N[C.event_id]=(N[C.event_id]||0)+1}),N}}),c=Mt({mutationFn:async _=>{await U.auth.refreshSession();const{data:b,error:j}=await U.functions.invoke("zoom-register",{body:{event_id:_}});if(j)throw j;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:_=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),_!=null&&_.join_url?he.success("Successfully registered! You'll receive a Zoom confirmation email."):he.success("Successfully registered for the event!")},onError:_=>{he.error("Failed to register: "+_.message)}}),d=Mt({mutationFn:async _=>{const{data:b,error:j}=await U.functions.invoke("zoom-unregister",{body:{event_id:_}});if(j)throw j;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),he.success("Registration cancelled and removed from Zoom")},onError:_=>{he.error("Failed to cancel: "+_.message)}}),u=_=>l==null?void 0:l.some(b=>b.event_id===_),m=_=>{const b=l==null?void 0:l.find(j=>j.event_id===_);return b==null?void 0:b.zoom_join_url},f=_=>_.capacity?((o==null?void 0:o[_.id])||0)>=_.capacity:!1,x=(a==null?void 0:a.filter(_=>_P(_.event_date)!=="ended"))||[],y=(a==null?void 0:a.filter(_=>_P(_.event_date)==="ended"))||[];return e.jsx(ws,{title:"Events",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Events"}),e.jsx("p",{className:"text-muted-foreground",children:"Browse and register for upcoming events"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(qos,{}),r&&e.jsx(q,{variant:"outline",onClick:()=>s("/admin/events"),children:"Manage Events"})]})]}),e.jsxs("div",{className:`grid grid-cols-1 ${r?"lg:grid-cols-3":""} gap-6`,children:[e.jsxs("div",{className:r?"lg:col-span-2":"",children:[i?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):x.length===0?e.jsx(ke,{className:"text-center py-12",children:e.jsx(Pe,{children:e.jsx("p",{className:"text-muted-foreground",children:"No upcoming events at the moment. Check back soon!"})})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:x.map(_=>{const b=_P(_.event_date),j=yEe(_.event_date),N=b==="live",C=b==="starting_soon";return e.jsxs(ke,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${N?"border-red-500 ring-2 ring-red-500/20":C?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${_.id}`),children:[j&&e.jsxs("div",{className:`${N?"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"})]}),N?e.jsxs(e.Fragment,{children:[e.jsx(h2,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),_.image_url&&e.jsx(Uos,{ratio:3/2,className:"overflow-hidden",children:e.jsx("img",{src:_.image_url,alt:_.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"})}),e.jsxs(Pt,{children:[e.jsx(Dt,{className:"line-clamp-2",children:_.title}),_.description&&e.jsx(Ur,{className:"line-clamp-2",children:_.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Pe,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(vn,{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(jn,{className:"h-4 w-4"}),D9(new Date(_.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Dr,{className:"h-4 w-4"}),(o==null?void 0:o[_.id])||0," registered",_.capacity&&` / ${_.capacity} spots`]})]}),e.jsx(y7,{className:"flex gap-2",onClick:A=>A.stopPropagation(),children:u(_.id)?e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"outline",className:"flex-1",onClick:()=>d.mutate(_.id),disabled:d.isPending,children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(q,{className:"flex-1",onClick:()=>window.open(m(_.id)||_.zoom_link,"_blank"),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(q,{className:"w-full",onClick:()=>c.mutate(_.id),disabled:c.isPending||f(_),children:f(_)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(la,{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(ke,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${_.id}`),children:e.jsxs(Pt,{children:[e.jsx(Dt,{className:"text-base line-clamp-1",children:_.title}),e.jsx(Ur,{children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(_.event_date))})]})},_.id))})]})]}),r&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(_ht,{showUserStats:!0})})]})]})})}const Q_e=[{value:"all",label:"All Roles",icon:Dr},{value:"newest",label:"Newest Members",icon:jn},{value:"brokerage_manager",label:"Brokerage Managers",icon:s7},{value:"admin",label:"Admins",icon:Oh}];function Wos({open:s,onOpenChange:t,resourceType:r,resourceId:n,resourceTitle:a}){var Le,$e;const{user:i,isAdmin:l,isBrokerageManager:o}=Cs(),[c,d]=k.useState([]),[u,m]=k.useState([]),[f,x]=k.useState([]),[y,_]=k.useState([]),[b,j]=k.useState(""),[N,C]=k.useState(""),[A,E]=k.useState(""),[D,R]=k.useState(!1),[F,O]=k.useState(!1),[B,K]=k.useState("agents"),[Z,Q]=k.useState("all"),[W,te]=k.useState({}),ne=l||o;k.useEffect(()=>{s&&i&&(l?ae():ue())},[s,i,l]),k.useEffect(()=>{s||(x([]),_([]),j(""),C(""),E(""),K("agents"),Q("all"))},[s]);const ae=async()=>{if(i){R(!0);try{const{data:ve,error:Qe}=await U.from("brokerages").select("id, name").order("name");if(Qe)throw Qe;const we=1e3,nt={};let Se=0,Ge=!0;for(;Ge;){const{data:qe,error:et}=await U.from("profiles").select("brokerage_id").range(Se*we,(Se+1)*we-1);if(et)throw et;qe==null||qe.forEach(Ze=>{Ze.brokerage_id&&(nt[Ze.brokerage_id]=(nt[Ze.brokerage_id]||0)+1)}),Ge=(qe==null?void 0:qe.length)===we,Se++}m((ve==null?void 0:ve.map(qe=>({...qe,agent_count:nt[qe.id]||0})))||[]);const We=[];for(Se=0,Ge=!0;Ge;){const{data:qe,error:et}=await U.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Se*we,(Se+1)*we-1);if(et)throw et;qe&&We.push(...qe),Ge=(qe==null?void 0:qe.length)===we,Se++}const Ce={};for(Se=0,Ge=!0;Ge;){const{data:qe,error:et}=await U.from("user_roles").select("user_id, role").range(Se*we,(Se+1)*we-1);if(et)throw et;qe==null||qe.forEach(Ze=>{Ce[Ze.user_id]||(Ce[Ze.user_id]=[]),Ce[Ze.user_id].push(Ze.role)}),Ge=(qe==null?void 0:qe.length)===we,Se++}te(Ce),d(We.map(qe=>{var et;return{id:qe.id,name:qe.name,email:qe.email,brokerage_name:((et=qe.brokerages)==null?void 0:et.name)||"No Brokerage",roles:Ce[qe.id]||[],created_at:qe.created_at}}))}catch(ve){console.error("Error loading data:",ve),he.error("Failed to load agents and brokerages")}finally{R(!1)}}},ue=async()=>{if(i){R(!0);try{const{data:ve}=await U.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(ve!=null&&ve.brokerage_id)){he.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Qe,error:we}=await U.from("profiles").select("id, name, email").eq("brokerage_id",ve.brokerage_id).neq("id",i.id).order("name");if(we)throw we;d(Qe||[])}catch(ve){console.error("Error loading agents:",ve),he.error("Failed to load agents")}finally{R(!1)}}},me=c.filter(ve=>{var we;const Qe=ve.name.toLowerCase().includes(b.toLowerCase())||ve.email.toLowerCase().includes(b.toLowerCase())||((we=ve.brokerage_name)==null?void 0:we.toLowerCase().includes(b.toLowerCase()));if(l&&Z!=="all"&&Z!=="newest"){const nt=W[ve.id]||[];return Qe&&nt.includes(Z)}return Qe}).sort((ve,Qe)=>Z==="newest"?(Qe.created_at||"").localeCompare(ve.created_at||""):0),de=u.filter(ve=>ve.name.toLowerCase().includes(N.toLowerCase())),fe=()=>{f.length===me.length?x([]):x(me.map(ve=>ve.id))},je=()=>{y.length===de.length?_([]):_(de.map(ve=>ve.id))},xe=ve=>{if(!ne){x([ve]);return}x(Qe=>Qe.includes(ve)?Qe.filter(we=>we!==ve):[...Qe,ve])},Ee=ve=>{_(Qe=>Qe.includes(ve)?Qe.filter(we=>we!==ve):[...Qe,ve])},Me=async()=>{if(!(f.length>0||y.length>0)){he.error("Please select at least one agent or brokerage to share with");return}O(!0);try{const{data:Qe,error:we}=await U.functions.invoke("send-share-notification",{body:{recipientIds:f,brokerageIds:y,resourceType:r,resourceId:n,resourceTitle:a,message:A.trim()||void 0}});if(we)throw we;const nt=(Qe==null?void 0:Qe.sharesCreated)||f.length;he.success(`Shared with ${nt} agent${nt!==1?"s":""}`),t(!1)}catch(Qe){console.error("Error sharing resource:",Qe),he.error("Failed to share resource")}finally{O(!1)}},Oe=ve=>ve.split(" ").map(Qe=>Qe[0]).join("").toUpperCase().slice(0,2),Ie=ve=>{const Qe=W[ve]||[];return Qe.includes("admin")?e.jsx(Xe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Qe.includes("brokerage_manager")?e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},ze=f.length+y.length,Ve=Z!=="all"&&Z!=="newest"?me.length:null;return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(_s,{className:"flex-shrink-0",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(hn,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(an,{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(ta,{value:B,onValueChange:K,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ea,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(rs,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),f.length>0&&e.jsx(Xe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:f.length})]}),e.jsxs(rs,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),y.length>0&&e.jsx(Xe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:y.length})]})]}),e.jsxs(fs,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or brokerage...",value:b,onChange:ve=>j(ve.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:Z,onValueChange:Q,children:[e.jsxs(Ps,{className:"w-[180px]",children:[e.jsx(C1,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(Fs,{placeholder:"Filter by role"})]}),e.jsx(Ls,{children:Q_e.map(ve=>e.jsx(lt,{value:ve.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve.icon,{className:"h-4 w-4"}),e.jsx("span",{children:ve.label})]})},ve.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:fe,className:"text-xs h-8",disabled:me.length===0,children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1.5"}),f.length===me.length&&me.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Ve!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Ve," ",(Le=Q_e.find(ve=>ve.value===Z))==null?void 0:Le.label]}),e.jsxs("span",{className:"font-medium",children:[f.length," selected"]})]})]}),e.jsx(ui,{className:"h-[300px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(ls,{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-[200px] text-muted-foreground",children:[e.jsx(Dr,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:Z!=="all"?`No ${($e=Q_e.find(ve=>ve.value===Z))==null?void 0:$e.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:me.map(ve=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${f.includes(ve.id)?"bg-accent":""}`,onClick:()=>xe(ve.id),children:[e.jsx(Ri,{checked:f.includes(ve.id),onCheckedChange:()=>xe(ve.id),className:"flex-shrink-0"}),e.jsx(Wn,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Kn,{className:"text-xs bg-primary/10 text-primary",children:Oe(ve.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:ve.name}),Ie(ve.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ve.email,ve.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",ve.brokerage_name]})]})]})]},ve.id))})})]}),e.jsxs(fs,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search brokerages...",value:N,onChange:ve=>C(ve.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:je,className:"text-xs h-8",disabled:de.length===0,children:[e.jsx(Ga,{className:"h-3.5 w-3.5 mr-1.5"}),y.length===de.length&&de.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(ui,{className:"h-[250px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):de.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Ga,{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:de.map(ve=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${y.includes(ve.id)?"bg-accent":""}`,onClick:()=>Ee(ve.id),children:[e.jsx(Ri,{checked:y.includes(ve.id),onCheckedChange:()=>Ee(ve.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(Ga,{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:ve.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ve.agent_count," agent",ve.agent_count!==1?"s":""]})]})]},ve.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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:b,onChange:ve=>j(ve.target.value),className:"pl-9"})]}),ne&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:fe,className:"text-xs h-8",disabled:me.length===0,children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1.5"}),f.length===me.length&&me.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[f.length," selected"]})]}),e.jsx(ui,{className:"h-[300px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(ls,{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-[200px] text-muted-foreground",children:[e.jsx(Dr,{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:me.map(ve=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${f.includes(ve.id)?"bg-accent":""}`,onClick:()=>xe(ve.id),children:[e.jsx(Ri,{checked:f.includes(ve.id),onCheckedChange:()=>xe(ve.id),className:"flex-shrink-0"}),e.jsx(Wn,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Kn,{className:"text-xs bg-primary/10 text-primary",children:Oe(ve.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ve.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ve.email})]})]},ve.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(ce,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(pr,{id:"message",placeholder:"I thought you might find this useful...",value:A,onChange:ve=>E(ve.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{onClick:Me,disabled:ze===0||F,children:F?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function L8({resourceType:s,resourceId:t,resourceTitle:r,variant:n="outline",size:a="sm",className:i=""}){const[l,o]=k.useState(!1),{user:c}=Cs();return c?e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:n,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Ec,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(Wos,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:r})]}):null}function Kos(){const{eventId:s}=xo(),t=qr(),{user:r}=Cs(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(0),[d,u]=k.useState(!0),[m,f]=k.useState(!1);k.useEffect(()=>{s&&x()},[s,r]);const x=async()=>{try{const{data:C,error:A}=await U.from("events").select("*").eq("id",s).single();if(A)throw A;a(C);const{count:E}=await U.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(E||0),r){const{data:D}=await U.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",r.id).maybeSingle();l(D)}}catch(C){console.error("Error loading event:",C),he.error("Failed to load event"),t("/events")}finally{u(!1)}},y=async()=>{if(!(!r||!n)){f(!0);try{const{error:C}=await U.auth.refreshSession();if(C){console.error("Session refresh failed:",C),he.error("Your session has expired. Please log in again.");return}if(i){const{error:A}=await U.functions.invoke("zoom-unregister",{body:{event_id:n.id}});if(A)throw A;he.success("Successfully cancelled registration"),l(null),c(E=>E-1)}else{const{data:A,error:E}=await U.functions.invoke("zoom-register",{body:{event_id:n.id}});if(E)throw E;he.success("Successfully registered for event!"),l({id:A.registration_id,zoom_join_url:A.zoom_join_url}),c(D=>D+1)}}catch(C){console.error("Registration error:",C),he.error(i?"Failed to cancel registration":"Failed to register for event")}finally{f(!1)}}},_=C=>{var A,E,D;if(C.includes("iframe.mediadelivery.net")||C.includes("video.bunnycdn.com")){const R=C.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(R)return`https://iframe.mediadelivery.net/embed/${R[1]}/${R[2]}?autoplay=false&preload=true`}if(C.includes("youtube.com")||C.includes("youtu.be")){const R=C.includes("youtu.be")?(A=C.split("youtu.be/")[1])==null?void 0:A.split("?")[0]:(E=C.split("v=")[1])==null?void 0:E.split("&")[0];if(R)return`https://www.youtube.com/embed/${R}`}if(C.includes("vimeo.com")){const R=(D=C.split("vimeo.com/")[1])==null?void 0:D.split("?")[0];if(R)return`https://player.vimeo.com/video/${R}`}return C};if(d)return e.jsx(ws,{title:"Event",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!n)return e.jsx(ws,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(q,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const b=M_(new Date(n.event_date)),j=n.capacity&&o>=n.capacity,N=(i==null?void 0:i.zoom_join_url)||n.zoom_link;return e.jsx(ws,{title:n.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(q,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Events"]}),n.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:n.image_url,alt:n.title,className:"w-full h-full object-cover"}),b&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Xe,{variant:"secondary",className:"text-lg px-4 py-2",children:"Event Ended"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:n.title}),e.jsx(L8,{resourceType:"event",resourceId:n.id,resourceTitle:n.title})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground dark:prose-invert",dangerouslySetInnerHTML:{__html:n.description}})]}),n.video_url&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Ff,{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:_(n.video_url),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Event Preview Video"})})]})]}),e.jsx("div",{className:"space-y-4",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(vn,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(n.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D9(new Date(n.event_date))})]})]}),n.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Dr,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[o," / ",n.capacity]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Registered"})]})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-500/10 rounded-lg",children:[e.jsx(Ti,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[!b&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(q,{className:"w-full gap-2",onClick:()=>window.open(N,"_blank"),children:[e.jsx(un,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(q,{variant:"outline",className:"w-full",onClick:y,disabled:m,children:[m?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(q,{className:"w-full gap-2",onClick:y,disabled:m||(j??!1),children:m?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):j?"Event Full":"Register Now"})}),b&&i&&e.jsxs(q,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(n.zoom_link,"_blank"),children:[e.jsx(un,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const Yos=[{id:"quickvid",name:"QuickVid",description:"Record, manage, and share personalized video messages",icon:e.jsx(bn,{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(S0,{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(Jy,{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(En,{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(vm,{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(Ir,{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(Ks,{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(rf,{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(hn,{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(t_,{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(OF,{className:"h-6 w-6"}),path:"/website-apps",category:"Website",isNew:!0,color:"bg-cyan-500/15 text-cyan-600"},{id:"cma",name:"CMA Reports",description:"Build interactive CMAs with live comps, share with clients, and auto-create deals",icon:e.jsx(Mo,{className:"h-6 w-6"}),path:"/mission-control/cma",category:"Marketing",isNew:!0,requiresLeadSiteMLS:!0,color:"bg-blue-500/15 text-blue-600"}],Zos=()=>{const{user:s,isAdmin:t}=Cs(),r=qr(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(""),[d,u]=k.useState("all"),[m,f]=k.useState(new Set),[x,y]=k.useState(new Set),[_,b]=k.useState(!1);k.useEffect(()=>{j()},[s]);const j=async()=>{try{const{data:K}=await U.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),Z=(K==null?void 0:K.map(xe=>xe.tag))||[],{data:Q,error:W}=await U.from("app_tiles").select("*").order("name");if(W)throw W;const[{data:te},{data:ne},{data:ae}]=await Promise.all([U.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),U.from("user_tool_favorites").select("tool_id").eq("user_id",s==null?void 0:s.id),U.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s==null?void 0:s.id)]),ue=(ae||[]).some(xe=>xe.is_active&&xe.mls_provider_id&&!xe.no_mls_mode);b(ue);const me=new Set((te==null?void 0:te.map(xe=>xe.app_id))||[]);f(me);const de=new Set((ne||[]).map(xe=>xe.tool_id));y(de);const je=((Q==null?void 0:Q.filter(xe=>!xe.required_tags||xe.required_tags.length===0?!0:xe.required_tags.some(Ee=>Z.includes(Ee))))||[]).sort((xe,Ee)=>xe.name==="LevelUp Members Portal"?-1:Ee.name==="LevelUp Members Portal"?1:0);a(je)}catch(K){console.error("Error loading apps:",K),he.error("Failed to load apps")}finally{l(!1)}},N=async K=>{var Q;const Z=window.open("about:blank","_blank");try{const{data:W,error:te}=await U.auth.getSession();if(te||!W.session){Z==null||Z.close(),he.error("Session expired. Please refresh the page and try again.");return}const ne=W.session.access_token;await U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:K.app_id,app_name:K.name,user_agent:navigator.userAgent});const{data:ae,error:ue}=await U.functions.invoke("sso-launch",{body:{app_id:K.app_id},headers:{Authorization:`Bearer ${ne}`}});if(ue)throw ue;ae!=null&&ae.redirect_url?Z&&!Z.closed?(Z.location.href=ae.redirect_url,(Q=Z.focus)==null||Q.call(Z)):window.location.assign(ae.redirect_url):(Z==null||Z.close(),he.error("Launch link unavailable"))}catch(W){Z==null||Z.close(),console.error("Error launching app:",W),he.error("Failed to launch app. Please try again.")}},C=async(K,Z)=>{K.stopPropagation();const Q=m.has(Z);try{if(Q){const{error:W}=await U.from("user_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("app_id",Z);if(W)throw W;f(te=>{const ne=new Set(te);return ne.delete(Z),ne}),he.success("Removed from favorites")}else{const{error:W}=await U.from("user_favorites").insert({user_id:s==null?void 0:s.id,app_id:Z});if(W)throw W;f(te=>new Set(te).add(Z)),he.success("Added to favorites")}}catch(W){console.error("Error toggling favorite:",W),he.error("Failed to update favorites")}},A=async(K,Z)=>{K.stopPropagation();const Q=x.has(Z);try{if(Q){const{error:W}=await U.from("user_tool_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("tool_id",Z);if(W)throw W;y(te=>{const ne=new Set(te);return ne.delete(Z),ne}),he.success("Removed from favorites")}else{const{error:W}=await U.from("user_tool_favorites").insert({user_id:s==null?void 0:s.id,tool_id:Z});if(W)throw W;y(te=>new Set(te).add(Z)),he.success("Added to favorites")}}catch(W){console.error("Error toggling tool favorite:",W),he.error("Failed to update favorites")}},E=n.filter(K=>{var Q;const Z=K.name.toLowerCase().includes(o.toLowerCase())||((Q=K.description)==null?void 0:Q.toLowerCase().includes(o.toLowerCase()));return d==="favorites"?Z&&m.has(K.id):Z}),D=Yos.filter(K=>{if(K.adminOnly&&!t||K.requiresLeadSiteMLS&&!_&&!t)return!1;const Z=K.name.toLowerCase().includes(o.toLowerCase())||K.description.toLowerCase().includes(o.toLowerCase());return d==="favorites"?Z&&x.has(K.id):Z}),R=D.reduce((K,Z)=>(K[Z.category]||(K[Z.category]=[]),K[Z.category].push(Z),K),{}),F=[{id:"all",label:"All"},{id:"tools",label:"Built-in Tools"},{id:"apps",label:"Connected Apps"},{id:"favorites",label:"Favorites"}];if(i)return e.jsx(ws,{title:"Apps & Tools",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading apps & tools..."})]})})});const O=d==="all"||d==="tools"||d==="favorites",B=d==="all"||d==="apps"||d==="favorites";return e.jsxs(ws,{title:"Apps & Tools",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Apps & Tools"}),e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search apps & tools...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:o,onChange:K=>c(K.target.value)})]})]}),e.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:F.map(K=>e.jsxs("button",{onClick:()=>u(K.id),className:zt("pb-3 text-sm font-medium transition-colors relative",d===K.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[K.label,d===K.id&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},K.id))}),O&&Object.keys(R).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(A_,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Built-in Tools"})]}),Object.entries(R).map(([K,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:K})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:Z.map(Q=>{const W=x.has(Q.id);return e.jsxs("div",{onClick:()=>r(Q.path),className:zt("group flex items-start gap-4 p-5 bg-card rounded-xl border transition-all duration-200 hover:shadow-lg cursor-pointer relative overflow-hidden",Q.isNew?"border-primary/40 ring-1 ring-primary/20 hover:border-primary/60":"border-border hover:border-primary/30"),children:[Q.isNew&&e.jsx("div",{className:"absolute top-0 right-0 bg-gradient-to-r from-violet-500 to-indigo-500 text-white text-[10px] font-bold uppercase px-3 py-0.5 rounded-bl-lg tracking-wider shadow-sm",children:"✨ New"}),e.jsx("div",{className:zt("flex-shrink-0 w-14 h-14 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105",Q.color||"bg-primary/10 text-primary"),children:Q.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate flex items-center gap-2",children:[Q.name,Q.beta&&e.jsx("span",{className:"text-[10px] font-semibold bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded-full border border-amber-200",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:Q.description})]}),e.jsx("button",{className:zt("flex-shrink-0 p-1 transition-colors",W?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:te=>A(te,Q.id),children:e.jsx(Zy,{className:zt("h-5 w-5",W&&"fill-current")})})]},Q.id)})})]},K))]}),B&&e.jsxs("div",{children:[d==="all"&&E.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(un,{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"&&D.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(Zy,{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(q,{className:"mt-4",onClick:()=>r("/admin/apps"),children:"Add Apps"})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:E.map(K=>{const Z=m.has(K.id),Q=K.name.toLowerCase().includes("agent review")||K.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:()=>N(K),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:K.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:K.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:K.description})]}),e.jsx("button",{className:zt("flex-shrink-0 p-1 transition-colors",Z?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:W=>C(W,K.id),children:e.jsx(Zy,{className:zt("h-5 w-5",Z&&"fill-current")})})]}),Q&&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 →"})]},K.id)})})]}),O&&B&&E.length===0&&D.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(_n,{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"})]})]})},Xos=()=>{var C;const s=qr(),{isAdmin:t}=Cs(),[r,n]=k.useState(""),[a,i]=k.useState("all"),[l,o]=k.useState("all"),[c,d]=k.useState("grid"),{data:u=[]}=pt({queryKey:["template-categories"],queryFn:async()=>{const{data:A,error:E}=await U.from("template_categories").select("*").order("name");if(E)throw E;return A}}),{data:m=[]}=pt({queryKey:["template-types"],queryFn:async()=>{const{data:A,error:E}=await U.from("template_types").select("*").order("name");if(E)throw E;return A}}),{data:f=[],isLoading:x}=pt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:A,error:E}=await U.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:D,error:R}=await U.from("template_links").select("*").order("sort_order");if(R)throw R;const F=async te=>{let ae=0;const ue=[];for(;;){const{data:me,error:de}=await te().range(ae,ae+1e3-1);if(de)throw de;if(!me||me.length===0||(ue.push(...me),me.length<1e3))break;ae+=1e3}return ue},O=await F(()=>U.from("template_likes").select("template_id")),B=await F(()=>U.from("template_comments").select("template_id")),K=new Map;O.forEach(te=>{K.set(te.template_id,(K.get(te.template_id)||0)+1)});const Z=new Map;B.forEach(te=>{Z.set(te.template_id,(Z.get(te.template_id)||0)+1)});const Q=new Map;return t&&(await F(()=>U.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(ne=>{Q.set(ne.resource_id,(Q.get(ne.resource_id)||0)+1)}),(A||[]).map(te=>({...te,links:(D||[]).filter(ne=>ne.template_id===te.id)||[],likesCount:K.get(te.id)||0,commentsCount:Z.get(te.id)||0,viewsCount:Q.get(te.id)||0}))}}),y=f.filter(A=>{var F;const E=A.name.toLowerCase().includes(r.toLowerCase())||((F=A.description)==null?void 0:F.toLowerCase().includes(r.toLowerCase())),D=a==="all"||A.category_id===a,R=l==="all"||A.type_id===l;return E&&D&&R}),_=()=>{n(""),i("all"),o("all")},b=r||a!=="all"||l!=="all",j=(C=[...f].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:C.id,N=A=>{s(`/templates/${A}`)};return e.jsx(ws,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!x&&f.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(fa,{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:f.filter(A=>A.is_featured).slice(0,4).map(A=>e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>N(A.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[A.id===j&&e.jsx(Xe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Pe,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:x9(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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search templates...",value:r,onChange:A=>n(A.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:a,onValueChange:i,children:[e.jsx(Ps,{className:"w-full sm:w-48",children:e.jsx(Fs,{placeholder:"All Categories"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Categories"}),u.map(A=>e.jsx(lt,{value:A.id,children:A.name},A.id))]})]}),e.jsxs(Ds,{value:l,onValueChange:o,children:[e.jsx(Ps,{className:"w-full sm:w-48",children:e.jsx(Fs,{placeholder:"All Types"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),m.map(A=>e.jsx(lt,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[b&&e.jsx(q,{variant:"outline",size:"sm",onClick:_,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(Ep,{className:"h-4 w-4"})}),e.jsx(q,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(Zf,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[y.length," template",y.length!==1?"s":""," found"]}),x&&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(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(dr,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(dr,{className:"h-5 w-3/4 mb-2"}),e.jsx(dr,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(dr,{className:"h-5 w-16"}),e.jsx(dr,{className:"h-5 w-20"})]})]})},E))}),!x&&y.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:b?"No templates match your filters":"No templates available yet"}),b&&e.jsx(q,{variant:"outline",onClick:_,children:"Clear Filters"})]}),!x&&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(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>N(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(Xe,{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(Xe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(tl,{className:"h-3 w-3"}),A.links.length]})})]}),e.jsxs(Pe,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:A.name}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:x9(A.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[A.category&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:A.category.name}),A.type&&e.jsx(Xe,{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(wm,{className:"h-3.5 w-3.5"}),A.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gc,{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(Nn,{className:"h-3.5 w-3.5"}),A.viewsCount]})]}),e.jsxs(q,{size:"sm",className:"w-full gap-2",onClick:E=>{E.stopPropagation(),N(A.id)},children:[e.jsx(un,{className:"h-4 w-4"}),"View Template"]})]})]},A.id))})]})})};var Qos="Separator",m$e="horizontal",Jos=["horizontal","vertical"],wht=k.forwardRef((s,t)=>{const{decorative:r,orientation:n=m$e,...a}=s,i=els(n)?n:m$e,o=r?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(Yn.div,{"data-orientation":i,...o,...a,ref:t})});wht.displayName=Qos;function els(s){return Jos.includes(s)}var jht=wht;const cl=k.forwardRef(({className:s,orientation:t="horizontal",decorative:r=!0,...n},a)=>e.jsx(jht,{ref:a,decorative:r,orientation:t,className:zt("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...n}));cl.displayName=jht.displayName;const tls=()=>{const{templateId:s}=xo(),t=qr(),{user:r,isAdmin:n}=Cs(),{toast:a}=Ba(),i=is(),{trackEngagement:l}=M8(),[o,c]=k.useState(""),{data:d,isLoading:u}=pt({queryKey:["template-detail",s],queryFn:async()=>{const{data:A,error:E}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(E)throw E;const{data:D}=await U.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:R}=await U.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...A,links:D||[],guides:R||[]}},enabled:!!s}),{data:m=[]}=pt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:A,error:E}=await U.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(D=>D.resource_kits).filter(Boolean)},enabled:!!s});k.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:f=[]}=pt({queryKey:["template-likes",s],queryFn:async()=>{const{data:A,error:E}=await U.from("template_likes").select("*").eq("template_id",s);if(E)throw E;return A},enabled:!!s}),{data:x=[]}=pt({queryKey:["template-comments",s],queryFn:async()=>{const{data:A,error:E}=await U.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(E)throw E;const D=[...new Set(A.map(O=>O.user_id))],{data:R}=await U.from("profiles").select("id, name").in("id",D),F=new Map((R==null?void 0:R.map(O=>[O.id,O.name]))||[]);return A.map(O=>({...O,user_name:F.get(O.user_id)||"Unknown User"}))},enabled:!!s}),y=Mt({mutationFn:async A=>{const{error:E}=await U.from("template_comments").insert({template_id:s,user_id:r.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"})}}),_=Mt({mutationFn:async A=>{const{error:E}=await U.from("template_comments").delete().eq("id",A);if(E)throw E},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),b=Mt({mutationFn:async()=>{const A=f.find(E=>E.user_id===(r==null?void 0:r.id));if(A){const{error:E}=await U.from("template_likes").delete().eq("id",A.id);if(E)throw E}else{const{error:E}=await U.from("template_likes").insert({template_id:s,user_id:r.id});if(E)throw E}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),j=f.some(A=>A.user_id===(r==null?void 0:r.id)),N=A=>A.split(" ").map(E=>E[0]).join("").toUpperCase().slice(0,2),C=A=>{A.preventDefault(),!(!o.trim()||!r)&&y.mutate(o.trim())};return u?e.jsx(ws,{title:"Templates",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):d?e.jsx(ws,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(q,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Vn,{to:"/templates",children:[e.jsx(Aa,{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(Xe,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(Xe,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx(q,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Vn,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(Ua,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(L8,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(q,{variant:j?"default":"outline",className:"gap-2 rounded-full",onClick:()=>b.mutate(),disabled:!r||b.isPending,children:[e.jsx(wm,{className:`h-4 w-4 ${j?"fill-current":""}`}),f.length," ",f.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(tl,{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(q,{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(un,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),d.video_url&&e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsx("div",{className:"aspect-video w-full rounded-lg overflow-hidden",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})}),d.guides&&d.guides.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(En,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(A=>e.jsxs(q,{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(En,{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(li,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),m.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(yc,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:m.map(A=>e.jsxs(q,{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(yc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:A.name})]},A.id))})]})}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(gc,{className:"h-5 w-5"}),"Comments (",x.length,")"]}),r?e.jsxs("form",{onSubmit:C,className:"flex gap-2",children:[e.jsx(pr,{placeholder:"Add a comment...",value:o,onChange:A=>c(A.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(q,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||y.isPending,children:e.jsx(hn,{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:x.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):x.map(A=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Kn,{className:"text-sm",children:N(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:Nl(new Date(A.created_at),{addSuffix:!0})}),A.user_id===(r==null?void 0:r.id)&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>_.mutate(A.id),children:e.jsx(zr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:A.content})]})]})})},A.id))})]})]})}):e.jsx(ws,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(tl,{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(q,{asChild:!0,className:"mt-4",children:e.jsx(Vn,{to:"/templates",children:"Back to Templates"})})]})})},sls=()=>{const{user:s}=Cs(),[t,r]=k.useState(""),[n,a]=k.useState("all"),{data:i=[]}=pt({queryKey:["academy-categories"],queryFn:async()=>{const{data:f,error:x}=await U.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(x)throw x;return f}}),{data:l=[],isLoading:o}=pt({queryKey:["academy-videos"],queryFn:async()=>{const{data:f,error:x}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(x)throw x;const{data:y,error:_}=await U.from("academy_resources").select("*").order("sort_order");if(_)throw _;return f.map(j=>({...j,resources:(y==null?void 0:y.filter(N=>N.video_id===j.id))||[]}))}}),{data:c=[]}=pt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:f,error:x}=await U.from("academy_video_likes").select("video_id, user_id");if(x)throw x;return f}}),d=l.filter(f=>{var _;const x=t===""||f.title.toLowerCase().includes(t.toLowerCase())||((_=f.description)==null?void 0:_.toLowerCase().includes(t.toLowerCase())),y=n==="all"||f.category_id===n;return x&&y}),u=f=>c.filter(x=>x.video_id===f).length,m=f=>c.some(x=>x.video_id===f&&x.user_id===(s==null?void 0:s.id));return e.jsx(ws,{title:"Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Academy"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search videos...",value:t,onChange:f=>r(f.target.value),className:"pl-10"})]})}),e.jsx(ta,{value:n,onValueChange:a,children:e.jsxs(ea,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(rs,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(f=>e.jsx(rs,{value:f.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:f.name},f.id))]})}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(bn,{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(f=>e.jsx(Vn,{to:`/academy/${f.id}`,children:e.jsxs(ke,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[f.thumbnail_url?e.jsx("img",{src:f.thumbnail_url,alt:f.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(bn,{className:"h-12 w-12 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/90 flex items-center justify-center",children:e.jsx(Al,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),f.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(jn,{className:"h-3 w-3"}),f.duration]})]}),e.jsxs(Pt,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Dt,{className:"text-lg line-clamp-2",children:f.title})}),f.category&&e.jsx(Xe,{variant:"secondary",className:"w-fit",children:f.category.name})]}),e.jsxs(Pe,{className:"pt-0",children:[f.description&&e.jsx(Ur,{className:"line-clamp-2",children:f.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(wm,{className:`h-4 w-4 ${m(f.id)?"fill-primary text-primary":""}`}),u(f.id)]}),f.resources&&f.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(En,{className:"h-4 w-4"}),f.resources.length]})]})]})]})},f.id))})]})})};function Nht({resourceType:s,resourceId:t}){const{data:r=[]}=pt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:n,error:a}=await U.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(n||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:n,error:a}=await U.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(n||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return r.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-sm",children:[e.jsx(dl,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(n=>e.jsx(Vn,{to:`/templates/${n.id}`,children:e.jsxs(Xe,{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(dl,{className:"h-3 w-3"}),n.name]})},n.id))})]})}const rls=(s,t)=>{if(t==="bunny_stream"){let r=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return r.includes("?")||(r+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),r}if(t==="youtube"){const r=/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/,n=s.match(r);if(n)return`https://www.youtube.com/embed/${n[1]}`}if(t==="vimeo"){const r=/vimeo\.com\/(?:video\/)?(\d+)/,n=s.match(r);if(n)return`https://player.vimeo.com/video/${n[1]}`}if(t==="loom"){const r=/loom\.com\/share\/([a-zA-Z0-9]+)/,n=s.match(r);if(n)return`https://www.loom.com/embed/${n[1]}`}return s},nls=()=>{const{videoId:s}=xo();qr();const{user:t,isAdmin:r}=Cs(),{toast:n}=Ba(),a=is(),{trackEngagement:i}=M8(),[l,o]=k.useState(""),{data:c,isLoading:d}=pt({queryKey:["academy-video",s],queryFn:async()=>{const{data:C,error:A}=await U.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 U.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...C,resources:E||[]}},enabled:!!s});k.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=pt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:C,error:A}=await U.from("academy_video_likes").select("*").eq("video_id",s);if(A)throw A;return C},enabled:!!s}),{data:m=[]}=pt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:C,error:A}=await U.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(A)throw A;const E=[...new Set(C.map(F=>F.user_id))],{data:D}=await U.from("profiles").select("id, name").in("id",E),R=new Map((D==null?void 0:D.map(F=>[F.id,F.name]))||[]);return C.map(F=>({...F,user_name:R.get(F.user_id)||"Unknown User"}))},enabled:!!s}),f=Mt({mutationFn:async C=>{const{error:A}=await U.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:C});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),n({title:"Comment added!"})},onError:C=>{n({title:"Error adding comment",description:C.message,variant:"destructive"})}}),x=Mt({mutationFn:async C=>{const{error:A}=await U.from("academy_video_comments").delete().eq("id",C);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),n({title:"Comment deleted"})}}),y=Mt({mutationFn:async()=>{const C=u.find(A=>A.user_id===(t==null?void 0:t.id));if(C){const{error:A}=await U.from("academy_video_likes").delete().eq("id",C.id);if(A)throw A}else{const{error:A}=await U.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(C=>C.user_id===(t==null?void 0:t.id)),b=C=>{switch(C==null?void 0:C.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=C=>C.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),N=C=>{C.preventDefault(),!(!l.trim()||!t)&&f.mutate(l.trim())};return d?e.jsx(ws,{title:"Academy",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(ws,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(q,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Vn,{to:"/academy",children:[e.jsx(Aa,{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:rls(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(bn,{className:"h-16 w-16 opacity-50"}),e.jsx(q,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(un,{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(Xe,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(q,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Vn,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(Ua,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(L8,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(q,{variant:_?"default":"outline",className:"gap-2 w-fit",onClick:()=>y.mutate(),disabled:!t||y.isPending,children:[e.jsx(wm,{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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(En,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(C=>e.jsxs("a",{href:C.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[e.jsx("span",{className:"text-2xl",children:b(C.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:C.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:C.file_type})]}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground"})]},C.id))})]})}),e.jsx(Nht,{resourceType:"academy_video",resourceId:c.id}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(gc,{className:"h-5 w-5"}),"Comments (",m.length,")"]}),t?e.jsxs("form",{onSubmit:N,className:"flex gap-2",children:[e.jsx(pr,{placeholder:"Add a comment...",value:l,onChange:C=>o(C.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(q,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||f.isPending,children:e.jsx(hn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:m.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):m.map(C=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Kn,{className:"text-sm",children:j(C.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:C.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Nl(new Date(C.created_at),{addSuffix:!0})}),C.user_id===(t==null?void 0:t.id)&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(C.id),children:e.jsx(zr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:C.content})]})]})})},C.id))})]})]})}):e.jsx(ws,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(bn,{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(q,{asChild:!0,className:"mt-4",children:e.jsx(Vn,{to:"/academy",children:"Back to Academy"})})]})})},E6="https://dashboard.relevelup.com",als=(s,t)=>{if(t==="bunny_stream"){let r=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return r.includes("?")||(r+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),r}if(t==="youtube"){const r=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(r)return`https://www.youtube.com/embed/${r[1]}`}if(t==="vimeo"){const r=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(r)return`https://player.vimeo.com/video/${r[1]}`}if(t==="loom"){const r=s.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(r)return`https://www.loom.com/embed/${r[1]}`}return s},ils=[{icon:Ff,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:zh,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:Dr,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:wo,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function ols(){var i;const{slug:s}=xo(),{data:t,isLoading:r,error:n}=pt({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await U.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});k.useEffect(()=>{if(t&&s){U.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');if(o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy."),t.thumbnail_url){let c=document.querySelector('meta[property="og:image"]');c||(c=document.createElement("meta"),c.setAttribute("property","og:image"),document.head.appendChild(c)),c.setAttribute("content",t.thumbnail_url)}}},[t,s]);const a=k.useMemo(()=>t?als(t.video_url,t.video_type):"",[t]);return r?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"})}):n||!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:E6,children:e.jsx(q,{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(Ir,{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:E6,children:e.jsx(q,{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(Xe,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(Ff,{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(C_,{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:E6,className:"w-full sm:w-auto",children:e.jsxs(q,{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(ci,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:E6,className:"w-full sm:w-auto",children:e.jsx(q,{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:ils.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(qn,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:E6,children:e.jsxs(q,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(ci,{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:E6,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function lls(){const s=qr(),[t,r]=k.useState(""),{data:n,isLoading:a}=pt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:x,error:y}=await U.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(y)throw y;return x}}),{data:i}=pt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:x,error:y}=await U.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(y)throw y;return x}}),{data:l}=pt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:x,error:y}=await U.from("resource_kit_likes").select("kit_id");if(y)throw y;return x}}),{data:o}=pt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:x,error:y}=await U.from("resource_kit_comments").select("kit_id");if(y)throw y;return x}}),c=n==null?void 0:n.filter(x=>{var y;return x.name.toLowerCase().includes(t.toLowerCase())||((y=x.description)==null?void 0:y.toLowerCase().includes(t.toLowerCase()))}),d=x=>(i==null?void 0:i.filter(y=>y.kit_id===x))||[],u=x=>(l==null?void 0:l.filter(y=>y.kit_id===x).length)||0,m=x=>(o==null?void 0:o.filter(y=>y.kit_id===x).length)||0,f=x=>{s(`/toolbox/${x}`)};return e.jsx(ws,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Toolbox"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Download resource kits and tools to help grow your business"})]}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search resource kits...",value:t,onChange:x=>r(x.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((x,y)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(dr,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(dr,{className:"h-5 w-3/4 mb-2"}),e.jsx(dr,{className:"h-4 w-full mb-4"}),e.jsx(dr,{className:"h-4 w-2/3"})]})},y))}):(c==null?void 0:c.length)===0?e.jsxs(ke,{className:"p-12 text-center",children:[e.jsx(yc,{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(x=>{const y=d(x.id).length,_=u(x.id),b=m(x.id);return e.jsxs(ke,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>f(x.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:x.featured_image_url?e.jsx("img",{src:x.featured_image_url,alt:x.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(yc,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Pe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:x.name}),x.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:x9(x.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(En,{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(wm,{className:"h-3.5 w-3.5"}),_]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gc,{className:"h-3.5 w-3.5"}),b]})]})]})]})]},x.id)})})]})})}const cls=()=>{const{kitId:s}=xo(),{user:t,isAdmin:r}=Cs(),{toast:n}=Ba(),a=is(),{trackEngagement:i}=M8(),[l,o]=k.useState(""),{data:c,isLoading:d}=pt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:C,error:A}=await U.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:E}=await U.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:D}=await U.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...C,files:E||[],links:D||[]}},enabled:!!s});k.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=pt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:C,error:A}=await U.from("resource_kit_likes").select("*").eq("kit_id",s);if(A)throw A;return C},enabled:!!s}),{data:m=[]}=pt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:C,error:A}=await U.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(A)throw A;const E=[...new Set(C.map(F=>F.user_id))],{data:D}=await U.from("profiles").select("id, name").in("id",E),R=new Map((D==null?void 0:D.map(F=>[F.id,F.name]))||[]);return C.map(F=>({...F,user_name:R.get(F.user_id)||"Unknown User"}))},enabled:!!s}),f=Mt({mutationFn:async C=>{const{error:A}=await U.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:C});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),n({title:"Comment added!"})},onError:C=>{n({title:"Error adding comment",description:C.message,variant:"destructive"})}}),x=Mt({mutationFn:async C=>{const{error:A}=await U.from("resource_kit_comments").delete().eq("id",C);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),n({title:"Comment deleted"})}}),y=Mt({mutationFn:async()=>{const C=u.find(A=>A.user_id===(t==null?void 0:t.id));if(C){const{error:A}=await U.from("resource_kit_likes").delete().eq("id",C.id);if(A)throw A}else{const{error:A}=await U.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(C=>C.user_id===(t==null?void 0:t.id)),b=C=>C.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),j=C=>C?C<1024?C+" B":C<1024*1024?(C/1024).toFixed(1)+" KB":(C/(1024*1024)).toFixed(1)+" MB":"",N=C=>{C.preventDefault(),!(!l.trim()||!t)&&f.mutate(l.trim())};return d?e.jsx(ws,{title:"Toolbox",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(ws,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(q,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Vn,{to:"/toolbox",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Toolbox"]})}),c.featured_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.featured_image_url,alt:c.name,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.name})}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(q,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Vn,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(Ua,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(L8,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(q,{variant:_?"default":"outline",className:"gap-2 rounded-full",onClick:()=>y.mutate(),disabled:!t||y.isPending,children:[e.jsx(wm,{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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(En,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(C=>e.jsxs("a",{href:C.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(En,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:C.name}),C.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j(C.file_size)})]})]}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},C.id))})]})}),c.links&&c.links.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(un,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(C=>e.jsxs("a",{href:C.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(un,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:C.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},C.id))})]})}),e.jsx(Nht,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(gc,{className:"h-5 w-5"}),"Comments (",m.length,")"]}),t?e.jsxs("form",{onSubmit:N,className:"flex gap-2",children:[e.jsx(pr,{placeholder:"Add a comment...",value:l,onChange:C=>o(C.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(q,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||f.isPending,children:e.jsx(hn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:m.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):m.map(C=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Kn,{className:"text-sm",children:b(C.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:C.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Nl(new Date(C.created_at),{addSuffix:!0})}),C.user_id===(t==null?void 0:t.id)&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(C.id),children:e.jsx(zr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:C.content})]})]})})},C.id))})]})]})}):e.jsx(ws,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(yc,{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(q,{asChild:!0,className:"mt-4",children:e.jsx(Vn,{to:"/toolbox",children:"Back to Toolbox"})})]})})},dls=()=>{const s=qr(),[t,r]=k.useState(""),[n,a]=k.useState("grid"),{data:i=[],isLoading:l}=pt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await U.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:m,error:f}=await U.from("social_swag_links").select("*").order("sort_order");if(f)throw f;const{data:x}=await U.from("social_swag_likes").select("swag_id"),{data:y}=await U.from("social_swag_comments").select("swag_id"),_=new Map;x==null||x.forEach(N=>{_.set(N.swag_id,(_.get(N.swag_id)||0)+1)});const b=new Map;return y==null||y.forEach(N=>{b.set(N.swag_id,(b.get(N.swag_id)||0)+1)}),(d||[]).map(N=>({...N,links:(m||[]).filter(C=>C.swag_id===N.id)||[],likesCount:_.get(N.id)||0,commentsCount:b.get(N.id)||0}))}}),o=i.filter(d=>{var m;return d.title.toLowerCase().includes(t.toLowerCase())||((m=d.description)==null?void 0:m.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(ws,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search social swag...",value:t,onChange:d=>r(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(q,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Ep,{className:"h-4 w-4"})}),e.jsx(q,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Zf,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," item",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((d,u)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(dr,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(dr,{className:"h-5 w-3/4 mb-2"}),e.jsx(dr,{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(q,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(d=>e.jsxs(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Xe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(tl,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Pe,{className:`p-4 flex flex-col ${n==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:d.title}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:d.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wm,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gc,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(q,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(un,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var to=function(){return to=Object.assign||function(t){for(var r,n=1,a=arguments.length;n1&&(c||!d),m=t>1&&(d||!c),f=function(){n&&i(n)},x=function(){a&&i(a)};return e.jsx(qls,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:m,nextMonth:a,previousMonth:n,onPreviousClick:f,onNextClick:x})}function Vls(s){var t,r=ud(),n=r.classNames,a=r.disableNavigation,i=r.styles,l=r.captionLayout,o=r.components,c=(t=o==null?void 0:o.CaptionLabel)!==null&&t!==void 0?t:Cht,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(f$e,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(f$e,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(p$e,{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(p$e,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:n.caption,style:i.caption,children:d})}function Hls(s){var t=ud(),r=t.footer,n=t.styles,a=t.classNames.tfoot;return r?e.jsx("tfoot",{className:a,style:n.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:r})})}):e.jsx(e.Fragment,{})}function Gls(s,t,r){for(var n=r?C2(new Date):Mp(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Dc(n,i);a.push(l)}return a}function Wls(){var s=ud(),t=s.classNames,r=s.styles,n=s.showWeekNumber,a=s.locale,i=s.weekStartsOn,l=s.ISOWeek,o=s.formatters.formatWeekdayName,c=s.labels.labelWeekday,d=Gls(a,i,l);return e.jsxs("tr",{style:r.head_row,className:t.head_row,children:[n&&e.jsx("td",{style:r.head_cell,className:t.head_cell}),d.map(function(u,m){return e.jsx("th",{scope:"col",className:t.head_cell,style:r.head_cell,"aria-label":c(u,{locale:a}),children:o(u,{locale:a})},m)})]})}function Kls(){var s,t=ud(),r=t.classNames,n=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:Wls;return e.jsx("thead",{style:n.head,className:r.head,children:e.jsx(i,{})})}function Yls(s){var t=ud(),r=t.locale,n=t.formatters.formatDay;return e.jsx(e.Fragment,{children:n(s.date,{locale:r})})}var pAe=k.createContext(void 0);function Zls(s){if(!PB(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(pAe.Provider,{value:t,children:s.children})}return e.jsx(Xls,{initialProps:s.initialProps,children:s.children})}function Xls(s){var t=s.initialProps,r=s.children,n=t.selected,a=t.min,i=t.max,l=function(d,u,m){var f,x;(f=t.onDayClick)===null||f===void 0||f.call(t,d,u,m);var y=!!(u.selected&&a&&(n==null?void 0:n.length)===a);if(!y){var _=!!(!u.selected&&i&&(n==null?void 0:n.length)===i);if(!_){var b=n?kht([],n):[];if(u.selected){var j=b.findIndex(function(N){return pc(d,N)});b.splice(j,1)}else b.push(d);(x=t.onSelect)===null||x===void 0||x.call(t,b,d,u,m)}}},o={disabled:[]};n&&o.disabled.push(function(d){var u=i&&n.length>i-1,m=n.some(function(f){return pc(f,d)});return!!(u&&!m)});var c={selected:n,onDayClick:l,modifiers:o};return e.jsx(pAe.Provider,{value:c,children:r})}function xAe(){var s=k.useContext(pAe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function Qls(s,t){var r=t||{},n=r.from,a=r.to;return n&&a?pc(a,s)&&pc(n,s)?void 0:pc(a,s)?{from:a,to:void 0}:pc(n,s)?void 0:xS(n,s)?{from:s,to:a}:{from:n,to:s}:a?xS(s,a)?{from:a,to:s}:{from:s,to:a}:n?gS(s,n)?{from:s,to:n}:{from:n,to:s}:{from:s,to:void 0}}var gAe=k.createContext(void 0);function Jls(s){if(!LB(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(gAe.Provider,{value:t,children:s.children})}return e.jsx(ecs,{initialProps:s.initialProps,children:s.children})}function ecs(s){var t=s.initialProps,r=s.children,n=t.selected,a=n||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(x,y,_){var b,j;(b=t.onDayClick)===null||b===void 0||b.call(t,x,y,_);var N=Qls(x,n);(j=t.onSelect)===null||j===void 0||j.call(t,N,x,y,_)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],pc(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:zue(i,o-1),before:Dc(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Dc(i,o-1)}),!i&&l&&u.disabled.push({after:zue(l,o-1),before:Dc(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Dc(i,-c+1)}),u.disabled.push({after:Dc(i,c-1)})),i&&l){var m=cg(l,i)+1,f=c-m;u.disabled.push({before:zue(i,f)}),u.disabled.push({after:Dc(l,f)})}!i&&l&&(u.disabled.push({before:Dc(l,-c+1)}),u.disabled.push({after:Dc(l,c-1)}))}return e.jsx(gAe.Provider,{value:{selected:n,onDayClick:d,modifiers:u},children:r})}function yAe(){var s=k.useContext(gAe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function nhe(s){return Array.isArray(s)?kht([],s):s!==void 0?[s]:[]}function tcs(s){var t={};return Object.entries(s).forEach(function(r){var n=r[0],a=r[1];t[n]=nhe(a)}),t}var z1;(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"})(z1||(z1={}));var scs=z1.Selected,gj=z1.Disabled,rcs=z1.Hidden,ncs=z1.Today,J_e=z1.RangeEnd,ewe=z1.RangeMiddle,twe=z1.RangeStart,acs=z1.Outside;function ics(s,t,r){var n,a=(n={},n[scs]=nhe(s.selected),n[gj]=nhe(s.disabled),n[rcs]=nhe(s.hidden),n[ncs]=[s.today],n[J_e]=[],n[ewe]=[],n[twe]=[],n[acs]=[],n);return s.fromDate&&a[gj].push({before:s.fromDate}),s.toDate&&a[gj].push({after:s.toDate}),PB(s)?a[gj]=a[gj].concat(t.modifiers[gj]):LB(s)&&(a[gj]=a[gj].concat(r.modifiers[gj]),a[twe]=r.modifiers[twe],a[ewe]=r.modifiers[ewe],a[J_e]=r.modifiers[J_e]),a}var Aht=k.createContext(void 0);function ocs(s){var t=ud(),r=xAe(),n=yAe(),a=ics(t,r,n),i=tcs(t.modifiers),l=to(to({},a),i);return e.jsx(Aht.Provider,{value:l,children:s.children})}function Mht(){var s=k.useContext(Aht);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function lcs(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function ccs(s){return!!(s&&typeof s=="object"&&"from"in s)}function dcs(s){return!!(s&&typeof s=="object"&&"after"in s)}function ucs(s){return!!(s&&typeof s=="object"&&"before"in s)}function hcs(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function mcs(s,t){var r,n=t.from,a=t.to;if(n&&a){var i=cg(a,n)<0;i&&(r=[a,n],n=r[0],a=r[1]);var l=cg(s,n)>=0&&cg(a,s)>=0;return l}return a?pc(a,s):n?pc(n,s):!1}function fcs(s){return iTe(s)}function pcs(s){return Array.isArray(s)&&s.every(iTe)}function xcs(s,t){return t.some(function(r){if(typeof r=="boolean")return r;if(fcs(r))return pc(s,r);if(pcs(r))return r.includes(s);if(ccs(r))return mcs(s,r);if(hcs(r))return r.dayOfWeek.includes(s.getDay());if(lcs(r)){var n=cg(r.before,s),a=cg(r.after,s),i=n>0,l=a<0,o=xS(r.before,r.after);return o?l&&i:i||l}return dcs(r)?cg(s,r.after)>0:ucs(r)?cg(r.before,s)>0:typeof r=="function"?r(s):!1})}function vAe(s,t,r){var n=Object.keys(t).reduce(function(i,l){var o=t[l];return xcs(s,o)&&i.push(l),i},[]),a={};return n.forEach(function(i){return a[i]=!0}),r&&!lge(s,r)&&(a.outside=!0),a}function gcs(s,t){for(var r=qd(s[0]),n=Py(s[s.length-1]),a,i,l=r;l<=n;){var o=vAe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Dc(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Dc(l,1)}return i||a}var ycs=365;function Iht(s,t){var r=t.moveBy,n=t.direction,a=t.context,i=t.modifiers,l=t.retry,o=l===void 0?{count:0,lastFocused:s}:l,c=a.weekStartsOn,d=a.fromDate,u=a.toDate,m=a.locale,f={day:Dc,week:KT,month:Ex,year:KRt,startOfWeek:function(b){return a.ISOWeek?C2(b):Mp(b,{locale:m,weekStartsOn:c})},endOfWeek:function(b){return a.ISOWeek?hat(b):ige(b,{locale:m,weekStartsOn:c})}},x=f[r](s,n==="after"?1:-1);n==="before"&&d?x=YRt([d,x]):n==="after"&&u&&(x=ZRt([u,x]));var y=!0;if(i){var _=vAe(x,i);y=!_.disabled&&!_.hidden}return y?x:o.count>ycs?o.lastFocused:Iht(x,{moveBy:r,direction:n,context:a,modifiers:i,retry:to(to({},o),{count:o.count+1})})}var Pht=k.createContext(void 0);function vcs(s){var t=DB(),r=Mht(),n=k.useState(),a=n[0],i=n[1],l=k.useState(),o=l[0],c=l[1],d=gcs(t.displayMonths,r),u=a??(o&&t.isDateDisplayed(o))?o:d,m=function(){c(a),i(void 0)},f=function(b){i(b)},x=ud(),y=function(b,j){if(a){var N=Iht(a,{moveBy:b,direction:j,context:x,modifiers:r});pc(a,N)||(t.goToDate(N,a),f(N))}},_={focusedDay:a,focusTarget:u,blur:m,focus:f,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(Pht.Provider,{value:_,children:s.children})}function bAe(){var s=k.useContext(Pht);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function bcs(s,t){var r=Mht(),n=vAe(s,r,t);return n}var _Ae=k.createContext(void 0);function _cs(s){if(!t0e(s.initialProps)){var t={selected:void 0};return e.jsx(_Ae.Provider,{value:t,children:s.children})}return e.jsx(wcs,{initialProps:s.initialProps,children:s.children})}function wcs(s){var t=s.initialProps,r=s.children,n=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:n};return e.jsx(_Ae.Provider,{value:a,children:r})}function Lht(){var s=k.useContext(_Ae);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function jcs(s,t){var r=ud(),n=Lht(),a=xAe(),i=yAe(),l=bAe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,m=l.blur,f=l.focus,x=l.focusMonthBefore,y=l.focusMonthAfter,_=l.focusYearBefore,b=l.focusYearAfter,j=l.focusStartOfWeek,N=l.focusEndOfWeek,C=function(ae){var ue,me,de,fe;t0e(r)?(ue=n.onDayClick)===null||ue===void 0||ue.call(n,s,t,ae):PB(r)?(me=a.onDayClick)===null||me===void 0||me.call(a,s,t,ae):LB(r)?(de=i.onDayClick)===null||de===void 0||de.call(i,s,t,ae):(fe=r.onDayClick)===null||fe===void 0||fe.call(r,s,t,ae)},A=function(ae){var ue;f(s),(ue=r.onDayFocus)===null||ue===void 0||ue.call(r,s,t,ae)},E=function(ae){var ue;m(),(ue=r.onDayBlur)===null||ue===void 0||ue.call(r,s,t,ae)},D=function(ae){var ue;(ue=r.onDayMouseEnter)===null||ue===void 0||ue.call(r,s,t,ae)},R=function(ae){var ue;(ue=r.onDayMouseLeave)===null||ue===void 0||ue.call(r,s,t,ae)},F=function(ae){var ue;(ue=r.onDayPointerEnter)===null||ue===void 0||ue.call(r,s,t,ae)},O=function(ae){var ue;(ue=r.onDayPointerLeave)===null||ue===void 0||ue.call(r,s,t,ae)},B=function(ae){var ue;(ue=r.onDayTouchCancel)===null||ue===void 0||ue.call(r,s,t,ae)},K=function(ae){var ue;(ue=r.onDayTouchEnd)===null||ue===void 0||ue.call(r,s,t,ae)},Z=function(ae){var ue;(ue=r.onDayTouchMove)===null||ue===void 0||ue.call(r,s,t,ae)},Q=function(ae){var ue;(ue=r.onDayTouchStart)===null||ue===void 0||ue.call(r,s,t,ae)},W=function(ae){var ue;(ue=r.onDayKeyUp)===null||ue===void 0||ue.call(r,s,t,ae)},te=function(ae){var ue;switch(ae.key){case"ArrowLeft":ae.preventDefault(),ae.stopPropagation(),r.dir==="rtl"?o():c();break;case"ArrowRight":ae.preventDefault(),ae.stopPropagation(),r.dir==="rtl"?c():o();break;case"ArrowDown":ae.preventDefault(),ae.stopPropagation(),d();break;case"ArrowUp":ae.preventDefault(),ae.stopPropagation(),u();break;case"PageUp":ae.preventDefault(),ae.stopPropagation(),ae.shiftKey?_():x();break;case"PageDown":ae.preventDefault(),ae.stopPropagation(),ae.shiftKey?b():y();break;case"Home":ae.preventDefault(),ae.stopPropagation(),j();break;case"End":ae.preventDefault(),ae.stopPropagation(),N();break}(ue=r.onDayKeyDown)===null||ue===void 0||ue.call(r,s,t,ae)},ne={onClick:C,onFocus:A,onBlur:E,onKeyDown:te,onKeyUp:W,onMouseEnter:D,onMouseLeave:R,onPointerEnter:F,onPointerLeave:O,onTouchCancel:B,onTouchEnd:K,onTouchMove:Z,onTouchStart:Q};return ne}function Ncs(){var s=ud(),t=Lht(),r=xAe(),n=yAe(),a=t0e(s)?t.selected:PB(s)?r.selected:LB(s)?n.selected:void 0;return a}function kcs(s){return Object.values(z1).includes(s)}function Scs(s,t){var r=[s.classNames.day];return Object.keys(t).forEach(function(n){var a=s.modifiersClassNames[n];if(a)r.push(a);else if(kcs(n)){var i=s.classNames["day_".concat(n)];i&&r.push(i)}}),r}function Ccs(s,t){var r=to({},s.styles.day);return Object.keys(t).forEach(function(n){var a;r=to(to({},r),(a=s.modifiersStyles)===null||a===void 0?void 0:a[n])}),r}function Tcs(s,t,r){var n,a,i,l=ud(),o=bAe(),c=bcs(s,t),d=jcs(s,c),u=Ncs(),m=!!(l.onDayClick||l.mode!=="default");k.useEffect(function(){var D;c.outside||o.focusedDay&&m&&pc(o.focusedDay,s)&&((D=r.current)===null||D===void 0||D.focus())},[o.focusedDay,s,r,m,c.outside]);var f=Scs(l,c).join(" "),x=Ccs(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:Yls,b=e.jsx(_,{date:s,displayMonth:t,activeModifiers:c}),j={style:x,className:f,children:b,role:"gridcell"},N=o.focusTarget&&pc(o.focusTarget,s)&&!c.outside,C=o.focusedDay&&pc(o.focusedDay,s),A=to(to(to({},j),(n={disabled:c.disabled,role:"gridcell"},n["aria-selected"]=c.selected,n.tabIndex=C||N?0:-1,n)),d),E={isButton:m,isHidden:y,activeModifiers:c,selectedDays:u,buttonProps:A,divProps:j};return E}function Ecs(s){var t=k.useRef(null),r=Tcs(s.date,s.displayMonth,t);return r.isHidden?e.jsx("div",{role:"gridcell"}):r.isButton?e.jsx(_fe,to({name:"day",ref:t},r.buttonProps)):e.jsx("div",to({},r.divProps))}function Acs(s){var t=s.number,r=s.dates,n=ud(),a=n.onWeekNumberClick,i=n.styles,l=n.classNames,o=n.locale,c=n.labels.labelWeekNumber,d=n.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var m=c(Number(t),{locale:o}),f=function(x){a(t,r,x)};return e.jsx(_fe,{name:"week-number","aria-label":m,className:l.weeknumber,style:i.weeknumber,onClick:f,children:u})}function Mcs(s){var t,r,n=ud(),a=n.styles,i=n.classNames,l=n.showWeekNumber,o=n.components,c=(t=o==null?void 0:o.Day)!==null&&t!==void 0?t:Ecs,d=(r=o==null?void 0:o.WeekNumber)!==null&&r!==void 0?r:Acs,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(m){return e.jsx("td",{className:i.cell,style:a.cell,role:"presentation",children:e.jsx(c,{displayMonth:s.displayMonth,date:m})},JOt(m))})]})}function x$e(s,t,r){for(var n=r!=null&&r.ISOWeek?hat(t):ige(t,r),a=r!=null&&r.ISOWeek?C2(s):Mp(s,r),i=cg(n,a),l=[],o=0;o<=i;o++)l.push(Dc(a,o));var c=l.reduce(function(d,u){var m=r!=null&&r.ISOWeek?oTe(u):cTe(u,r),f=d.find(function(x){return x.weekNumber===m});return f?(f.dates.push(u),d):(d.push({weekNumber:m,dates:[u]}),d)},[]);return c}function Ics(s,t){var r=x$e(qd(s),Py(s),t);if(t!=null&&t.useFixedWeeks){var n=tFt(s,t);if(n<6){var a=r[r.length-1],i=a.dates[a.dates.length-1],l=KT(i,6-n),o=x$e(KT(i,1),l,t);r.push.apply(r,o)}}return r}function Pcs(s){var t,r,n,a=ud(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,m=a.weekStartsOn,f=a.firstWeekContainsDate,x=a.ISOWeek,y=Ics(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:x,locale:i,weekStartsOn:m,firstWeekContainsDate:f}),_=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:Kls,b=(r=u==null?void 0:u.Row)!==null&&r!==void 0?r:Mcs,j=(n=u==null?void 0:u.Footer)!==null&&n!==void 0?n:Hls;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(N){return e.jsx(b,{displayMonth:s.displayMonth,dates:N.dates,weekNumber:N.weekNumber},N.weekNumber)})}),e.jsx(j,{displayMonth:s.displayMonth})]})}function Lcs(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Dcs=Lcs()?k.useLayoutEffect:k.useEffect,swe=!1,Rcs=0;function g$e(){return"react-day-picker-".concat(++Rcs)}function Ocs(s){var t,r=s??(swe?g$e():null),n=k.useState(r),a=n[0],i=n[1];return Dcs(function(){a===null&&i(g$e())},[]),k.useEffect(function(){swe===!1&&(swe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function Fcs(s){var t,r,n=ud(),a=n.dir,i=n.classNames,l=n.styles,o=n.components,c=DB().displayMonths,d=Ocs(n.id?"".concat(n.id,"-").concat(s.displayIndex):void 0),u=n.id?"".concat(n.id,"-grid-").concat(s.displayIndex):void 0,m=[i.month],f=l.month,x=s.displayIndex===0,y=s.displayIndex===c.length-1,_=!x&&!y;a==="rtl"&&(t=[x,y],y=t[0],x=t[1]),x&&(m.push(i.caption_start),f=to(to({},f),l.caption_start)),y&&(m.push(i.caption_end),f=to(to({},f),l.caption_end)),_&&(m.push(i.caption_between),f=to(to({},f),l.caption_between));var b=(r=o==null?void 0:o.Caption)!==null&&r!==void 0?r:Vls;return e.jsxs("div",{className:m.join(" "),style:f,children:[e.jsx(b,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(Pcs,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function zcs(s){var t=ud(),r=t.classNames,n=t.styles;return e.jsx("div",{className:r.months,style:n.months,children:s.children})}function Bcs(s){var t,r,n=s.initialProps,a=ud(),i=bAe(),l=DB(),o=k.useState(!1),c=o[0],d=o[1];k.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var u=[a.classNames.root,a.className];a.numberOfMonths>1&&u.push(a.classNames.multiple_months),a.showWeekNumber&&u.push(a.classNames.with_weeknumber);var m=to(to({},a.styles.root),a.style),f=Object.keys(n).filter(function(y){return y.startsWith("data-")}).reduce(function(y,_){var b;return to(to({},y),(b={},b[_]=n[_],b))},{}),x=(r=(t=n.components)===null||t===void 0?void 0:t.Months)!==null&&r!==void 0?r:zcs;return e.jsx("div",to({className:u.join(" "),style:m,dir:a.dir,id:a.id,nonce:n.nonce,title:n.title,lang:n.lang},f,{children:e.jsx(x,{children:l.displayMonths.map(function(y,_){return e.jsx(Fcs,{displayIndex:_,displayMonth:y},_)})})}))}function $cs(s){var t=s.children,r=uls(s,["children"]);return e.jsx(Als,{initialProps:r,children:e.jsx(Bls,{children:e.jsx(_cs,{initialProps:r,children:e.jsx(Zls,{initialProps:r,children:e.jsx(Jls,{initialProps:r,children:e.jsx(ocs,{children:e.jsx(vcs,{children:t})})})})})})})}function Ucs(s){return e.jsx($cs,to({},s,{children:e.jsx(Bcs,{initialProps:s})}))}function _g({className:s,classNames:t,showOutsideDays:r=!0,...n}){return e.jsx(Ucs,{showOutsideDays:r,className:zt("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:zt(lL({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:zt(lL({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(jl,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(Ia,{className:"h-4 w-4"})},...n})}_g.displayName="Calendar";var s0e="Popover",[Dht,Jnr]=bu(s0e,[Q_]),RB=Q_(),[qcs,o4]=Dht(s0e),Rht=s=>{const{__scopePopover:t,children:r,open:n,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=RB(t),c=k.useRef(null),[d,u]=k.useState(!1),[m,f]=df({prop:n,defaultProp:a??!1,onChange:i,caller:s0e});return e.jsx(nB,{...o,children:e.jsx(qcs,{scope:t,contentId:jm(),triggerRef:c,open:m,onOpenChange:f,onOpenToggle:k.useCallback(()=>f(x=>!x),[f]),hasCustomAnchor:d,onCustomAnchorAdd:k.useCallback(()=>u(!0),[]),onCustomAnchorRemove:k.useCallback(()=>u(!1),[]),modal:l,children:r})})};Rht.displayName=s0e;var Oht="PopoverAnchor",Vcs=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=o4(Oht,r),i=RB(r),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return k.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(x8,{...i,...n,ref:t})});Vcs.displayName=Oht;var Fht="PopoverTrigger",zht=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=o4(Fht,r),i=RB(r),l=_i(t,a.triggerRef),o=e.jsx(Yn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":Vht(a.open),...n,ref:l,onClick:dn(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(x8,{asChild:!0,...i,children:o})});zht.displayName=Fht;var wAe="PopoverPortal",[Hcs,Gcs]=Dht(wAe,{forceMount:void 0}),Bht=s=>{const{__scopePopover:t,forceMount:r,children:n,container:a}=s,i=o4(wAe,t);return e.jsx(Hcs,{scope:t,forceMount:r,children:e.jsx(yh,{present:r||i.open,children:e.jsx(h8,{asChild:!0,container:a,children:n})})})};Bht.displayName=wAe;var _L="PopoverContent",$ht=k.forwardRef((s,t)=>{const r=Gcs(_L,s.__scopePopover),{forceMount:n=r.forceMount,...a}=s,i=o4(_L,s.__scopePopover);return e.jsx(yh,{present:n||i.open,children:i.modal?e.jsx(Kcs,{...a,ref:t}):e.jsx(Ycs,{...a,ref:t})})});$ht.displayName=_L;var Wcs=ES("PopoverContent.RemoveScroll"),Kcs=k.forwardRef((s,t)=>{const r=o4(_L,s.__scopePopover),n=k.useRef(null),a=_i(t,n),i=k.useRef(!1);return k.useEffect(()=>{const l=n.current;if(l)return Bxe(l)},[]),e.jsx(uB,{as:Wcs,allowPinchZoom:!0,children:e.jsx(Uht,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:dn(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=r.triggerRef.current)==null||o.focus()}),onPointerDownOutside:dn(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:dn(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),Ycs=k.forwardRef((s,t)=>{const r=o4(_L,s.__scopePopover),n=k.useRef(!1),a=k.useRef(!1);return e.jsx(Uht,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(n.current||(o=r.triggerRef.current)==null||o.focus(),i.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=r.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),Uht=k.forwardRef((s,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...m}=s,f=o4(_L,r),x=RB(r);return Oxe(),e.jsx(cB,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(WS,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>f.onOpenChange(!1),children:e.jsx(aB,{"data-state":Vht(f.open),role:"dialog",id:f.contentId,...x,...m,ref:t,style:{...m.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),qht="PopoverClose",Zcs=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=o4(qht,r);return e.jsx(Yn.button,{type:"button",...n,ref:t,onClick:dn(s.onClick,()=>a.onOpenChange(!1))})});Zcs.displayName=qht;var Xcs="PopoverArrow",Qcs=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=RB(r);return e.jsx(iB,{...a,...n,ref:t})});Qcs.displayName=Xcs;function Vht(s){return s?"open":"closed"}var Jcs=Rht,eds=zht,tds=Bht,Hht=$ht;const sl=Jcs,rl=eds,Ko=k.forwardRef(({className:s,align:t="center",sideOffset:r=4,...n},a)=>e.jsx(tds,{children:e.jsx(Hht,{ref:a,align:t,sideOffset:r,className:zt("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n})}));Ko.displayName=Hht.displayName;const sds=WA("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"}}),jAe=k.forwardRef(({className:s,variant:t,...r},n)=>e.jsx("div",{ref:n,role:"alert",className:zt(sds({variant:t}),s),...r}));jAe.displayName="Alert";const rds=k.forwardRef(({className:s,...t},r)=>e.jsx("h5",{ref:r,className:zt("mb-1 font-medium leading-none tracking-tight",s),...t}));rds.displayName="AlertTitle";const NAe=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:zt("text-sm [&_p]:leading-relaxed",s),...t}));NAe.displayName="AlertDescription";function nds({open:s,onOpenChange:t,imageUrl:r,imageId:n,defaultCaption:a="",swagItemId:i,reelId:l}){const o=is(),[c,d]=k.useState(a),[u,m]=k.useState([]),[f,x]=k.useState(null),[y,_]=k.useState("now"),[b,j]=k.useState(WFe(JFe(new Date),1)),[N,C]=k.useState("12"),[A,E]=k.useState("00"),[D,R]=k.useState("PM");k.useEffect(()=>{if(s){d(a),_("now"),m([]);const xe=WFe(JFe(new Date),1);j(xe);const Ee=xe.getHours();C(String(Ee>12?Ee-12:Ee===0?12:Ee)),E("00"),R(Ee>=12?"PM":"AM")}},[s,a]);const F=()=>{if(!b)return null;let xe=parseInt(N);const Ee=parseInt(A);return D==="PM"&&xe!==12&&(xe+=12),D==="AM"&&xe===12&&(xe=0),h7(u7(b,xe),Ee)},{data:O,isLoading:B}=pt({queryKey:["social-accounts-for-post"],queryFn:async()=>{const{data:{user:xe}}=await U.auth.getUser();if(!xe)return[];const{data:Ee,error:Me}=await U.from("social_accounts").select("*").eq("user_id",xe.id).eq("is_active",!0).order("platform",{ascending:!0});if(Me)throw Me;return console.log("Fetched social accounts for posting:",Ee),Ee},enabled:s,staleTime:0}),K=Mt({mutationFn:async({accountId:xe,platform:Ee})=>{x(xe);const{data:Me,error:Oe}=await U.functions.invoke("social-post",{body:{platform:Ee,accountId:xe,imageUrl:r,caption:c}});if(Oe)throw Oe;if(Me!=null&&Me.error)throw new Error(Me.error);return Me},onSuccess:xe=>{const Ee=xe.platform==="facebook"?"Facebook":xe.platform==="instagram"?"Instagram":xe.platform==="linkedin"?"LinkedIn":"Google Business";he.success(`Posted to ${Ee}!`)},onError:xe=>{he.error(`Failed to post: ${xe.message}`)},onSettled:()=>{x(null)}}),Z=Mt({mutationFn:async({accountId:xe,platform:Ee,scheduledFor:Me})=>{const{data:{user:Oe}}=await U.auth.getUser();if(!Oe)throw new Error("Not authenticated");const{error:Ie}=await U.from("scheduled_posts").insert({user_id:Oe.id,social_account_id:xe,platform:Ee,image_url:r,caption:c,swag_item_id:i||null,reel_id:l||null,scheduled_for:Me.toISOString(),status:"scheduled"});if(Ie)throw Ie;return{platform:Ee}},onSuccess:xe=>{const Ee=xe.platform==="facebook"?"Facebook":xe.platform==="instagram"?"Instagram":"LinkedIn";he.success(`Post scheduled for ${Ee}!`)},onError:xe=>{he.error(`Failed to schedule: ${xe.message}`)}}),Q=async()=>{if(u.length===0){he.error("Please select at least one account");return}if(y==="schedule"){const xe=F();if(!xe||xe<=new Date){he.error("Please select a future date and time");return}for(const Ee of u){const Me=O==null?void 0:O.find(Oe=>Oe.id===Ee);Me&&await Z.mutateAsync({accountId:Ee,platform:Me.platform,scheduledFor:xe})}o.invalidateQueries({queryKey:["scheduled-posts"]}),he.success(`${u.length} post(s) scheduled for ${As(xe,"PPp")}`)}else for(const xe of u){const Ee=O==null?void 0:O.find(Me=>Me.id===xe);Ee&&await K.mutateAsync({accountId:xe,platform:Ee.platform})}o.invalidateQueries({queryKey:["scheduled-posts"]}),d(""),m([]),t(!1)},W=xe=>{m(Ee=>Ee.includes(xe)?Ee.filter(Me=>Me!==xe):[...Ee,xe])},te=(O==null?void 0:O.filter(xe=>xe.platform==="facebook"))||[],ne=(O==null?void 0:O.filter(xe=>xe.platform==="instagram"))||[],ae=(O==null?void 0:O.filter(xe=>xe.platform==="linkedin"))||[],ue=(O==null?void 0:O.filter(xe=>xe.platform==="google_business"))||[],me=((O==null?void 0:O.length)||0)>0,de=K.isPending||Z.isPending,fe=Array.from({length:12},(xe,Ee)=>String(Ee+1)),je=["00","15","30","45"];return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create Social Post"}),e.jsx(an,{children:"Share this image to your connected social accounts"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-full max-w-[200px] mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:r,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"caption",children:"Caption"}),e.jsx(pr,{id:"caption",placeholder:"Write a caption for your post...",value:c,onChange:xe=>d(xe.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(ce,{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:zt("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:zt("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(jn,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),b?As(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:b,onSelect:j,disabled:xe=>xee.jsx(lt,{value:xe,children:xe},xe))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Ds,{value:A,onValueChange:E,children:[e.jsx(Ps,{className:"w-[70px]",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:je.map(xe=>e.jsx(lt,{value:xe,children:xe},xe))})]}),e.jsxs(Ds,{value:D,onValueChange:xe=>R(xe),children:[e.jsx(Ps,{className:"w-[70px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"AM",children:"AM"}),e.jsx(lt,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",As(F()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{children:"Post to"}),B&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ls,{className:"h-6 w-6 animate-spin"})}),!B&&!me&&e.jsxs(jAe,{children:[e.jsx(go,{className:"h-4 w-4"}),e.jsxs(NAe,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(Vn,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Bo,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),te.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"]}),te.map(xe=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Ri,{checked:u.includes(xe.id),onCheckedChange:()=>W(xe.id),disabled:f===xe.id}),e.jsxs(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:xe.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(mh,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:xe.page_name||xe.platform_username}),f===xe.id&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]},xe.id))]}),ne.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(gu,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),ne.map(xe=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Ri,{checked:u.includes(xe.id),onCheckedChange:()=>W(xe.id),disabled:f===xe.id}),e.jsxs(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:xe.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(gu,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",xe.platform_username]}),f===xe.id&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]},xe.id))]}),ae.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(Yf,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ae.map(xe=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Ri,{checked:u.includes(xe.id),onCheckedChange:()=>W(xe.id),disabled:f===xe.id}),e.jsxs(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:xe.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(Yf,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:xe.platform_username}),f===xe.id&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]},xe.id))]}),ue.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ma,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ue.map(xe=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(Ri,{checked:u.includes(xe.id),onCheckedChange:()=>W(xe.id),disabled:f===xe.id}),e.jsxs(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:xe.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(Ma,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:xe.page_name||xe.platform_username}),f===xe.id&&e.jsx(ls,{className:"h-4 w-4 animate-spin"})]},xe.id))]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:Q,disabled:u.length===0||de,className:"gap-2",children:[de?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):y==="schedule"?e.jsx(vn,{className:"h-4 w-4"}):e.jsx(hn,{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 ads(){const s=is(),[t,r]=k.useState(void 0),[n,a]=k.useState("all"),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,u]=k.useState(void 0),[m,f]=k.useState("12"),[x,y]=k.useState("00"),[_,b]=k.useState("PM"),{data:j=[],isLoading:N}=pt({queryKey:["scheduled-posts"],queryFn:async()=>{const{data:ue,error:me}=await U.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).order("scheduled_for",{ascending:!1});if(me)throw me;return ue}}),C=j.filter(ue=>{if(n!=="all"&&ue.status!==n)return!1;if(t&&ue.scheduled_for){const me=new Date(ue.scheduled_for);if(!pc(me,t))return!1}return!0}),A=j.filter(ue=>ue.scheduled_for).map(ue=>Ax(new Date(ue.scheduled_for))),E=Mt({mutationFn:async ue=>{const{error:me}=await U.from("scheduled_posts").update({caption:ue.caption,scheduled_for:ue.scheduled_for}).eq("id",ue.id);if(me)throw me},onSuccess:()=>{he.success("Post updated!"),s.invalidateQueries({queryKey:["scheduled-posts"]}),l(null)},onError:ue=>{he.error(`Failed to update: ${ue.message}`)}}),D=Mt({mutationFn:async ue=>{const{error:me}=await U.from("scheduled_posts").update({status:"cancelled"}).eq("id",ue);if(me)throw me},onSuccess:()=>{he.success("Post cancelled"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ue=>{he.error(`Failed to cancel: ${ue.message}`)}}),R=Mt({mutationFn:async ue=>{const{error:me}=await U.from("scheduled_posts").delete().eq("id",ue);if(me)throw me},onSuccess:()=>{he.success("Post deleted"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ue=>{he.error(`Failed to delete: ${ue.message}`)}}),F=Mt({mutationFn:async ue=>{const{data:me,error:de}=await U.functions.invoke("social-post",{body:{platform:ue.platform,accountId:ue.social_account_id,imageUrl:ue.image_url,caption:ue.caption}});if(de)throw de;if(me!=null&&me.error)throw new Error(me.error);return await U.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:me.postId}).eq("id",ue.id),me},onSuccess:ue=>{const me=ue.platform==="facebook"?"Facebook":ue.platform==="instagram"?"Instagram":"LinkedIn";he.success(`Posted to ${me}!`),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ue=>{he.error(`Failed to post: ${ue.message}`)}}),O=ue=>{if(l(ue),c(ue.caption||""),ue.scheduled_for){const me=new Date(ue.scheduled_for);u(me);const de=me.getHours();f(String(de>12?de-12:de===0?12:de)),y(String(me.getMinutes()).padStart(2,"0")),b(de>=12?"PM":"AM")}},B=()=>{if(!i||!d)return;let ue=parseInt(m);const me=parseInt(x);_==="PM"&&ue!==12&&(ue+=12),_==="AM"&&ue===12&&(ue=0);const de=h7(u7(d,ue),me);E.mutate({id:i.id,caption:o,scheduled_for:de.toISOString()})},K=ue=>{switch(ue){case"facebook":return e.jsx(mh,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(gu,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(Yf,{className:"h-4 w-4 text-blue-700"});default:return null}},Z=ue=>{switch(ue){case"scheduled":return e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(Xe,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Ti,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(Xe,{variant:"destructive",className:"gap-1",children:[e.jsx(ad,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(Xe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(go,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(Xe,{variant:"outline",children:ue})}},Q=Array.from({length:12},(ue,me)=>String(me+1)),W=["00","15","30","45"],te=j.filter(ue=>ue.status==="scheduled").length,ne=j.filter(ue=>ue.status==="posted").length,ae=j.filter(ue=>ue.status==="scheduled"&&ue.scheduled_for&&sFt(new Date(ue.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:te}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ae}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ne}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children: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(ke,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(xu,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(_g,{mode:"single",selected:t,onSelect:r,className:zt("pointer-events-auto"),modifiers:{hasPost:A},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),t&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>r(void 0),className:"w-full mt-2",children:"Clear date filter"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C1,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ue=>e.jsx(q,{variant:n===ue?"default":"outline",size:"sm",onClick:()=>a(ue),className:"capitalize",children:ue},ue))})]}),N&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!N&&C.length===0&&e.jsxs(ke,{className:"p-8 text-center",children:[e.jsx(vn,{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 ${As(t,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:C.map(ue=>{var me,de;return e.jsx(ke,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsx("div",{className:"sm:w-32 h-32 sm:h-auto bg-muted flex-shrink-0",children:e.jsx("img",{src:ue.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Pe,{className:"flex-1 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[K(ue.platform),e.jsx("span",{className:"font-medium",children:((me=ue.social_accounts)==null?void 0:me.page_name)||((de=ue.social_accounts)==null?void 0:de.platform_username)||"Unknown"}),Z(ue.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ue.status==="scheduled"&&e.jsxs(J_,{children:[e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>O(ue),children:e.jsx(Ua,{className:"h-4 w-4"})})}),e.jsx(Sc,{children:"Edit post"})]}),e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>F.mutate(ue),disabled:F.isPending,children:F.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"})})}),e.jsx(Sc,{children:"Post now"})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Cancel this scheduled post?"}),e.jsx(Ho,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Keep"}),e.jsx(Oo,{onClick:()=>D.mutate(ue.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(Oo,{onClick:()=>R.mutate(ue.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ue.status==="posted"||ue.status==="cancelled"||ue.status==="failed")&&e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete this post?"}),e.jsx(Ho,{children:"This will permanently remove this post from your history."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>R.mutate(ue.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ue.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ue.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),ue.status==="posted"&&ue.posted_at?`Posted ${As(new Date(ue.posted_at),"PPp")}`:ue.scheduled_for?`Scheduled for ${As(new Date(ue.scheduled_for),"PPp")}`:"Not scheduled"]}),ue.status==="failed"&&ue.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ue.error_message]})]})]})},ue.id)})})]})]}),e.jsx(vs,{open:!!i,onOpenChange:ue=>!ue&&l(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Edit Scheduled Post"}),e.jsx(an,{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(ce,{children:"Caption"}),e.jsx(pr,{value:o,onChange:ue=>c(ue.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(ce,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("justify-start text-left font-normal flex-1",!d&&"text-muted-foreground"),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),d?As(d,"PPP"):"Pick a date"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:d,onSelect:u,disabled:ue=>uee.jsx(lt,{value:ue,children:ue},ue))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Ds,{value:x,onValueChange:y,children:[e.jsx(Ps,{className:"w-[70px]",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:W.map(ue=>e.jsx(lt,{value:ue,children:ue},ue))})]}),e.jsxs(Ds,{value:_,onValueChange:ue=>b(ue),children:[e.jsx(Ps,{className:"w-[70px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"AM",children:"AM"}),e.jsx(lt,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(q,{onClick:B,disabled:E.isPending,children:[E.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function Fq(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 Ght={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */(function(s,t){(function(r){s.exports=r()})(function(){return function r(n,a,i){function l(d,u){if(!a[d]){if(!n[d]){var m=typeof Fq=="function"&&Fq;if(!u&&m)return m(d,!0);if(o)return o(d,!0);var f=new Error("Cannot find module '"+d+"'");throw f.code="MODULE_NOT_FOUND",f}var x=a[d]={exports:{}};n[d][0].call(x.exports,function(y){var _=n[d][1][y];return l(_||y)},x,x.exports,r,n,a,i)}return a[d].exports}for(var o=typeof Fq=="function"&&Fq,c=0;c>2,x=(3&d)<<4|u>>4,y=1>6:64,_=2>4,u=(15&f)<<4|(x=o.indexOf(c.charAt(_++)))>>2,m=(3&x)<<6|(y=o.indexOf(c.charAt(_++))),N[b++]=d,x!==64&&(N[b++]=u),y!==64&&(N[b++]=m);return N}},{"./support":30,"./utils":32}],2:[function(r,n,a){var i=r("./external"),l=r("./stream/DataWorker"),o=r("./stream/Crc32Probe"),c=r("./stream/DataLengthProbe");function d(u,m,f,x,y){this.compressedSize=u,this.uncompressedSize=m,this.crc32=f,this.compression=x,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")),m=this;return u.on("end",function(){if(this.streamInfo.data_length!==m.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,m,f){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(m.compressWorker(f)).pipe(new c("compressedSize")).withStreamInfo("compression",m)},n.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,n,a){var i=r("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,n,a){var i=r("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();n.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,m,f){var x=l,y=f+m;d^=-1;for(var _=f;_>>8^x[255&(d^u[_])];return-1^d}(0|c,o,o.length,0):function(d,u,m,f){var x=l,y=f+m;d^=-1;for(var _=f;_>>8^x[255&(d^u.charCodeAt(_))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(r,n,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(r,n,a){var i=null;i=typeof Promise<"u"?Promise:r("lie"),n.exports={Promise:i}},{lie:37}],7:[function(r,n,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=r("pako"),o=r("./utils"),c=r("./stream/GenericWorker"),d=i?"uint8array":"array";function u(m,f){c.call(this,"FlateWorker/"+m),this._pako=null,this._pakoAction=m,this._pakoOptions=f,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(m){this.meta=m.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,m.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 m=this;this._pako.onData=function(f){m.push({data:f,meta:m.meta})}},a.compressWorker=function(m){return new u("Deflate",m)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,n,a){function i(x,y){var _,b="";for(_=0;_>>=8;return b}function l(x,y,_,b,j,N){var C,A,E=x.file,D=x.compression,R=N!==d.utf8encode,F=o.transformTo("string",N(E.name)),O=o.transformTo("string",d.utf8encode(E.name)),B=E.comment,K=o.transformTo("string",N(B)),Z=o.transformTo("string",d.utf8encode(B)),Q=O.length!==E.name.length,W=Z.length!==B.length,te="",ne="",ae="",ue=E.dir,me=E.date,de={crc32:0,compressedSize:0,uncompressedSize:0};y&&!_||(de.crc32=x.crc32,de.compressedSize=x.compressedSize,de.uncompressedSize=x.uncompressedSize);var fe=0;y&&(fe|=8),R||!Q&&!W||(fe|=2048);var je=0,xe=0;ue&&(je|=16),j==="UNIX"?(xe=798,je|=function(Me,Oe){var Ie=Me;return Me||(Ie=Oe?16893:33204),(65535&Ie)<<16}(E.unixPermissions,ue)):(xe=20,je|=function(Me){return 63&(Me||0)}(E.dosPermissions)),C=me.getUTCHours(),C<<=6,C|=me.getUTCMinutes(),C<<=5,C|=me.getUTCSeconds()/2,A=me.getUTCFullYear()-1980,A<<=4,A|=me.getUTCMonth()+1,A<<=5,A|=me.getUTCDate(),Q&&(ne=i(1,1)+i(u(F),4)+O,te+="up"+i(ne.length,2)+ne),W&&(ae=i(1,1)+i(u(K),4)+Z,te+="uc"+i(ae.length,2)+ae);var Ee="";return Ee+=` \0`,Ee+=i(fe,2),Ee+=D.magic,Ee+=i(C,2),Ee+=i(A,2),Ee+=i(de.crc32,4),Ee+=i(de.compressedSize,4),Ee+=i(de.uncompressedSize,4),Ee+=i(F.length,2),Ee+=i(te.length,2),{fileRecord:m.LOCAL_FILE_HEADER+Ee+F+te,dirRecord:m.CENTRAL_FILE_HEADER+i(xe,2)+Ee+i(K.length,2)+"\0\0\0\0"+i(je,4)+i(b,4)+F+te+K}}var o=r("../utils"),c=r("../stream/GenericWorker"),d=r("../utf8"),u=r("../crc32"),m=r("../signature");function f(x,y,_,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=y,this.zipPlatform=_,this.encodeFileName=b,this.streamFiles=x,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(f,c),f.prototype.push=function(x){var y=x.meta.percent||0,_=this.entriesCount,b=this._sources.length;this.accumulate?this.contentBuffer.push(x):(this.bytesWritten+=x.data.length,c.prototype.push.call(this,{data:x.data,meta:{currentFile:this.currentFile,percent:_?(y+100*(_-b-1))/_:100}}))},f.prototype.openedSource=function(x){this.currentSourceOffset=this.bytesWritten,this.currentFile=x.file.name;var y=this.streamFiles&&!x.file.dir;if(y){var _=l(x,y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:_.fileRecord,meta:{percent:0}})}else this.accumulate=!0},f.prototype.closedSource=function(x){this.accumulate=!1;var y=this.streamFiles&&!x.file.dir,_=l(x,y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(_.dirRecord),y)this.push({data:function(b){return m.DATA_DESCRIPTOR+i(b.crc32,4)+i(b.compressedSize,4)+i(b.uncompressedSize,4)}(x),meta:{percent:100}});else for(this.push({data:_.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},f.prototype.flush=function(){for(var x=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))}},n.exports=l},{"../utils":32}],19:[function(r,n,a){var i=r("./Uint8ArrayReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,n,a){var i=r("./DataReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./DataReader":18}],21:[function(r,n,a){var i=r("./ArrayReader");function l(o){i.call(this,o)}r("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},n.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(r,n,a){var i=r("../utils"),l=r("../support"),o=r("./ArrayReader"),c=r("./StringReader"),d=r("./NodeBufferReader"),u=r("./Uint8ArrayReader");n.exports=function(m){var f=i.getTypeOf(m);return i.checkSupport(f),f!=="string"||l.uint8array?f==="nodebuffer"?new d(m):l.uint8array?new u(i.transformTo("uint8array",m)):new o(i.transformTo("array",m)):new c(m)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(r,n,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(r,n,a){var i=r("./GenericWorker"),l=r("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},n.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(r,n,a){var i=r("./GenericWorker"),l=r("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},n.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,n,a){var i=r("../utils"),l=r("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},n.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(r,n,a){var i=r("../utils"),l=r("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(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}})},n.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(r,n,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},n.exports=i},{}],29:[function(r,n,a){var i=r("../utils"),l=r("./ConvertWorker"),o=r("./GenericWorker"),c=r("../base64"),d=r("../support"),u=r("../external"),m=null;if(d.nodestream)try{m=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function f(y,_){return new u.Promise(function(b,j){var N=[],C=y._internalType,A=y._outputType,E=y._mimeType;y.on("data",function(D,R){N.push(D),_&&_(R)}).on("error",function(D){N=[],j(D)}).on("end",function(){try{var D=function(R,F,O){switch(R){case"blob":return i.newBlob(i.transformTo("arraybuffer",F),O);case"base64":return c.encode(F);default:return i.transformTo(R,F)}}(A,function(R,F){var O,B=0,K=null,Z=0;for(O=0;O"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!r("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(r,n,a){for(var i=r("./utils"),l=r("./support"),o=r("./nodejsUtils"),c=r("./stream/GenericWorker"),d=new Array(256),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 m(){c.call(this,"utf-8 decode"),this.leftOver=null}function f(){c.call(this,"utf-8 encode")}a.utf8encode=function(x){return l.nodebuffer?o.newBufferFrom(x,"utf-8"):function(y){var _,b,j,N,C,A=y.length,E=0;for(N=0;N>>6:(b<65536?_[C++]=224|b>>>12:(_[C++]=240|b>>>18,_[C++]=128|b>>>12&63),_[C++]=128|b>>>6&63),_[C++]=128|63&b);return _}(x)},a.utf8decode=function(x){return l.nodebuffer?i.transformTo("nodebuffer",x).toString("utf-8"):function(y){var _,b,j,N,C=y.length,A=new Array(2*C);for(_=b=0;_>10&1023,A[b++]=56320|1023&j)}return A.length!==b&&(A.subarray?A=A.subarray(0,b):A.length=b),i.applyFromCharCode(A)}(x=i.transformTo(l.uint8array?"uint8array":"array",x))},i.inherits(m,c),m.prototype.processChunk=function(x){var y=i.transformTo(l.uint8array?"uint8array":"array",x.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 b=function(N,C){var A;for((C=C||N.length)>N.length&&(C=N.length),A=C-1;0<=A&&(192&N[A])==128;)A--;return A<0||A===0?C:A+d[N[A]]>C?A:C}(y),j=y;b!==y.length&&(l.uint8array?(j=y.subarray(0,b),this.leftOver=y.subarray(b,y.length)):(j=y.slice(0,b),this.leftOver=y.slice(b,y.length))),this.push({data:a.utf8decode(j),meta:x.meta})},m.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=m,i.inherits(f,c),f.prototype.processChunk=function(x){this.push({data:a.utf8encode(x.data),meta:x.meta})},a.Utf8EncodeWorker=f},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,n,a){var i=r("./support"),l=r("./base64"),o=r("./nodejsUtils"),c=r("./external");function d(_){return _}function u(_,b){for(var j=0;j<_.length;++j)b[j]=255&_.charCodeAt(j);return b}r("setimmediate"),a.newBlob=function(_,b){a.checkSupport("blob");try{return new Blob([_],{type:b})}catch{try{var j=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return j.append(_),j.getBlob(b)}catch{throw new Error("Bug : can't construct the Blob.")}}};var m={stringifyByChunk:function(_,b,j){var N=[],C=0,A=_.length;if(A<=j)return String.fromCharCode.apply(null,_);for(;C>8;this.dir=!!(16&this.externalFileAttributes),x==0&&(this.dosPermissions=63&this.externalFileAttributes),x==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var x=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=x.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=x.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=x.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=x.readInt(4))}},readExtraFields:function(x){var y,_,b,j=x.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});x.index+4>>6:(x<65536?f[b++]=224|x>>>12:(f[b++]=240|x>>>18,f[b++]=128|x>>>12&63),f[b++]=128|x>>>6&63),f[b++]=128|63&x);return f},a.buf2binstring=function(m){return u(m,m.length)},a.binstring2buf=function(m){for(var f=new i.Buf8(m.length),x=0,y=f.length;x>10&1023,N[y++]=56320|1023&_)}return u(N,y)},a.utf8border=function(m,f){var x;for((f=f||m.length)>m.length&&(f=m.length),x=f-1;0<=x&&(192&m[x])==128;)x--;return x<0||x===0?f:x+c[m[x]]>f?x:f}},{"./common":41}],43:[function(r,n,a){n.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,m=0;o!==0;){for(o-=m=2e3>>1:l>>>1;o[c]=l}return o}();n.exports=function(l,o,c,d){var u=i,m=d+c;l^=-1;for(var f=d;f>>8^u[255&(l^o[f])];return-1^l}},{}],46:[function(r,n,a){var i,l=r("../utils/common"),o=r("./trees"),c=r("./adler32"),d=r("./crc32"),u=r("./messages"),m=0,f=4,x=0,y=-2,_=-1,b=4,j=2,N=8,C=9,A=286,E=30,D=19,R=2*A+1,F=15,O=3,B=258,K=B+O+1,Z=42,Q=113,W=1,te=2,ne=3,ae=4;function ue(we,nt){return we.msg=u[nt],nt}function me(we){return(we<<1)-(4we.avail_out&&(Se=we.avail_out),Se!==0&&(l.arraySet(we.output,nt.pending_buf,nt.pending_out,Se,we.next_out),we.next_out+=Se,nt.pending_out+=Se,we.total_out+=Se,we.avail_out-=Se,nt.pending-=Se,nt.pending===0&&(nt.pending_out=0))}function je(we,nt){o._tr_flush_block(we,0<=we.block_start?we.block_start:-1,we.strstart-we.block_start,nt),we.block_start=we.strstart,fe(we.strm)}function xe(we,nt){we.pending_buf[we.pending++]=nt}function Ee(we,nt){we.pending_buf[we.pending++]=nt>>>8&255,we.pending_buf[we.pending++]=255&nt}function Me(we,nt){var Se,Ge,We=we.max_chain_length,Ce=we.strstart,qe=we.prev_length,et=we.nice_match,Ze=we.strstart>we.w_size-K?we.strstart-(we.w_size-K):0,rt=we.window,ct=we.w_mask,vt=we.prev,kt=we.strstart+B,St=rt[Ce+qe-1],Yt=rt[Ce+qe];we.prev_length>=we.good_match&&(We>>=2),et>we.lookahead&&(et=we.lookahead);do if(rt[(Se=nt)+qe]===Yt&&rt[Se+qe-1]===St&&rt[Se]===rt[Ce]&&rt[++Se]===rt[Ce+1]){Ce+=2,Se++;do;while(rt[++Ce]===rt[++Se]&&rt[++Ce]===rt[++Se]&&rt[++Ce]===rt[++Se]&&rt[++Ce]===rt[++Se]&&rt[++Ce]===rt[++Se]&&rt[++Ce]===rt[++Se]&&rt[++Ce]===rt[++Se]&&rt[++Ce]===rt[++Se]&&CeZe&&--We!=0);return qe<=we.lookahead?qe:we.lookahead}function Oe(we){var nt,Se,Ge,We,Ce,qe,et,Ze,rt,ct,vt=we.w_size;do{if(We=we.window_size-we.lookahead-we.strstart,we.strstart>=vt+(vt-K)){for(l.arraySet(we.window,we.window,vt,vt,0),we.match_start-=vt,we.strstart-=vt,we.block_start-=vt,nt=Se=we.hash_size;Ge=we.head[--nt],we.head[nt]=vt<=Ge?Ge-vt:0,--Se;);for(nt=Se=vt;Ge=we.prev[--nt],we.prev[nt]=vt<=Ge?Ge-vt:0,--Se;);We+=vt}if(we.strm.avail_in===0)break;if(qe=we.strm,et=we.window,Ze=we.strstart+we.lookahead,rt=We,ct=void 0,ct=qe.avail_in,rt=O)for(Ce=we.strstart-we.insert,we.ins_h=we.window[Ce],we.ins_h=(we.ins_h<=O&&(we.ins_h=(we.ins_h<=O)if(Ge=o._tr_tally(we,we.strstart-we.match_start,we.match_length-O),we.lookahead-=we.match_length,we.match_length<=we.max_lazy_match&&we.lookahead>=O){for(we.match_length--;we.strstart++,we.ins_h=(we.ins_h<=O&&(we.ins_h=(we.ins_h<=O&&we.match_length<=we.prev_length){for(We=we.strstart+we.lookahead-O,Ge=o._tr_tally(we,we.strstart-1-we.prev_match,we.prev_length-O),we.lookahead-=we.prev_length-1,we.prev_length-=2;++we.strstart<=We&&(we.ins_h=(we.ins_h<we.pending_buf_size-5&&(Se=we.pending_buf_size-5);;){if(we.lookahead<=1){if(Oe(we),we.lookahead===0&&nt===m)return W;if(we.lookahead===0)break}we.strstart+=we.lookahead,we.lookahead=0;var Ge=we.block_start+Se;if((we.strstart===0||we.strstart>=Ge)&&(we.lookahead=we.strstart-Ge,we.strstart=Ge,je(we,!1),we.strm.avail_out===0)||we.strstart-we.block_start>=we.w_size-K&&(je(we,!1),we.strm.avail_out===0))return W}return we.insert=0,nt===f?(je(we,!0),we.strm.avail_out===0?ne:ae):(we.strstart>we.block_start&&(je(we,!1),we.strm.avail_out),W)}),new Ve(4,4,8,4,Ie),new Ve(4,5,16,8,Ie),new Ve(4,6,32,32,Ie),new Ve(4,4,16,16,ze),new Ve(8,16,32,32,ze),new Ve(8,16,128,128,ze),new Ve(8,32,128,256,ze),new Ve(32,128,258,1024,ze),new Ve(32,258,258,4096,ze)],a.deflateInit=function(we,nt){return Qe(we,nt,N,15,8,0)},a.deflateInit2=Qe,a.deflateReset=ve,a.deflateResetKeep=$e,a.deflateSetHeader=function(we,nt){return we&&we.state?we.state.wrap!==2?y:(we.state.gzhead=nt,x):y},a.deflate=function(we,nt){var Se,Ge,We,Ce;if(!we||!we.state||5>8&255),xe(Ge,Ge.gzhead.time>>16&255),xe(Ge,Ge.gzhead.time>>24&255),xe(Ge,Ge.level===9?2:2<=Ge.strategy||Ge.level<2?4:0),xe(Ge,255&Ge.gzhead.os),Ge.gzhead.extra&&Ge.gzhead.extra.length&&(xe(Ge,255&Ge.gzhead.extra.length),xe(Ge,Ge.gzhead.extra.length>>8&255)),Ge.gzhead.hcrc&&(we.adler=d(we.adler,Ge.pending_buf,Ge.pending,0)),Ge.gzindex=0,Ge.status=69):(xe(Ge,0),xe(Ge,0),xe(Ge,0),xe(Ge,0),xe(Ge,0),xe(Ge,Ge.level===9?2:2<=Ge.strategy||Ge.level<2?4:0),xe(Ge,3),Ge.status=Q);else{var qe=N+(Ge.w_bits-8<<4)<<8;qe|=(2<=Ge.strategy||Ge.level<2?0:Ge.level<6?1:Ge.level===6?2:3)<<6,Ge.strstart!==0&&(qe|=32),qe+=31-qe%31,Ge.status=Q,Ee(Ge,qe),Ge.strstart!==0&&(Ee(Ge,we.adler>>>16),Ee(Ge,65535&we.adler)),we.adler=1}if(Ge.status===69)if(Ge.gzhead.extra){for(We=Ge.pending;Ge.gzindex<(65535&Ge.gzhead.extra.length)&&(Ge.pending!==Ge.pending_buf_size||(Ge.gzhead.hcrc&&Ge.pending>We&&(we.adler=d(we.adler,Ge.pending_buf,Ge.pending-We,We)),fe(we),We=Ge.pending,Ge.pending!==Ge.pending_buf_size));)xe(Ge,255&Ge.gzhead.extra[Ge.gzindex]),Ge.gzindex++;Ge.gzhead.hcrc&&Ge.pending>We&&(we.adler=d(we.adler,Ge.pending_buf,Ge.pending-We,We)),Ge.gzindex===Ge.gzhead.extra.length&&(Ge.gzindex=0,Ge.status=73)}else Ge.status=73;if(Ge.status===73)if(Ge.gzhead.name){We=Ge.pending;do{if(Ge.pending===Ge.pending_buf_size&&(Ge.gzhead.hcrc&&Ge.pending>We&&(we.adler=d(we.adler,Ge.pending_buf,Ge.pending-We,We)),fe(we),We=Ge.pending,Ge.pending===Ge.pending_buf_size)){Ce=1;break}Ce=Ge.gzindexWe&&(we.adler=d(we.adler,Ge.pending_buf,Ge.pending-We,We)),Ce===0&&(Ge.gzindex=0,Ge.status=91)}else Ge.status=91;if(Ge.status===91)if(Ge.gzhead.comment){We=Ge.pending;do{if(Ge.pending===Ge.pending_buf_size&&(Ge.gzhead.hcrc&&Ge.pending>We&&(we.adler=d(we.adler,Ge.pending_buf,Ge.pending-We,We)),fe(we),We=Ge.pending,Ge.pending===Ge.pending_buf_size)){Ce=1;break}Ce=Ge.gzindexWe&&(we.adler=d(we.adler,Ge.pending_buf,Ge.pending-We,We)),Ce===0&&(Ge.status=103)}else Ge.status=103;if(Ge.status===103&&(Ge.gzhead.hcrc?(Ge.pending+2>Ge.pending_buf_size&&fe(we),Ge.pending+2<=Ge.pending_buf_size&&(xe(Ge,255&we.adler),xe(Ge,we.adler>>8&255),we.adler=0,Ge.status=Q)):Ge.status=Q),Ge.pending!==0){if(fe(we),we.avail_out===0)return Ge.last_flush=-1,x}else if(we.avail_in===0&&me(nt)<=me(Se)&&nt!==f)return ue(we,-5);if(Ge.status===666&&we.avail_in!==0)return ue(we,-5);if(we.avail_in!==0||Ge.lookahead!==0||nt!==m&&Ge.status!==666){var et=Ge.strategy===2?function(Ze,rt){for(var ct;;){if(Ze.lookahead===0&&(Oe(Ze),Ze.lookahead===0)){if(rt===m)return W;break}if(Ze.match_length=0,ct=o._tr_tally(Ze,0,Ze.window[Ze.strstart]),Ze.lookahead--,Ze.strstart++,ct&&(je(Ze,!1),Ze.strm.avail_out===0))return W}return Ze.insert=0,rt===f?(je(Ze,!0),Ze.strm.avail_out===0?ne:ae):Ze.last_lit&&(je(Ze,!1),Ze.strm.avail_out===0)?W:te}(Ge,nt):Ge.strategy===3?function(Ze,rt){for(var ct,vt,kt,St,Yt=Ze.window;;){if(Ze.lookahead<=B){if(Oe(Ze),Ze.lookahead<=B&&rt===m)return W;if(Ze.lookahead===0)break}if(Ze.match_length=0,Ze.lookahead>=O&&0Ze.lookahead&&(Ze.match_length=Ze.lookahead)}if(Ze.match_length>=O?(ct=o._tr_tally(Ze,1,Ze.match_length-O),Ze.lookahead-=Ze.match_length,Ze.strstart+=Ze.match_length,Ze.match_length=0):(ct=o._tr_tally(Ze,0,Ze.window[Ze.strstart]),Ze.lookahead--,Ze.strstart++),ct&&(je(Ze,!1),Ze.strm.avail_out===0))return W}return Ze.insert=0,rt===f?(je(Ze,!0),Ze.strm.avail_out===0?ne:ae):Ze.last_lit&&(je(Ze,!1),Ze.strm.avail_out===0)?W:te}(Ge,nt):i[Ge.level].func(Ge,nt);if(et!==ne&&et!==ae||(Ge.status=666),et===W||et===ne)return we.avail_out===0&&(Ge.last_flush=-1),x;if(et===te&&(nt===1?o._tr_align(Ge):nt!==5&&(o._tr_stored_block(Ge,0,0,!1),nt===3&&(de(Ge.head),Ge.lookahead===0&&(Ge.strstart=0,Ge.block_start=0,Ge.insert=0))),fe(we),we.avail_out===0))return Ge.last_flush=-1,x}return nt!==f?x:Ge.wrap<=0?1:(Ge.wrap===2?(xe(Ge,255&we.adler),xe(Ge,we.adler>>8&255),xe(Ge,we.adler>>16&255),xe(Ge,we.adler>>24&255),xe(Ge,255&we.total_in),xe(Ge,we.total_in>>8&255),xe(Ge,we.total_in>>16&255),xe(Ge,we.total_in>>24&255)):(Ee(Ge,we.adler>>>16),Ee(Ge,65535&we.adler)),fe(we),0=Se.w_size&&(Ce===0&&(de(Se.head),Se.strstart=0,Se.block_start=0,Se.insert=0),rt=new l.Buf8(Se.w_size),l.arraySet(rt,nt,ct-Se.w_size,Se.w_size,0),nt=rt,ct=Se.w_size),qe=we.avail_in,et=we.next_in,Ze=we.input,we.avail_in=ct,we.next_in=0,we.input=nt,Oe(Se);Se.lookahead>=O;){for(Ge=Se.strstart,We=Se.lookahead-(O-1);Se.ins_h=(Se.ins_h<>>=O=F>>>24,C-=O,(O=F>>>16&255)===0)te[u++]=65535&F;else{if(!(16&O)){if(!(64&O)){F=A[(65535&F)+(N&(1<>>=O,C-=O),C<15&&(N+=W[c++]<>>=O=F>>>24,C-=O,!(16&(O=F>>>16&255))){if(!(64&O)){F=E[(65535&F)+(N&(1<>>=O,C-=O,(O=u-m)>3,N&=(1<<(C-=B<<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 N(){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 C(Z){var Q;return Z&&Z.state?(Q=Z.state,Z.total_in=Z.total_out=Q.total=0,Z.msg="",Q.wrap&&(Z.adler=1&Q.wrap),Q.mode=y,Q.last=0,Q.havedict=0,Q.dmax=32768,Q.head=null,Q.hold=0,Q.bits=0,Q.lencode=Q.lendyn=new i.Buf32(_),Q.distcode=Q.distdyn=new i.Buf32(b),Q.sane=1,Q.back=-1,f):x}function A(Z){var Q;return Z&&Z.state?((Q=Z.state).wsize=0,Q.whave=0,Q.wnext=0,C(Z)):x}function E(Z,Q){var W,te;return Z&&Z.state?(te=Z.state,Q<0?(W=0,Q=-Q):(W=1+(Q>>4),Q<48&&(Q&=15)),Q&&(Q<8||15=ae.wsize?(i.arraySet(ae.window,Q,W-ae.wsize,ae.wsize,0),ae.wnext=0,ae.whave=ae.wsize):(te<(ne=ae.wsize-ae.wnext)&&(ne=te),i.arraySet(ae.window,Q,W-te,ne,ae.wnext),(te-=ne)?(i.arraySet(ae.window,Q,W-te,te,0),ae.wnext=te,ae.whave=ae.wsize):(ae.wnext+=ne,ae.wnext===ae.wsize&&(ae.wnext=0),ae.whave>>8&255,W.check=o(W.check,Ce,2,0),je=fe=0,W.mode=2;break}if(W.flags=0,W.head&&(W.head.done=!1),!(1&W.wrap)||(((255&fe)<<8)+(fe>>8))%31){Z.msg="incorrect header check",W.mode=30;break}if((15&fe)!=8){Z.msg="unknown compression method",W.mode=30;break}if(je-=4,we=8+(15&(fe>>>=4)),W.wbits===0)W.wbits=we;else if(we>W.wbits){Z.msg="invalid window size",W.mode=30;break}W.dmax=1<>8&1),512&W.flags&&(Ce[0]=255&fe,Ce[1]=fe>>>8&255,W.check=o(W.check,Ce,2,0)),je=fe=0,W.mode=3;case 3:for(;je<32;){if(me===0)break e;me--,fe+=te[ae++]<>>8&255,Ce[2]=fe>>>16&255,Ce[3]=fe>>>24&255,W.check=o(W.check,Ce,4,0)),je=fe=0,W.mode=4;case 4:for(;je<16;){if(me===0)break e;me--,fe+=te[ae++]<>8),512&W.flags&&(Ce[0]=255&fe,Ce[1]=fe>>>8&255,W.check=o(W.check,Ce,2,0)),je=fe=0,W.mode=5;case 5:if(1024&W.flags){for(;je<16;){if(me===0)break e;me--,fe+=te[ae++]<>>8&255,W.check=o(W.check,Ce,2,0)),je=fe=0}else W.head&&(W.head.extra=null);W.mode=6;case 6:if(1024&W.flags&&(me<(Me=W.length)&&(Me=me),Me&&(W.head&&(we=W.head.extra_len-W.length,W.head.extra||(W.head.extra=new Array(W.head.extra_len)),i.arraySet(W.head.extra,te,ae,Me,we)),512&W.flags&&(W.check=o(W.check,te,Me,ae)),me-=Me,ae+=Me,W.length-=Me),W.length))break e;W.length=0,W.mode=7;case 7:if(2048&W.flags){if(me===0)break e;for(Me=0;we=te[ae+Me++],W.head&&we&&W.length<65536&&(W.head.name+=String.fromCharCode(we)),we&&Me>9&1,W.head.done=!0),Z.adler=W.check=0,W.mode=12;break;case 10:for(;je<32;){if(me===0)break e;me--,fe+=te[ae++]<>>=7&je,je-=7&je,W.mode=27;break}for(;je<3;){if(me===0)break e;me--,fe+=te[ae++]<>>=1)){case 0:W.mode=14;break;case 1:if(B(W),W.mode=20,Q!==6)break;fe>>>=2,je-=2;break e;case 2:W.mode=17;break;case 3:Z.msg="invalid block type",W.mode=30}fe>>>=2,je-=2;break;case 14:for(fe>>>=7&je,je-=7&je;je<32;){if(me===0)break e;me--,fe+=te[ae++]<>>16^65535)){Z.msg="invalid stored block lengths",W.mode=30;break}if(W.length=65535&fe,je=fe=0,W.mode=15,Q===6)break e;case 15:W.mode=16;case 16:if(Me=W.length){if(me>>=5,je-=5,W.ndist=1+(31&fe),fe>>>=5,je-=5,W.ncode=4+(15&fe),fe>>>=4,je-=4,286>>=3,je-=3}for(;W.have<19;)W.lens[qe[W.have++]]=0;if(W.lencode=W.lendyn,W.lenbits=7,Se={bits:W.lenbits},nt=d(0,W.lens,0,19,W.lencode,0,W.work,Se),W.lenbits=Se.bits,nt){Z.msg="invalid code lengths set",W.mode=30;break}W.have=0,W.mode=19;case 19:for(;W.have>>16&255,Le=65535&We,!((ze=We>>>24)<=je);){if(me===0)break e;me--,fe+=te[ae++]<>>=ze,je-=ze,W.lens[W.have++]=Le;else{if(Le===16){for(Ge=ze+2;je>>=ze,je-=ze,W.have===0){Z.msg="invalid bit length repeat",W.mode=30;break}we=W.lens[W.have-1],Me=3+(3&fe),fe>>>=2,je-=2}else if(Le===17){for(Ge=ze+3;je>>=ze)),fe>>>=3,je-=3}else{for(Ge=ze+7;je>>=ze)),fe>>>=7,je-=7}if(W.have+Me>W.nlen+W.ndist){Z.msg="invalid bit length repeat",W.mode=30;break}for(;Me--;)W.lens[W.have++]=we}}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,Se={bits:W.lenbits},nt=d(u,W.lens,0,W.nlen,W.lencode,0,W.work,Se),W.lenbits=Se.bits,nt){Z.msg="invalid literal/lengths set",W.mode=30;break}if(W.distbits=6,W.distcode=W.distdyn,Se={bits:W.distbits},nt=d(m,W.lens,W.nlen,W.ndist,W.distcode,0,W.work,Se),W.distbits=Se.bits,nt){Z.msg="invalid distances set",W.mode=30;break}if(W.mode=20,Q===6)break e;case 20:W.mode=21;case 21:if(6<=me&&258<=de){Z.next_out=ue,Z.avail_out=de,Z.next_in=ae,Z.avail_in=me,W.hold=fe,W.bits=je,c(Z,Ee),ue=Z.next_out,ne=Z.output,de=Z.avail_out,ae=Z.next_in,te=Z.input,me=Z.avail_in,fe=W.hold,je=W.bits,W.mode===12&&(W.back=-1);break}for(W.back=0;Ve=(We=W.lencode[fe&(1<>>16&255,Le=65535&We,!((ze=We>>>24)<=je);){if(me===0)break e;me--,fe+=te[ae++]<>$e)])>>>16&255,Le=65535&We,!($e+(ze=We>>>24)<=je);){if(me===0)break e;me--,fe+=te[ae++]<>>=$e,je-=$e,W.back+=$e}if(fe>>>=ze,je-=ze,W.back+=ze,W.length=Le,Ve===0){W.mode=26;break}if(32&Ve){W.back=-1,W.mode=12;break}if(64&Ve){Z.msg="invalid literal/length code",W.mode=30;break}W.extra=15&Ve,W.mode=22;case 22:if(W.extra){for(Ge=W.extra;je>>=W.extra,je-=W.extra,W.back+=W.extra}W.was=W.length,W.mode=23;case 23:for(;Ve=(We=W.distcode[fe&(1<>>16&255,Le=65535&We,!((ze=We>>>24)<=je);){if(me===0)break e;me--,fe+=te[ae++]<>$e)])>>>16&255,Le=65535&We,!($e+(ze=We>>>24)<=je);){if(me===0)break e;me--,fe+=te[ae++]<>>=$e,je-=$e,W.back+=$e}if(fe>>>=ze,je-=ze,W.back+=ze,64&Ve){Z.msg="invalid distance code",W.mode=30;break}W.offset=Le,W.extra=15&Ve,W.mode=24;case 24:if(W.extra){for(Ge=W.extra;je>>=W.extra,je-=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(de===0)break e;if(Me=Ee-de,W.offset>Me){if((Me=W.offset-Me)>W.whave&&W.sane){Z.msg="invalid distance too far back",W.mode=30;break}Oe=Me>W.wnext?(Me-=W.wnext,W.wsize-Me):W.wnext-Me,Me>W.length&&(Me=W.length),Ie=W.window}else Ie=ne,Oe=ue-W.offset,Me=W.length;for(deR?(O=Oe[Ie+b[Q]],je[xe+b[Q]]):(O=96,0),N=1<>ue)+(C-=N)]=F<<24|O<<16|B|0,C!==0;);for(N=1<>=1;if(N!==0?(fe&=N-1,fe+=N):fe=0,Q++,--Ee[Z]==0){if(Z===te)break;Z=m[f+b[Q]]}if(ne>>7)]}function xe(We,Ce){We.pending_buf[We.pending++]=255&Ce,We.pending_buf[We.pending++]=Ce>>>8&255}function Ee(We,Ce,qe){We.bi_valid>j-qe?(We.bi_buf|=Ce<>j-We.bi_valid,We.bi_valid+=qe-j):(We.bi_buf|=Ce<>>=1,qe<<=1,0<--Ce;);return qe>>>1}function Ie(We,Ce,qe){var et,Ze,rt=new Array(b+1),ct=0;for(et=1;et<=b;et++)rt[et]=ct=ct+qe[et-1]<<1;for(Ze=0;Ze<=Ce;Ze++){var vt=We[2*Ze+1];vt!==0&&(We[2*Ze]=Oe(rt[vt]++,vt))}}function ze(We){var Ce;for(Ce=0;Ce>1;1<=qe;qe--)$e(We,rt,qe);for(Ze=kt;qe=We.heap[1],We.heap[1]=We.heap[We.heap_len--],$e(We,rt,1),et=We.heap[1],We.heap[--We.heap_max]=qe,We.heap[--We.heap_max]=et,rt[2*Ze]=rt[2*qe]+rt[2*et],We.depth[Ze]=(We.depth[qe]>=We.depth[et]?We.depth[qe]:We.depth[et])+1,rt[2*qe+1]=rt[2*et+1]=Ze,We.heap[1]=Ze++,$e(We,rt,1),2<=We.heap_len;);We.heap[--We.heap_max]=We.heap[1],function(Yt,es){var zs,sr,ms,gt,Ut,ht,Jt=es.dyn_tree,Ms=es.max_code,ts=es.stat_desc.static_tree,Xs=es.stat_desc.has_stree,js=es.stat_desc.extra_bits,$s=es.stat_desc.extra_base,Js=es.stat_desc.max_length,or=0;for(gt=0;gt<=b;gt++)Yt.bl_count[gt]=0;for(Jt[2*Yt.heap[Yt.heap_max]+1]=0,zs=Yt.heap_max+1;zs<_;zs++)Js<(gt=Jt[2*Jt[2*(sr=Yt.heap[zs])+1]+1]+1)&&(gt=Js,or++),Jt[2*sr+1]=gt,Ms>=7;Ze>>=1)if(1&St&&vt.dyn_ltree[2*kt]!==0)return l;if(vt.dyn_ltree[18]!==0||vt.dyn_ltree[20]!==0||vt.dyn_ltree[26]!==0)return o;for(kt=32;kt>>3,(rt=We.static_len+3+7>>>3)<=Ze&&(Ze=rt)):Ze=rt=qe+5,qe+4<=Ze&&Ce!==-1?Ge(We,Ce,qe,et):We.strategy===4||rt===Ze?(Ee(We,2+(et?1:0),3),ve(We,K,Z)):(Ee(We,4+(et?1:0),3),function(vt,kt,St,Yt){var es;for(Ee(vt,kt-257,5),Ee(vt,St-1,5),Ee(vt,Yt-4,4),es=0;es>>8&255,We.pending_buf[We.d_buf+2*We.last_lit+1]=255&Ce,We.pending_buf[We.l_buf+We.last_lit]=255&qe,We.last_lit++,Ce===0?We.dyn_ltree[2*qe]++:(We.matches++,Ce--,We.dyn_ltree[2*(W[qe]+m+1)]++,We.dyn_dtree[2*je(Ce)]++),We.last_lit===We.lit_bufsize-1},a._tr_align=function(We){Ee(We,2,3),Me(We,C,K),function(Ce){Ce.bi_valid===16?(xe(Ce,Ce.bi_buf),Ce.bi_buf=0,Ce.bi_valid=0):8<=Ce.bi_valid&&(Ce.pending_buf[Ce.pending++]=255&Ce.bi_buf,Ce.bi_buf>>=8,Ce.bi_valid-=8)}(We)}},{"../utils/common":41}],53:[function(r,n,a){n.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(r,n,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,m,f=1,x={},y=!1,_=l.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(l);b=b&&b.setTimeout?b:l,c={}.toString.call(l.process)==="[object process]"?function(A){process.nextTick(function(){N(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}}()?(m="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",C,!1):l.attachEvent("onmessage",C),function(A){l.postMessage(m+A,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(A){N(A.data)},function(A){u.port2.postMessage(A)}):_&&"onreadystatechange"in _.createElement("script")?(d=_.documentElement,function(A){var E=_.createElement("script");E.onreadystatechange=function(){N(A),E.onreadystatechange=null,d.removeChild(E),E=null},d.appendChild(E)}):function(A){setTimeout(N,0,A)},b.setImmediate=function(A){typeof A!="function"&&(A=new Function(""+A));for(var E=new Array(arguments.length-1),D=0;D"u"?i===void 0?this:i:self)}).call(this,typeof lh<"u"?lh:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Ght);var ids=Ght.exports;const Wht=gl(ids);function rwe(s,t=400,r=75){return s&&`${s.replace("/storage/v1/object/public/","/storage/v1/render/image/public/")}?width=${t}&quality=${r}&resize=contain`}const ods=()=>{Cs();const[s,t]=k.useState(null),[r,n]=k.useState(null),[a,i]=k.useState("all"),[l,o]=k.useState(new Set),[c,d]=k.useState(!1),[u,m]=k.useState(!1),[f,x]=k.useState("images"),[y,_]=k.useState(null),{data:b=[],isLoading:j}=pt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:ue,error:me}=await U.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(me)throw me;return ue}}),{data:N=[]}=pt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:ue,error:me}=await U.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(me)throw me;return ue}}),{data:C=[]}=pt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:ue,error:me}=await U.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(me)throw me;return ue}}),{data:A=[]}=pt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:ue,error:me}=await U.from("social_accounts").select("id, platform").eq("is_active",!0);if(me)throw me;return ue||[]}}),E=A.length>0,D=k.useMemo(()=>a==="all"?null:C.find(ue=>ue.month===a)||null,[a,C]),R=k.useMemo(()=>[...new Set(b.map(me=>me.month))].sort((me,de)=>de.localeCompare(me)),[b]);k.useEffect(()=>{R.length>0&&a==="all"&&i(R[0])},[R,a]);const F=ue=>{try{const me=hTe(ue,"yyyy-MM",new Date);return As(me,"MMMM yyyy")}catch{return ue}},O=k.useMemo(()=>a==="all"?b:b.filter(ue=>ue.month===a),[a,b]),B=k.useMemo(()=>{var ue;return a==="all"?null:((ue=N.find(me=>me.month===a))==null?void 0:ue.canva_link)||null},[a,N]),K=async ue=>{try{await navigator.clipboard.writeText(ue),he.success("Caption copied to clipboard!")}catch{he.error("Failed to copy caption")}},Z=async(ue,me)=>{try{const fe=await(await fetch(ue)).blob(),je=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),xe=navigator.canShare&&navigator.canShare({files:[new File([fe],"test.jpg",{type:"image/jpeg"})]});if(je&&xe){const Ee=new File([fe],`social-swag-${me}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Ee],title:"Social Swag Image"}),he.success("Image ready to save!")}else{const Ee=window.URL.createObjectURL(fe),Me=document.createElement("a");Me.href=Ee,Me.download=`social-swag-${me}.jpg`,document.body.appendChild(Me),Me.click(),document.body.removeChild(Me),window.URL.revokeObjectURL(Ee),he.success("Image downloaded!")}}catch(de){de.name!=="AbortError"&&he.error("Failed to download image")}},Q=ue=>{o(me=>{const de=new Set(me);return de.has(ue)?de.delete(ue):de.add(ue),de})},W=()=>{o(new Set(O.map(ue=>ue.id)))},te=()=>{o(new Set),d(!1)},ne=async()=>{const ue=O.filter(me=>l.has(me.id));if(ue.length===0){he.error("No images selected");return}m(!0),he.info(`Preparing ${ue.length} images for download...`);try{const me=new Wht,de=[...ue].sort((Me,Oe)=>Me.sort_order-Oe.sort_order);for(let Me=0;Me{c?Q(ue.id):t(ue)};return e.jsx(ws,{title:"Social Swag 2.0",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary via-primary/80 to-info p-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[e.jsxs(Xe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(Xe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(zo,{className:"h-3 w-3 mr-1"}),b.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(ta,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(ea,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(rs,{value:"gallery",className:"gap-2",children:[e.jsx(zo,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(rs,{value:"scheduled",className:"gap-2",children:[e.jsx(xu,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(fs,{value:"gallery",className:"space-y-6",children:[E?e.jsx(ke,{className:"border rounded-xl",children:e.jsx(Pe,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-muted text-2xl",children:"📸"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Ready to post!"}),e.jsx("p",{className:"text-muted-foreground",children:'Click any image and use "Create Post" to share directly to your connected accounts.'})]}),e.jsx(q,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(Vn,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(ke,{className:"border-2 border-dashed border-primary/30 bg-gradient-to-r from-pink-500/5 via-purple-500/5 to-blue-500/5 rounded-xl",children:e.jsx(Pe,{className:"p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 rounded-full bg-blue-500/10",children:e.jsx(mh,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(gu,{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(q,{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(Vn,{to:"/social-connections",children:[e.jsx(Ul,{className:"h-4 w-4"}),"Connect Accounts"]})})]})})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:R.map(ue=>e.jsx("button",{onClick:()=>i(ue),className:zt("px-4 py-2 rounded-full text-sm font-medium transition-all",a===ue?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:F(ue)},ue))}),a!=="all"&&(B?e.jsxs("a",{href:B,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 ",F(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 ",F(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:()=>{x("images"),te()},className:zt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",f==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(zo,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{x("reels"),te()},className:zt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",f==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(rf,{className:"h-4 w-4"}),"Reels"]})]}),f==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:c?e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:W,className:"gap-2",children:["Select All (",O.length,")"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:te,className:"gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),"Cancel"]}),l.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(q,{size:"sm",onClick:ne,disabled:u,className:"gap-2",children:[e.jsx(li,{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(q,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"gap-2",children:[e.jsx(la,{className:"h-4 w-4"}),"Select Images"]})})]}),j&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!j&&f==="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:O.map(ue=>{const me=l.has(ue.id);return e.jsx(ke,{className:zt("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",c&&me&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ae(ue),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:rwe(ue.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"}),ue.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:As(new Date(ue.post_date+"T00:00:00"),"MMM d")})}),c&&e.jsx("div",{className:zt("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",me?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:me&&e.jsx(la,{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"})})]})},ue.id)})}),O.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(zo,{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&&f==="reels"&&e.jsx(e.Fragment,{children:D?e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4",children:e.jsx(ke,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>n(D),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:rwe(D.image_url,400,75),alt:"Reel preview",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105",loading:"lazy",decoding:"async"}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsxs(Xe,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(rf,{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(rf,{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(vs,{open:!!s,onOpenChange:()=>t(null),children:e.jsx(ys,{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:rwe(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(vn,{className:"h-4 w-4"}),As(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(vn,{className:"h-3.5 w-3.5"}),"Post on ",As(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(q,{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(hn,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(q,{variant:"outline",onClick:()=>K(s.caption),className:"flex-1 gap-2",children:[e.jsx(si,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(q,{variant:"outline",onClick:()=>Z(s.image_url,s.id),className:"flex-1 gap-2",children:[e.jsx(li,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(vs,{open:!!r,onOpenChange:()=>n(null),children:e.jsx(ys,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:r&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-black flex items-center justify-center",children:e.jsx("div",{className:"aspect-[9/16] max-h-[70vh]",children:e.jsx("img",{src:r.image_url,alt:"Reel preview",className:"w-full h-full object-contain"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-4",children:[e.jsx(rf,{className:"h-4 w-4"}),"Monthly Reel"]}),r.caption&&e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:r.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[r.caption&&e.jsxs(q,{onClick:()=>K(r.caption||""),className:"flex-1 gap-2",children:[e.jsx(si,{className:"h-4 w-4"}),"Copy Caption"]}),r.canva_link&&e.jsxs(q,{variant:"outline",onClick:()=>window.open(r.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(nds,{open:!!y,onOpenChange:ue=>!ue&&_(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(fs,{value:"scheduled",children:e.jsx(ads,{})})]})]})})},lds=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:zo,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:Pn,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:qi,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:Mo,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:_m,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:_1,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:sP,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function cds(){return e.jsx(ws,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(Yo,{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(Xe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(Ir,{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(q,{variant:"outline",asChild:!0,children:e.jsxs(Vn,{to:"/marketing-studio/brand-kit",children:[e.jsx(dl,{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:lds.map(s=>{const t=s.icon,r=e.jsxs(ke,{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(Pe,{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(Xe,{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(Vn,{to:s.to,className:"block",children:r},s.id):e.jsx("div",{children:r},s.id)})})]})})}function OB(){const s=xa();return pt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s})}function dds(){const{data:s,...t}=OB();return{data:(s==null?void 0:s.find(r=>r.is_default))??(s==null?void 0:s[0])??null,...t}}function uds(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not signed in");if(r.is_default&&await U.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),r.id){const{id:n,...a}=r,{data:i,error:l}=await U.from("marketing_brand_presets").update(a).eq("id",n).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:n,error:a}=await U.from("marketing_brand_presets").insert({...r,user_id:s}).select().single();if(a)throw a;return n}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function hds(){const s=xa(),t=is();return Mt({mutationFn:async r=>{const{error:n}=await U.from("marketing_brand_presets").delete().eq("id",r);if(n)throw n},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function mds(s,t,r){var o;const n=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${r}-${Date.now()}.${n}`,{error:i}=await U.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await U.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function fds({preset:s,onSaved:t,onCancel:r}){var _;const n=xa(),a=uds(),i=hds(),l=k.useRef(null),o=k.useRef(null),[c,d]=k.useState(null),[u,m]=k.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"});k.useEffect(()=>{s||(async()=>{if(!n)return;const{supabase:b}=await vi(async()=>{const{supabase:N}=await Promise.resolve().then(()=>xIt);return{supabase:N}},void 0),{data:j}=await b.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",n).maybeSingle();j&&m(N=>({...N,display_name:N.display_name||(j.name??""),email:N.email||(j.email??""),phone:N.phone||(j.phone??""),headshot_url:N.headshot_url||(j.avatar_url??""),website_url:N.website_url||(j.website_url??""),tagline:N.tagline||(j.title??"")}))})()},[n]);const f=async(b,j)=>{if(n){d(b);try{const N=await mds(n,j,b);m(C=>({...C,[b==="headshot"?"headshot_url":"brokerage_logo_url"]:N}))}catch(N){he.error(N.message||"Upload failed")}finally{d(null)}}},x=async()=>{try{const b=await a.mutateAsync({id:s==null?void 0:s.id,...u});he.success("Brand preset saved"),t==null||t(b)}catch(b){he.error(b.message||"Save failed")}},y=async()=>{s!=null&&s.id&&confirm("Delete this brand preset?")&&(await i.mutateAsync(s.id),he.success("Preset deleted"),r==null||r())};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(ce,{children:"Preset name"}),e.jsx(Ne,{value:u.name,onChange:b=>m({...u,name:b.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(Rr,{checked:u.is_default,onCheckedChange:b=>m({...u,is_default:b})}),e.jsx(ce,{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(ce,{children:"Display name"}),e.jsx(Ne,{value:u.display_name,onChange:b=>m({...u,display_name:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Phone"}),e.jsx(Ne,{value:u.phone,onChange:b=>m({...u,phone:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Email"}),e.jsx(Ne,{value:u.email,onChange:b=>m({...u,email:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"License #"}),e.jsx(Ne,{value:u.license_number,onChange:b=>m({...u,license_number:b.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ce,{children:"Tagline"}),e.jsx(Ne,{value:u.tagline,onChange:b=>m({...u,tagline:b.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ce,{children:"Website"}),e.jsx(Ne,{value:u.website_url,onChange:b=>m({...u,website_url:b.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(ce,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Wn,{className:"h-16 w-16",children:[e.jsx(Xa,{src:u.headshot_url||void 0}),e.jsx(Kn,{children:((_=u.display_name)==null?void 0:_[0])??"A"})]}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:()=>{var b;return(b=l.current)==null?void 0:b.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:b=>{var j;return((j=b.target.files)==null?void 0:j[0])&&f("headshot",b.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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(q,{type:"button",variant:"outline",size:"sm",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:b=>{var j;return((j=b.target.files)==null?void 0:j[0])&&f("logo",b.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:b=>m({...u,brand_color:b.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(Ne,{value:u.brand_color,onChange:b=>m({...u,brand_color:b.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:b=>m({...u,accent_color:b.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(Ne,{value:u.accent_color,onChange:b=>m({...u,accent_color:b.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs(q,{variant:"ghost",size:"sm",onClick:y,className:"text-destructive",children:[e.jsx(zr,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(q,{variant:"outline",onClick:r,children:"Cancel"}),e.jsxs(q,{onClick:x,disabled:a.isPending,children:[a.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function pds(){const{data:s,isLoading:t}=OB(),[r,n]=k.useState(null);return e.jsx(ws,{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(Yo,{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(Vn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Aa,{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(q,{onClick:()=>n("new"),className:"w-full sm:w-auto",children:[e.jsx(Ys,{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(ke,{className:"border-dashed",children:e.jsxs(Pe,{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(q,{onClick:()=>n("new"),children:[e.jsx(Ys,{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(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Pt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(fa,{className:"h-3 w-3"})," Default"]})]}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>n(a),children:e.jsx(Ua,{className:"h-4 w-4"})})]}),e.jsx(Ur,{children:a.display_name})]}),e.jsxs(Pe,{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(vs,{open:r!==null,onOpenChange:a=>!a&&n(null),children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(_s,{children:e.jsx(bs,{children:r==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(fds,{preset:r==="new"?null:r,onSaved:()=>n(null),onCancel:()=>n(null)})]})})]})})}const ySe=[{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"}],xds=s=>ySe.find(t=>t.id===s)??ySe[0];function gds(s){if(!s)return"#ffffff";const t=s.replace("#","");if(t.length!==6)return"#ffffff";const r=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),a=parseInt(t.slice(4,6),16);return(r*299+n*587+a*114)/1e3>=150?"#0f172a":"#ffffff"}function yds({value:s,onChange:t,mediaType:r}){const n=ySe.filter(a=>a.appliesTo.includes(r));return e.jsx("div",{className:"grid grid-cols-2 gap-2",children:n.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.id),className:zt("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(vds,{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 vds({style:s}){const t="#cbd5e1",r="#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:r}}),s.position==="top"&&e.jsx("div",{className:"absolute left-0 right-0 top-0",style:{height:`${s.heightRatio*100}%`,background:r}}),s.position==="corner-br"&&e.jsx("div",{className:"absolute bottom-2 right-2 w-1/3 h-1/3 rounded",style:{background:r,opacity:.85}}),s.position==="side-right"&&e.jsx("div",{className:"absolute top-0 bottom-0 right-0",style:{width:`${s.heightRatio*100}%`,background:r}}),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:r}}),e.jsx("div",{className:"absolute left-0 right-0 bottom-0",style:{height:`${s.heightRatio*100}%`,background:r}})]})]})}const bds=Math.PI/180;function _ds(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const rE=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},ra={_global:rE,version:"10.2.5",isBrowser:_ds(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return ra.angleDeg?s*bds: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 ra.DD.isDragging},isTransforming(){var s,t;return(t=(s=ra.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!ra.DD.node},releaseCanvasOnDestroy:!0,document:rE.document,_injectGlobal(s){typeof rE.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),rE.Konva=s}},wu=s=>{ra[s.prototype.getClassName()]=s};ra._injectGlobal(ra);const wds=`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"; `,y$e=()=>{if(typeof document>"u")throw new Error(wds)};class _0{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 _0(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 r=this.m;return{x:r[0]*t.x+r[2]*t.y+r[4],y:r[1]*t.x+r[3]*t.y+r[5]}}translate(t,r){return this.m[4]+=this.m[0]*t+this.m[2]*r,this.m[5]+=this.m[1]*t+this.m[3]*r,this}scale(t,r){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=r,this.m[3]*=r,this}rotate(t){const r=Math.cos(t),n=Math.sin(t),a=this.m[0]*r+this.m[2]*n,i=this.m[1]*r+this.m[3]*n,l=this.m[0]*-n+this.m[2]*r,o=this.m[1]*-n+this.m[3]*r;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,r){const n=this.m[0]+this.m[2]*r,a=this.m[1]+this.m[3]*r,i=this.m[2]+this.m[0]*t,l=this.m[3]+this.m[1]*t;return this.m[0]=n,this.m[1]=a,this.m[2]=i,this.m[3]=l,this}multiply(t){const r=this.m[0]*t.m[0]+this.m[2]*t.m[1],n=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]=r,this.m[1]=n,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]),r=this.m[3]*t,n=-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]=r,this.m[1]=n,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],r=this.m[1],n=this.m[2],a=this.m[3],i=this.m[4],l=this.m[5],o=t*a-r*n,c={x:i,y:l,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||r!=0){const d=Math.sqrt(t*t+r*r);c.rotation=r>0?Math.acos(t/d):-Math.acos(t/d),c.scaleX=d,c.scaleY=o/d,c.skewX=(t*n+r*a)/o,c.skewY=0}else if(n!=0||a!=0){const d=Math.sqrt(n*n+a*a);c.rotation=Math.PI/2-(a>0?Math.acos(-n/d):-Math.acos(n/d)),c.scaleX=o/d,c.scaleY=d,c.skewX=0,c.skewY=(t*n+r*a)/o}return c.rotation=fr._getRotation(c.rotation),c}}const jds="[object Array]",Nds="[object Number]",kds="[object String]",Sds="[object Boolean]",Cds=Math.PI/180,Tds=180/Math.PI,YR="#",Eds="",Ads="0",Mds="Konva warning: ",v$e="Konva error: ",Ids="rgb(",nwe={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]},Pds=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let zq=[],ZR=null;const Lds=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},fr={_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)===jds},_isNumber(s){return Object.prototype.toString.call(s)===Nds&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===kds},_isBoolean(s){return Object.prototype.toString.call(s)===Sds},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){zq.push(s),zq.length===1&&Lds(function(){const t=zq;zq=[],t.forEach(function(r){r()})})},createCanvasElement(){y$e();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return y$e(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const r=fr.createImageElement();r.onload=function(){t(r)},r.src=s},_rgbToHex(s,t,r){return((1<<24)+(s<<16)+(t<<8)+r).toString(16).slice(1)},_hexToRgb(s){s=s.replace(YR,Eds);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=Ads+s;return YR+s},isCanvasFarblingActive(){if(ZR!==null)return ZR;if(typeof document>"u")return ZR=!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 r=t.getImageData(0,0,10,10).data;let n=!1;for(let a=0;a<100;a++)if(r[a*4]!==40||r[a*4+1]!==40||r[a*4+2]!==40||r[a*4+3]!==255){n=!0;break}return ZR=n,this.releaseCanvas(s),ZR},getHitColor(){const s=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(s):s},getHitColorKey(s,t,r){return this.isCanvasFarblingActive()&&(s=Math.round(s/5)*5,t=Math.round(t/5)*5,r=Math.round(r/5)*5),YR+this._rgbToHex(s,t,r)},getSnappedHexColor(s){const t=this._hexToRgb(s);return YR+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 nwe?(t=nwe[s],{r:t[0],g:t[1],b:t[2]}):s[0]===YR?this._hexToRgb(s.substring(1)):s.substr(0,4)===Ids?(t=Pds.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",fr._namedColorToRBA(s)||fr._hex3ColorToRGBA(s)||fr._hex4ColorToRGBA(s)||fr._hex6ColorToRGBA(s)||fr._hex8ColorToRGBA(s)||fr._rgbColorToRGBA(s)||fr._rgbaColorToRGBA(s)||fr._hslColorToRGBA(s)},_namedColorToRBA(s){const t=nwe[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((r,n)=>r.slice(-1)==="%"?n===3?parseInt(r)/100:parseInt(r)/100*255:Number(r));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,...r]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(s),n=Number(r[0])/360,a=Number(r[1])/100,i=Number(r[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 m=0;m<3;m++)o=n+1/3*-(m-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[m]=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=r,o=n,c=(r-a)*(r-a)+(n-i)*(n-i)):(l=s+u*(r-s),o=t+u*(n-t),c=(l-a)*(l-a)+(o-i)*(o-i))}return[l,o,c]},_getProjectionToLine(s,t,r){const n=fr.cloneObject(s);let a=Number.MAX_VALUE;return t.forEach(function(i,l){if(!r&&l===t.length-1)return;const o=t[(l+1)%t.length],c=fr._getProjectionToSegment(i.x,i.y,o.x,o.y,s.x,s.y),d=c[0],u=c[1],m=c[2];mt.length){const l=t;t=s,s=l}for(let l=0;l{t.width=0,t.height=0})},drawRoundedRectPath(s,t,r,n){let a=t<0?t:0,i=r<0?r:0;t=Math.abs(t),r=Math.abs(r);let l=0,o=0,c=0,d=0;typeof n=="number"?l=o=c=d=Math.min(n,t/2,r/2):(l=Math.min(n[0]||0,t/2,r/2),o=Math.min(n[1]||0,t/2,r/2),d=Math.min(n[2]||0,t/2,r/2),c=Math.min(n[3]||0,t/2,r/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+r-d),s.arc(a+t-d,i+r-d,d,0,Math.PI/2,!1),s.lineTo(a+c,i+r),s.arc(a+c,i+r-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,r,n,a){n=Math.abs(n);for(let i=0;itypeof u=="number"?Math.floor(u):u)),i+=Rds+d.join(b$e)+Ods)):(i+=o.property,t||(i+=Uds+o.val)),i+=Bds;return i}clearTrace(){this.traceArr=[]}_trace(t){let r=this.traceArr,n;r.push(t),n=r.length,n>=Vds&&r.shift()}reset(){const t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){const r=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,r.getWidth()/r.pixelRatio,r.getHeight()/r.pixelRatio)}_applyLineCap(t){const r=t.attrs.lineCap;r&&this.setAttr("lineCap",r)}_applyOpacity(t){const r=t.getAbsoluteOpacity();r!==1&&this.setAttr("globalAlpha",r)}_applyLineJoin(t){const r=t.attrs.lineJoin;r&&this.setAttr("lineJoin",r)}_applyMiterLimit(t){const r=t.attrs.miterLimit;r!=null&&this.setAttr("miterLimit",r)}setAttr(t,r){this._context[t]=r}arc(t,r,n,a,i,l){this._context.arc(t,r,n,a,i,l)}arcTo(t,r,n,a,i){this._context.arcTo(t,r,n,a,i)}beginPath(){this._context.beginPath()}bezierCurveTo(t,r,n,a,i,l){this._context.bezierCurveTo(t,r,n,a,i,l)}clearRect(t,r,n,a){this._context.clearRect(t,r,n,a)}clip(...t){this._context.clip.apply(this._context,t)}closePath(){this._context.closePath()}createImageData(t,r){const n=arguments;if(n.length===2)return this._context.createImageData(t,r);if(n.length===1)return this._context.createImageData(t)}createLinearGradient(t,r,n,a){return this._context.createLinearGradient(t,r,n,a)}createPattern(t,r){return this._context.createPattern(t,r)}createRadialGradient(t,r,n,a,i,l){return this._context.createRadialGradient(t,r,n,a,i,l)}drawImage(t,r,n,a,i,l,o,c,d){const u=arguments,m=this._context;u.length===3?m.drawImage(t,r,n):u.length===5?m.drawImage(t,r,n,a,i):u.length===9&&m.drawImage(t,r,n,a,i,l,o,c,d)}ellipse(t,r,n,a,i,l,o,c){this._context.ellipse(t,r,n,a,i,l,o,c)}isPointInPath(t,r,n,a){return n?this._context.isPointInPath(n,t,r,a):this._context.isPointInPath(t,r,a)}fill(...t){this._context.fill.apply(this._context,t)}fillRect(t,r,n,a){this._context.fillRect(t,r,n,a)}strokeRect(t,r,n,a){this._context.strokeRect(t,r,n,a)}fillText(t,r,n,a){a?this._context.fillText(t,r,n,a):this._context.fillText(t,r,n)}measureText(t){return this._context.measureText(t)}getImageData(t,r,n,a){return this._context.getImageData(t,r,n,a)}lineTo(t,r){this._context.lineTo(t,r)}moveTo(t,r){this._context.moveTo(t,r)}rect(t,r,n,a){this._context.rect(t,r,n,a)}roundRect(t,r,n,a,i){this._context.roundRect(t,r,n,a,i)}putImageData(t,r,n){this._context.putImageData(t,r,n)}quadraticCurveTo(t,r,n,a){this._context.quadraticCurveTo(t,r,n,a)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,r){this._context.scale(t,r)}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,r,n,a,i,l){this._context.setTransform(t,r,n,a,i,l)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,r,n,a){this._context.strokeText(t,r,n,a)}transform(t,r,n,a,i,l){this._context.transform(t,r,n,a,i,l)}translate(t,r){this._context.translate(t,r)}_enableTrace(){let t=this,r=_$e.length,n=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=Dds(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 Rl._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];Rl._dragElements.forEach((r,n)=>{const{node:a}=r,i=a.getStage();i.setPointersPositions(s),r.pointerId===void 0&&(r.pointerId=fr._getFirstPointerId(s));const l=i._changedPointerPositions.find(o=>o.id===r.pointerId);if(l){if(r.dragStatus!=="dragging"){const o=a.dragDistance();if(Math.max(Math.abs(l.x-r.startPointerPos.x),Math.abs(l.y-r.startPointerPos.y)){r.getStage()&&r.fire("dragmove",{type:"dragmove",target:r,evt:s},!0)})},_endDragBefore(s){const t=[];Rl._dragElements.forEach(r=>{const{node:n}=r,a=n.getStage();if(s&&a.setPointersPositions(s),!a._changedPointerPositions.find(o=>o.id===r.pointerId))return;(r.dragStatus==="dragging"||r.dragStatus==="stopped")&&(Rl.justDragged=!0,ra._mouseListenClick=!1,ra._touchListenClick=!1,ra._pointerListenClick=!1,r.dragStatus="stopped");const l=r.node.getLayer()||r.node instanceof ra.Stage&&r.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(r=>{r.draw()})},_endDragAfter(s){Rl._dragElements.forEach((t,r)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&Rl._dragElements.delete(r)})}};ra.isBrowser&&(window.addEventListener("mouseup",Rl._endDragBefore,!0),window.addEventListener("touchend",Rl._endDragBefore,!0),window.addEventListener("touchcancel",Rl._endDragBefore,!0),window.addEventListener("mousemove",Rl._drag),window.addEventListener("touchmove",Rl._drag),window.addEventListener("mouseup",Rl._endDragAfter,!1),window.addEventListener("touchend",Rl._endDragAfter,!1),window.addEventListener("touchcancel",Rl._endDragAfter,!1));function l4(s){return fr._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||fr._isBoolean(s)?s:Object.prototype.toString.call(s)}function Kht(s){return s>255?255:s<0?0:Math.round(s)}function Zn(){if(ra.isUnminified)return function(s,t){return fr._isNumber(s)||fr.warn(l4(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function n0e(s){if(ra.isUnminified)return function(t,r){let n=fr._isNumber(t),a=fr._isArray(t)&&t.length==s;return!n&&!a&&fr.warn(l4(t)+' is a not valid value for "'+r+'" attribute. The value should be a number or Array('+s+")"),t}}function CAe(){if(ra.isUnminified)return function(s,t){return fr._isNumber(s)||s==="auto"||fr.warn(l4(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function JA(){if(ra.isUnminified)return function(s,t){return fr._isString(s)||fr.warn(l4(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function Yht(){if(ra.isUnminified)return function(s,t){const r=fr._isString(s),n=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return r||n||fr.warn(l4(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function Kds(){if(ra.isUnminified)return function(s,t){const r=Int8Array?Object.getPrototypeOf(Int8Array):null;return r&&s instanceof r||(fr._isArray(s)?s.forEach(function(n){fr._isNumber(n)||fr.warn('"'+t+'" attribute has non numeric element '+n+". Make sure that all elements are numbers.")}):fr.warn(l4(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function H1(){if(ra.isUnminified)return function(s,t){return s===!0||s===!1||fr.warn(l4(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function Yds(s){if(ra.isUnminified)return function(t,r){return t==null||fr.isObject(t)||fr.warn(l4(t)+' is a not valid value for "'+r+'" attribute. The value should be an object with properties '+s),t}}const XR="get",QR="set",ks={addGetterSetter(s,t,r,n,a){ks.addGetter(s,t,r),ks.addSetter(s,t,n,a),ks.addOverloadedGetterSetter(s,t)},addGetter(s,t,r){const n=XR+fr._capitalize(t);s.prototype[n]=s.prototype[n]||function(){const a=this.attrs[t];return a===void 0?r:a}},addSetter(s,t,r,n){const a=QR+fr._capitalize(t);s.prototype[a]||ks.overWriteSetter(s,t,r,n)},overWriteSetter(s,t,r,n){const a=QR+fr._capitalize(t);s.prototype[a]=function(i){return r&&i!==void 0&&i!==null&&(i=r.call(this,i,t)),this._setAttr(t,i),n&&n.call(this),this}},addComponentsGetterSetter(s,t,r,n,a){const i=r.length,l=fr._capitalize,o=XR+l(t),c=QR+l(t);s.prototype[o]=function(){const u={};for(let m=0;m{this._setAttr(t+l(f),void 0)}),this._fireChangeEvent(t,m,u),a&&a.call(this),this},ks.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const r=fr._capitalize(t),n=QR+r,a=XR+r;s.prototype[t]=function(){return arguments.length?(this[n](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,r,n){fr.error("Adding deprecated "+t);const a=XR+fr._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){fr.error(i);const l=this.attrs[t];return l===void 0?r:l},ks.addSetter(s,t,n,function(){fr.error(i)}),ks.addOverloadedGetterSetter(s,t)},backCompat(s,t){fr.each(t,function(r,n){const a=s.prototype[n],i=XR+fr._capitalize(r),l=QR+fr._capitalize(r);function o(){a.apply(this,arguments),fr.error('"'+r+'" method is deprecated and will be removed soon. Use ""'+n+'" instead.')}s.prototype[r]=o,s.prototype[i]=o,s.prototype[l]=o})},afterSetFilter(){this._filterUpToDate=!1}};function Zds(s){const t=/(\w+)\(([^)]+)\)/g;let r;for(;(r=t.exec(s))!==null;){const[,n,a]=r;switch(n){case"blur":{const i=parseFloat(a.replace("px",""));return function(l){this.blurRadius(i*.5);const o=ra.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=ra.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=ra.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=ra.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=ra.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=ra.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:fr.warn(`CSS filter "${n}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const ahe="absoluteOpacity",j$e="allEventListeners",Cj="absoluteTransform",N$e="absoluteScale",pC="canvas",Xds="Change",Qds="children",Jds="konva",vSe="listening",eus="mouseenter",tus="mouseleave",sus="pointerenter",rus="pointerleave",nus="touchenter",aus="touchleave",k$e="set",S$e="Shape",ihe=" ",C$e="stage",JN="transform",ius="Stage",bSe="visible",ous=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(ihe);let lus=1,oa=class OO{constructor(t){this._id=lus++,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===JN||t===Cj)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,r){let n=this._cache.get(t);return(n===void 0||(t===JN||t===Cj)&&n.dirty===!0)&&(n=r.call(this),this._cache.set(t,n)),n}_calculate(t,r,n){if(!this._attachedDepsListeners.get(t)){const a=r.map(i=>i+"Change.konva").join(ihe);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,n)}_getCanvasCache(){return this._cache.get(pC)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===Cj&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(pC)){const{scene:t,filter:r,hit:n}=this._cache.get(pC);fr.releaseCanvas(t._canvas,r._canvas,n._canvas),this._cache.delete(pC)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const r=t||{};let n={};(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)&&(n=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let a=Math.ceil(r.width||n.width),i=Math.ceil(r.height||n.height),l=r.pixelRatio,o=r.x===void 0?Math.floor(n.x):r.x,c=r.y===void 0?Math.floor(n.y):r.y,d=r.offset||0,u=r.drawBorder||!1,m=r.hitCanvasPixelRatio||1;if(!a||!i){fr.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const f=Math.abs(Math.round(n.x)-o)>.5?1:0,x=Math.abs(Math.round(n.y)-c)>.5?1:0;a+=d*2+f,i+=d*2+x,o-=d,c-=d;const y=new _k({pixelRatio:l,width:a,height:i}),_=new _k({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),b=new SAe({pixelRatio:m,width:a,height:i}),j=y.getContext(),N=b.getContext(),C=new _k({width:y.width/y.pixelRatio+Math.abs(o),height:y.height/y.pixelRatio+Math.abs(c),pixelRatio:y.pixelRatio}),A=C.getContext();return b.isCache=!0,y.isCache=!0,this._cache.delete(pC),this._filterUpToDate=!1,r.imageSmoothingEnabled===!1&&(y.getContext()._context.imageSmoothingEnabled=!1,_.getContext()._context.imageSmoothingEnabled=!1),j.save(),N.save(),A.save(),j.translate(-o,-c),N.translate(-o,-c),A.translate(-o,-c),C.x=o,C.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(ahe),this._clearSelfAndDescendantCache(N$e),this.drawScene(y,this,C),this.drawHit(b,this),this._isUnderCache=!1,j.restore(),N.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()),fr.releaseCanvas(C._canvas),this._cache.set(pC,{scene:y,filter:_,hit:b,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(pC)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,r){const n=[{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(r);return n.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 r=this._getCanvasCache();t.translate(r.x,r.y);const n=this._getCachedSceneCanvas(),a=n.pixelRatio;t.drawImage(n._canvas,0,0,n.width/a,n.height/a),t.restore()}_drawCachedHitCanvas(t){const r=this._getCanvasCache(),n=r.hit;t.save(),t.translate(r.x,r.y),t.drawImage(n._canvas,0,0,n.width/n.pixelRatio,n.height/n.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),r=this._getCanvasCache(),n=r.scene,a=r.filter,i=a.getContext(),l,o,c,d;if(!t||t.length===0)return n;if(this._filterUpToDate)return a;let u=!0;for(let f=0;f{this.isAncestorOf(t.node)&&Rl._dragElements.delete(r)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(Cj),this._clearSelfAndDescendantCache(ahe),this._clearSelfAndDescendantCache(N$e),this._clearSelfAndDescendantCache(C$e),this._clearSelfAndDescendantCache(bSe),this._clearSelfAndDescendantCache(vSe)}_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 r="get"+fr._capitalize(t);return fr._isFunction(this[r])?this[r]():this.attrs[t]}getAncestors(){let t=this.getParent(),r=[];for(;t;)r.push(t),t=t.getParent();return r}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let r,n;if(!t)return this;for(r in t)r!==Qds&&(n=k$e+fr._capitalize(r),fr._isFunction(this[n])?this[n](t[r]):this._setAttr(r,t[r]))}),this}isListening(){return this._getCache(vSe,this._isListening)}_isListening(t){if(!this.listening())return!1;const n=this.getParent();return n&&n!==t&&this!==t?n._isListening(t):!0}isVisible(){return this._getCache(bSe,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const n=this.getParent();return n&&n!==t&&this!==t?n._isVisible(t):!0}shouldDrawHit(t,r=!1){if(t)return this._isVisible(t)&&this._isListening(t);const n=this.getLayer();let a=!1;Rl._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===n)&&(a=!0)});const i=!r&&!ra.hitOnDragEnabled&&(a||ra.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(),r=this,n=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 r.nodeType!==ius&&d&&c(d.getChildren()),n}getDepth(){let t=0,r=this.parent;for(;r;)t++,r=r.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(JN),this._clearSelfAndDescendantCache(Cj)),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 r=t.getPointerPosition();if(!r)return null;const n=this.getAbsoluteTransform().copy();return n.invert(),n.point(r)}getAbsolutePosition(t){let r=!1,n=this.parent;for(;n;){if(n.isCached()){r=!0;break}n=n.parent}r&&!t&&(t=!0);const a=this.getAbsoluteTransform(t).getMatrix(),i=new _0,l=this.offset();return i.m=a.slice(),i.translate(l.x,l.y),i.getTranslation()}setAbsolutePosition(t){const{x:r,y:n,...a}=this._clearTransform();this.attrs.x=r,this.attrs.y=n,this._clearCache(JN);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(JN),this._clearSelfAndDescendantCache(Cj),this}_setTransform(t){let r;for(r in t)this.attrs[r]=t[r]}_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 r=t.x,n=t.y,a=this.x(),i=this.y();return r!==void 0&&(a+=r),n!==void 0&&(i+=n),this.setPosition({x:a,y:i}),this}_eachAncestorReverse(t,r){let n=[],a=this.getParent(),i,l;if(!(r&&r._id===this._id)){for(n.unshift(this);a&&(!r||a._id!==r._id);)n.unshift(a),a=a.parent;for(i=n.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 fr.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 fr.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&fr.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 r=this.index;return this.parent.children.splice(r,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(ahe,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const r=this.getParent();return r&&!r._isUnderCache&&(t*=r.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),r,n,a,i,l;const o={attrs:{},className:this.getClassName()};for(r in t)n=t[r],l=fr.isObject(n)&&!fr._isPlainObject(n)&&!fr._isArray(n),!l&&(a=typeof this[r]=="function"&&this[r],delete t[r],i=a?a.call(this):null,t[r]=n,i!==n&&(o.attrs[r]=n));return fr._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,r,n){const a=[];r&&this._isMatch(t)&&a.push(this);let i=this.parent;for(;i;){if(i===n)return a;i._isMatch(t)&&a.push(i),i=i.parent}return a}isAncestorOf(t){return!1}findAncestor(t,r,n){return this.findAncestors(t,r,n)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let r=t.replace(/ /g,"").split(","),n=r.length,a,i;for(a=0;a{try{const a=t==null?void 0:t.callback;a&&delete t.callback,fr._urlToImage(this.toDataURL(t),function(i){r(i),a==null||a(i)})}catch(a){n(a)}})}toBlob(t){return new Promise((r,n)=>{try{const a=t==null?void 0:t.callback;a&&delete t.callback,this.toCanvas(t).toBlob(i=>{r(i),a==null||a(i)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(a){n(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():ra.dragDistance}_off(t,r,n){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;Rl._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 r=Rl._dragElements.get(this._id),n=r&&r.dragStatus==="dragging",a=r&&r.dragStatus==="ready";n?this.stopDrag():a&&Rl._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const r=this.getStage();if(!r)return!1;const n={x:-t.x,y:-t.y,width:r.width()+2*t.x,height:r.height()+2*t.y};return fr.haveIntersection(n,this.getClientRect())}static create(t,r){return fr._isString(t)&&(t=JSON.parse(t)),this._createNode(t,r)}static _createNode(t,r){let n=OO.prototype.getClassName.call(t),a=t.children,i,l,o;r&&(t.attrs.container=r),ra[n]||(fr.warn('Can not find a node with class name "'+n+'". Fallback to "Shape".'),n="Shape");const c=ra[n];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 n=0;n0?r[0]:void 0}_generalFind(t,r){const n=[];return this._descendants(a=>{const i=a._isMatch(t);return i&&n.push(a),!!(i&&r)}),n}_descendants(t){let r=!1;const n=this.getChildren();for(const a of n){if(r=t(a),r)return!0;if(a.hasChildren()&&(r=a._descendants(t),r))return!0}return!1}toObject(){const t=oa.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(r=>{t.children.push(r.toObject())}),t}isAncestorOf(t){let r=t.getParent();for(;r;){if(r._id===this._id)return!0;r=r.getParent()}return!1}clone(t){const r=oa.prototype.clone.call(this,t);return this.getChildren().forEach(function(n){r.add(n.clone())}),r}getAllIntersections(t){const r=[];return this.find("Shape").forEach(n=>{n.isVisible()&&n.intersects(t)&&r.push(n)}),r}_clearSelfAndDescendantCache(t){var r;super._clearSelfAndDescendantCache(t),!this.isCached()&&((r=this.children)===null||r===void 0||r.forEach(function(n){n._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(r,n){r.index=n}),this._requestDraw()}drawScene(t,r,n){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(r).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,r,n);return this}drawHit(t,r){if(!this.shouldDrawHit(r))return this;const n=this.getLayer(),a=t||n&&n.hitCanvas,i=a&&a.getContext(),l=this._getCanvasCache();if(l&&l.hit){i.save();const c=this.getAbsoluteTransform(r).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,r);return this}_drawChildren(t,r,n,a){var i;const l=r&&r.getContext(),o=this.clipWidth(),c=this.clipHeight(),d=this.clipFunc(),u=typeof o=="number"&&typeof c=="number"||d,m=n===this;if(u){l.save();const x=this.getAbsoluteTransform(n);let y=x.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 b=this.clipX(),j=this.clipY();l.rect(b||0,j||0,o,c)}l.clip.apply(l,_),y=x.copy().invert().getMatrix(),l.transform(y[0],y[1],y[2],y[3],y[4],y[5])}const f=!m&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";f&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(x){x[t](r,n,a)}),f&&l.restore(),u&&l.restore()}getClientRect(t={}){var r;const n=t.skipTransform,a=t.relativeTo;let i,l,o,c,d={x:1/0,y:1/0,width:0,height:0};const u=this;(r=this.children)===null||r===void 0||r.forEach(function(x){if(!x.visible())return;const y=x.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 m=this.find("Shape");let f=!1;for(let x=0;xs.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",A6=s=>{const t=UO(s);if(t==="pointer")return ra.pointerEventsEnabled&&iwe.pointer;if(t==="touch")return iwe.touch;if(t==="mouse")return iwe.mouse};function E$e(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&fr.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const pus="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);",P7=[];let a0e=class extends I0{constructor(t){super(E$e(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),P7.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{E$e(this.attrs)}),this._checkVisibility()}_validateAdd(t){const r=t.getType()==="Layer",n=t.getType()==="FastLayer";r||n||fr.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===dus){let r;if(t.charAt(0)==="."){const n=t.slice(1);t=document.getElementsByClassName(n)[0]}else t.charAt(0)!=="#"?r=t:r=t.slice(1),t=document.getElementById(r);if(!t)throw"Can not find container in document with id "+r}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,r=t.length;for(let n=0;n-1&&P7.splice(r,1),fr.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}:(fr.warn(pus),null)}_getPointerById(t){return this._pointerPositions.find(r=>r.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 r=new _k({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),n=r.getContext()._context,a=this.children;return(t.x||t.y)&&n.translate(-1*t.x,-1*t.y),a.forEach(function(i){if(!i.isVisible())return;const l=i._toKonvaCanvas(t);n.drawImage(l._canvas,t.x,t.y,l.getWidth()/l.getPixelRatio(),l.getHeight()/l.getPixelRatio())}),r}getIntersection(t){if(!t)return null;const r=this.children,n=r.length,a=n-1;for(let i=a;i>=0;i--){const l=r[i].getIntersection(t);if(l)return l}return null}_resizeDOM(){const t=this.width(),r=this.height();this.content&&(this.content.style.width=t+T$e,this.content.style.height=r+T$e),this.bufferCanvas.setSize(t,r),this.bufferHitCanvas.setSize(t,r),this.children.forEach(n=>{n.setSize({width:t,height:r}),n.draw()})}add(t,...r){if(arguments.length>1){for(let a=0;amus&&fr.warn("The stage has "+n+" 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(),ra.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return Xht(t,this)}setPointerCapture(t){Qht(t,this)}releaseCapture(t){I7(t)}getLayers(){return this.children}_bindContentEvents(){ra.isBrowser&&fus.forEach(([t,r])=>{this.content.addEventListener(t,n=>{this[r](n)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const r=A6(t.type);r&&this._fire(r.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const r=A6(t.type);r&&this._fire(r.pointerover,{evt:t,target:this,currentTarget:this})}_getTargetShape(t){let r=this[t+"targetShape"];return r&&!r.getStage()&&(r=null),r}_pointerleave(t){const r=A6(t.type),n=UO(t.type);if(!r)return;this.setPointersPositions(t);const a=this._getTargetShape(n),i=!(ra.isDragging()||ra.isTransforming())||ra.hitOnDragEnabled;a&&i?(a._fireAndBubble(r.pointerout,{evt:t}),a._fireAndBubble(r.pointerleave,{evt:t}),this._fire(r.pointerleave,{evt:t,target:this,currentTarget:this}),this[n+"targetShape"]=null):i&&(this._fire(r.pointerleave,{evt:t,target:this,currentTarget:this}),this._fire(r.pointerout,{evt:t,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(t){const r=A6(t.type),n=UO(t.type);if(!r)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(Rl.justDragged=!1,ra["_"+n+"ListenClick"]=!0,!l||!l.isListening()){this[n+"ClickStartShape"]=void 0;return}ra.capturePointerEventsEnabled&&l.setPointerCapture(i.id),this[n+"ClickStartShape"]=l,l._fireAndBubble(r.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(r.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(t){const r=A6(t.type),n=UO(t.type);if(!r)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(ra.isDragging()&&Rl.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(ra.isDragging()||ra.isTransforming())||ra.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(n);this._changedPointerPositions.forEach(d=>{const u=awe(d.id)||this.getIntersection(d),m=d.id,f={evt:t,pointerId:m},x=c!==u;if(x&&c&&(c._fireAndBubble(r.pointerout,{...f},u),c._fireAndBubble(r.pointerleave,{...f},u)),u){if(l[u._id])return;l[u._id]=!0}u&&u.isListening()?(o=!0,x&&(u._fireAndBubble(r.pointerover,{...f},c),u._fireAndBubble(r.pointerenter,{...f},c),this[n+"targetShape"]=u),u._fireAndBubble(r.pointermove,{...f})):c&&(this._fire(r.pointerover,{evt:t,target:this,currentTarget:this,pointerId:m}),this[n+"targetShape"]=null)}),o||this._fire(r.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const r=A6(t.type),n=UO(t.type);if(!r)return;this.setPointersPositions(t);const a=this[n+"ClickStartShape"],i=this[n+"ClickEndShape"],l={};let o=!1;this._changedPointerPositions.forEach(c=>{const d=awe(c.id)||this.getIntersection(c);if(d){if(d.releaseCapture(c.id),l[d._id])return;l[d._id]=!0}const u=c.id,m={evt:t,pointerId:u};let f=!1;ra["_"+n+"InDblClickWindow"]?(f=!0,clearTimeout(this[n+"DblTimeout"])):Rl.justDragged||(ra["_"+n+"InDblClickWindow"]=!0,clearTimeout(this[n+"DblTimeout"])),this[n+"DblTimeout"]=setTimeout(function(){ra["_"+n+"InDblClickWindow"]=!1},ra.dblClickWindow),d&&d.isListening()?(o=!0,this[n+"ClickEndShape"]=d,d._fireAndBubble(r.pointerup,{...m}),ra["_"+n+"ListenClick"]&&a&&a===d&&(d._fireAndBubble(r.pointerclick,{...m}),f&&i&&i===d&&d._fireAndBubble(r.pointerdblclick,{...m}))):(this[n+"ClickEndShape"]=null,o||(this._fire(r.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),ra["_"+n+"ListenClick"]&&this._fire(r.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:u}),f&&this._fire(r.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:u}))}),o||this._fire(r.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),ra["_"+n+"ListenClick"]=!1,t.cancelable&&n!=="touch"&&n!=="pointer"&&t.preventDefault()}_contextmenu(t){this.setPointersPositions(t);const r=this.getIntersection(this.getPointerPosition());r&&r.isListening()?r._fireAndBubble(_Se,{evt:t}):this._fire(_Se,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const r=this.getIntersection(this.getPointerPosition());r&&r.isListening()?r._fireAndBubble(wSe,{evt:t}):this._fire(wSe,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const r=awe(t.pointerId)||this.getIntersection(this.getPointerPosition());r&&r._fireAndBubble(SI,TAe(t)),I7(t.pointerId)}_lostpointercapture(t){I7(t.pointerId)}setPointersPositions(t){const r=this._getContentPosition();let n=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-r.left)/r.scaleX,y:(i.clientY-r.top)/r.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,i=>{this._changedPointerPositions.push({id:i.identifier,x:(i.clientX-r.left)/r.scaleX,y:(i.clientY-r.top)/r.scaleY})})):(n=(t.clientX-r.left)/r.scaleX,a=(t.clientY-r.top)/r.scaleY,this.pointerPos={x:n,y:a},this._pointerPositions=[{x:n,y:a,id:fr._getFirstPointerId(t)}],this._changedPointerPositions=[{x:n,y:a,id:fr._getFirstPointerId(t)}])}_setPointerPosition(t){fr.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 _k({width:this.width(),height:this.height()}),this.bufferHitCanvas=new SAe({pixelRatio:1,width:this.width(),height:this.height()}),!ra.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 fr.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}};a0e.prototype.nodeType=cus;wu(a0e);ks.addGetterSetter(a0e,"container");ra.isBrowser&&document.addEventListener("visibilitychange",()=>{P7.forEach(s=>{s.batchDraw()})});const cmt="hasShadow",dmt="shadowRGBA",umt="patternImage",hmt="linearGradient",mmt="radialGradient";let Hq;function owe(){return Hq||(Hq=fr.createCanvasElement().getContext("2d"),Hq)}const L7={};function xus(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function gus(s){s.stroke()}function yus(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function vus(s){s.stroke()}function bus(){this._clearCache(cmt)}function _us(){this._clearCache(dmt)}function wus(){this._clearCache(umt)}function jus(){this._clearCache(hmt)}function Nus(){this._clearCache(mmt)}let Un=class extends oa{constructor(t){super(t);let r,n=0;for(;r=fr.getHitColor(),!(r&&!(r in L7));)if(n++,n>=1e4){fr.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."),r=fr.getRandomColor();break}this.colorKey=r,L7[r]=this}getContext(){return fr.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return fr.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(cmt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(umt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const r=owe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(r&&r.setTransform){const n=new _0;n.translate(this.fillPatternX(),this.fillPatternY()),n.rotate(ra.getAngle(this.fillPatternRotation())),n.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),n.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const a=n.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);r.setTransform(i)}return r}}_getLinearGradient(){return this._getCache(hmt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const r=owe(),n=this.fillLinearGradientStartPoint(),a=this.fillLinearGradientEndPoint(),i=r.createLinearGradient(n.x,n.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 r=this.getStage();if(!r)return!1;const n=r.bufferHitCanvas;return n.getContext().clear(),this.drawHit(n,void 0,!0),n.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return oa.prototype.destroy.call(this),delete L7[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var r;if(!((r=this.attrs.perfectDrawEnabled)!==null&&r!==void 0?r:!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){fr.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 r=!1,n=this.getParent();for(;n;){if(n.isCached()){r=!0;break}n=n.getParent()}const a=t.skipTransform,i=t.relativeTo||r&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,u=l.height+c,m=!t.skipShadow&&this.hasShadow(),f=m?this.shadowOffsetX():0,x=m?this.shadowOffsetY():0,y=d+Math.abs(f),_=u+Math.abs(x),b=m&&this.shadowBlur()||0,j=y+b*2,N=_+b*2,C={width:j,height:N,x:-(c/2+b)+Math.min(f,0)+l.x,y:-(c/2+b)+Math.min(x,0)+l.y};return a?C:this._transformedRect(C,i)}drawScene(t,r,n){const a=this.getLayer(),i=t||a.getCanvas(),l=i.getContext(),o=this._getCanvasCache(),c=this.getSceneFunc(),d=this.hasShadow();let u;const m=!1,f=r===this;if(!this.isVisible()&&!f)return this;if(o){l.save();const x=this.getAbsoluteTransform(r).getMatrix();return l.transform(x[0],x[1],x[2],x[3],x[4],x[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!m){u=this.getStage();const x=n||u.bufferCanvas,y=x.getContext();n?(y.save(),y.setTransform(1,0,0,1,0,0),y.clearRect(0,0,x.width,x.height),y.restore()):y.clear(),y.save(),y._applyLineJoin(this),y._applyMiterLimit(this);const _=this.getAbsoluteTransform(r).getMatrix();y.transform(_[0],_[1],_[2],_[3],_[4],_[5]),c.call(this,y,this),y.restore();const b=x.pixelRatio;d&&l._applyShadow(this),f||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(x._canvas,x.x||0,x.y||0,x.width/b,x.height/b)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!f){const x=this.getAbsoluteTransform(r).getMatrix();l.transform(x[0],x[1],x[2],x[3],x[4],x[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,r,n=!1){if(!this.shouldDrawHit(r,n))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||fr.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 m=this.getAbsoluteTransform(r).getMatrix();return l.transform(m[0],m[1],m[2],m[3],m[4],m[5]),this._drawCachedHitCanvas(l),l.restore(),this}if(!o)return this;if(l.save(),l._applyLineJoin(this),l._applyMiterLimit(this),!(this===r)){const m=this.getAbsoluteTransform(r).getMatrix();l.transform(m[0],m[1],m[2],m[3],m[4],m[5])}return o.call(this,l,this),l.restore(),this}drawHitFromCache(t=0){const r=this._getCanvasCache(),n=this._getCachedSceneCanvas(),a=r.hit,i=a.getContext(),l=a.getWidth(),o=a.getHeight();i.clear(),i.drawImage(n._canvas,0,0,l,o);try{const c=i.getImageData(0,0,l,o),d=c.data,u=d.length,m=fr._hexToRgb(this.colorKey);for(let f=0;ft?(d[f]=m.r,d[f+1]=m.g,d[f+2]=m.b,d[f+3]=255):d[f+3]=0;i.putImageData(c,0,0)}catch(c){fr.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return Xht(t,this)}setPointerCapture(t){Qht(t,this)}releaseCapture(t){I7(t)}};Un.prototype._fillFunc=xus;Un.prototype._strokeFunc=gus;Un.prototype._fillFuncHit=yus;Un.prototype._strokeFuncHit=vus;Un.prototype._centroid=!1;Un.prototype.nodeType="Shape";wu(Un);Un.prototype.eventListeners={};Un.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",bus);Un.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",_us);Un.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",wus);Un.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",jus);Un.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Nus);ks.addGetterSetter(Un,"stroke",void 0,Yht());ks.addGetterSetter(Un,"strokeWidth",2,Zn());ks.addGetterSetter(Un,"fillAfterStrokeEnabled",!1);ks.addGetterSetter(Un,"hitStrokeWidth","auto",CAe());ks.addGetterSetter(Un,"strokeHitEnabled",!0,H1());ks.addGetterSetter(Un,"perfectDrawEnabled",!0,H1());ks.addGetterSetter(Un,"shadowForStrokeEnabled",!0,H1());ks.addGetterSetter(Un,"lineJoin");ks.addGetterSetter(Un,"lineCap");ks.addGetterSetter(Un,"miterLimit");ks.addGetterSetter(Un,"sceneFunc");ks.addGetterSetter(Un,"hitFunc");ks.addGetterSetter(Un,"dash");ks.addGetterSetter(Un,"dashOffset",0,Zn());ks.addGetterSetter(Un,"shadowColor",void 0,JA());ks.addGetterSetter(Un,"shadowBlur",0,Zn());ks.addGetterSetter(Un,"shadowOpacity",1,Zn());ks.addComponentsGetterSetter(Un,"shadowOffset",["x","y"]);ks.addGetterSetter(Un,"shadowOffsetX",0,Zn());ks.addGetterSetter(Un,"shadowOffsetY",0,Zn());ks.addGetterSetter(Un,"fillPatternImage");ks.addGetterSetter(Un,"fill",void 0,Yht());ks.addGetterSetter(Un,"fillPatternX",0,Zn());ks.addGetterSetter(Un,"fillPatternY",0,Zn());ks.addGetterSetter(Un,"fillLinearGradientColorStops");ks.addGetterSetter(Un,"strokeLinearGradientColorStops");ks.addGetterSetter(Un,"fillRadialGradientStartRadius",0);ks.addGetterSetter(Un,"fillRadialGradientEndRadius",0);ks.addGetterSetter(Un,"fillRadialGradientColorStops");ks.addGetterSetter(Un,"fillPatternRepeat","repeat");ks.addGetterSetter(Un,"fillEnabled",!0);ks.addGetterSetter(Un,"strokeEnabled",!0);ks.addGetterSetter(Un,"shadowEnabled",!0);ks.addGetterSetter(Un,"dashEnabled",!0);ks.addGetterSetter(Un,"strokeScaleEnabled",!0);ks.addGetterSetter(Un,"fillPriority","color");ks.addComponentsGetterSetter(Un,"fillPatternOffset",["x","y"]);ks.addGetterSetter(Un,"fillPatternOffsetX",0,Zn());ks.addGetterSetter(Un,"fillPatternOffsetY",0,Zn());ks.addComponentsGetterSetter(Un,"fillPatternScale",["x","y"]);ks.addGetterSetter(Un,"fillPatternScaleX",1,Zn());ks.addGetterSetter(Un,"fillPatternScaleY",1,Zn());ks.addComponentsGetterSetter(Un,"fillLinearGradientStartPoint",["x","y"]);ks.addComponentsGetterSetter(Un,"strokeLinearGradientStartPoint",["x","y"]);ks.addGetterSetter(Un,"fillLinearGradientStartPointX",0);ks.addGetterSetter(Un,"strokeLinearGradientStartPointX",0);ks.addGetterSetter(Un,"fillLinearGradientStartPointY",0);ks.addGetterSetter(Un,"strokeLinearGradientStartPointY",0);ks.addComponentsGetterSetter(Un,"fillLinearGradientEndPoint",["x","y"]);ks.addComponentsGetterSetter(Un,"strokeLinearGradientEndPoint",["x","y"]);ks.addGetterSetter(Un,"fillLinearGradientEndPointX",0);ks.addGetterSetter(Un,"strokeLinearGradientEndPointX",0);ks.addGetterSetter(Un,"fillLinearGradientEndPointY",0);ks.addGetterSetter(Un,"strokeLinearGradientEndPointY",0);ks.addComponentsGetterSetter(Un,"fillRadialGradientStartPoint",["x","y"]);ks.addGetterSetter(Un,"fillRadialGradientStartPointX",0);ks.addGetterSetter(Un,"fillRadialGradientStartPointY",0);ks.addComponentsGetterSetter(Un,"fillRadialGradientEndPoint",["x","y"]);ks.addGetterSetter(Un,"fillRadialGradientEndPointX",0);ks.addGetterSetter(Un,"fillRadialGradientEndPointY",0);ks.addGetterSetter(Un,"fillPatternRotation",0);ks.addGetterSetter(Un,"fillRule",void 0,JA());ks.backCompat(Un,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const kus="beforeDraw",Sus="draw",fmt=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Cus=fmt.length;let eM=class extends I0{constructor(t){super(t),this.canvas=new _k,this.hitCanvas=new SAe({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 r=this.getStage();return r&&r.content&&(r.content.removeChild(this.getNativeCanvasElement()),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;let r=1,n=!1;for(;;){for(let a=0;a0)return{antialiased:!0};return{}}drawScene(t,r,n){const a=this.getLayer(),i=t||a&&a.getCanvas();return this._fire(kus,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),I0.prototype.drawScene.call(this,i,r,n),this._fire(Sus,{node:this}),this}drawHit(t,r){const n=this.getLayer(),a=t||n&&n.hitCanvas;return n&&n.clearBeforeDraw()&&n.getHitCanvas().getContext().clear(),I0.prototype.drawHit.call(this,a,r),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){fr.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return fr.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 fr.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};eM.prototype.nodeType="Layer";wu(eM);ks.addGetterSetter(eM,"imageSmoothingEnabled",!0);ks.addGetterSetter(eM,"clearBeforeDraw",!0);ks.addGetterSetter(eM,"hitGraphEnabled",!0,H1());class EAe extends eM{constructor(t){super(t),this.listening(!1),fr.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}EAe.prototype.nodeType="FastLayer";wu(EAe);let wL=class extends I0{_validateAdd(t){const r=t.getType();r!=="Group"&&r!=="Shape"&&fr.throw("You may only add groups and shapes to groups.")}};wL.prototype.nodeType="Group";wu(wL);const lwe=function(){return rE.performance&&rE.performance.now?function(){return rE.performance.now()}:function(){return new Date().getTime()}}();class $y{constructor(t,r){this.id=$y.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:lwe(),frameRate:0},this.func=t,this.setLayers(r)}setLayers(t){let r=[];return t&&(r=Array.isArray(t)?t:[t]),this.layers=r,this}getLayers(){return this.layers}addLayer(t){const r=this.layers,n=r.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=A$e,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=M$e,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===A$e?this.setTime(t):this.state===M$e&&this.setTime(this.duration-t)}pause(){this.state=Eus,this.fire("onPause")}getTimer(){return new Date().getTime()}}class td{constructor(t){const r=this,n=t.node,a=n._id,i=t.easing||D7.Linear,l=!!t.yoyo;let o,c;typeof t.duration>"u"?o=.3:t.duration===0?o=.001:o=t.duration,this.node=n,this._id=Aus++;const d=n.getLayer()||(n instanceof ra.Stage?n.getLayers():null);d||fr.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new $y(function(){r.tween.onEnterFrame()},d),this.tween=new Mus(c,function(u){r._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),td.attrs[a]||(td.attrs[a]={}),td.attrs[a][this._id]||(td.attrs[a][this._id]={}),td.tweens[a]||(td.tweens[a]={});for(c in t)Tus[c]===void 0&&this._addAttr(c,t[c]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,r){const n=this.node,a=n._id;let i,l,o,c,d;const u=td.tweens[a][t];u&&delete td.attrs[a][u][t];let m=n.getAttr(t);if(fr._isArray(r))if(i=[],l=Math.max(r.length,m.length),t==="points"&&r.length!==m.length&&(r.length>m.length?(c=m,m=fr._prepareArrayForTween(m,r,n.closed())):(o=r,r=fr._prepareArrayForTween(r,m,n.closed()))),t.indexOf("fill")===0)for(let f=0;f{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,r=td.attrs[t._id][this._id];r.points&&r.points.trueEnd&&t.setAttr("points",r.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const t=this.node,r=td.attrs[t._id][this._id];r.points&&r.points.trueStart&&t.points(r.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,r=this._id,n=td.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in n)delete td.tweens[t][a];delete td.attrs[t][r],td.tweens[t]&&(Object.keys(td.tweens[t]).length===0&&delete td.tweens[t],Object.keys(td.attrs[t]).length===0&&delete td.attrs[t])}}td.attrs={};td.tweens={};oa.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new td(s).play()};const D7={BackEaseIn(s,t,r,n){return r*(s/=n)*s*((1.70158+1)*s-1.70158)+t},BackEaseOut(s,t,r,n){return r*((s=s/n-1)*s*((1.70158+1)*s+1.70158)+1)+t},BackEaseInOut(s,t,r,n){let a=1.70158;return(s/=n/2)<1?r/2*(s*s*(((a*=1.525)+1)*s-a))+t:r/2*((s-=2)*s*(((a*=1.525)+1)*s+a)+2)+t},ElasticEaseIn(s,t,r,n,a,i){let l=0;return s===0?t:(s/=n)===1?t+r:(i||(i=n*.3),!a||a0?t:r),u=l*r,m=o*(o>0?t:r),f=c*(c>0?r:t);return{x:d,y:n?-1*f:m,width:u-d,height:f-m}}}F2.prototype._centroid=!0;F2.prototype.className="Arc";F2.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];wu(F2);ks.addGetterSetter(F2,"innerRadius",0,Zn());ks.addGetterSetter(F2,"outerRadius",0,Zn());ks.addGetterSetter(F2,"angle",0,Zn());ks.addGetterSetter(F2,"clockwise",!1,H1());function jSe(s,t,r,n,a,i,l){const o=Math.sqrt(Math.pow(r-s,2)+Math.pow(n-t,2)),c=Math.sqrt(Math.pow(a-r,2)+Math.pow(i-n,2)),d=l*o/(o+c),u=l*c/(o+c),m=r-d*(a-s),f=n-d*(i-t),x=r+u*(a-s),y=n+u*(i-t);return[m,f,x,y]}function P$e(s,t){const r=s.length,n=[];for(let a=2;a=0){const c=Math.sqrt(o);r.push((-i+c)/(2*a)),r.push((-i-c)/(2*a))}}}return r.filter(n=>n>0&&n<1).flatMap(n=>t.map(a=>{const i=1-n;return i*i*i*a[0]+3*i*i*n*a[1]+3*i*n*n*a[2]+n*n*n*a[3]}))}let z2=class extends Un{constructor(t){super(t),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(t){const r=this.points(),n=r.length,a=this.tension(),i=this.closed(),l=this.bezier();if(!n)return;let o=0;if(t.beginPath(),t.moveTo(r[0],r[1]),a!==0&&n>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 n,a;const l=r/2;n=0;for(let o=0;o<20;o++)a=l*Pus[20][o]+l,n+=Lus[20][o]*Rus(s,t,a);return l*n},D$e=(s,t,r)=>{r===void 0&&(r=1);const n=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*(n*n+a*a),c=4*(n*i+a*l),d=i*i+l*l;if(o===0)return r*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const u=c/(2*o),m=d/o,f=r+u,x=m-u*u,y=f*f+x>0?Math.sqrt(f*f+x):0,_=u*u+x>0?Math.sqrt(u*u+x):0,b=u+Math.sqrt(u*u+x)!==0?x*Math.log(Math.abs((f+y)/(u+_))):0;return Math.sqrt(o)/2*(f*y-u*_+b)};function Rus(s,t,r){const n=NSe(1,r,s),a=NSe(1,r,t),i=n*n+a*a;return Math.sqrt(i)}const NSe=(s,t,r)=>{const n=r.length-1;let a,i;if(n===0)return 0;if(s===0){i=0;for(let l=0;l<=n;l++)i+=Dus[n][l]*Math.pow(1-t,n-l)*Math.pow(t,l)*r[l];return i}else{a=new Array(n);for(let l=0;l{let n=1,a=s/t,i=(s-r(a))/t,l=0;for(;n>.001;){const o=r(a+i),c=Math.abs(s-o)/t;if(c500)break}return a};let Uy=class Qx extends Un{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=Qx.parsePathData(this.data()),this.pathLength=Qx.getPathLength(this.dataArray)}_sceneFunc(t){const r=this.dataArray;t.beginPath();let n=!1;for(let a=0;au?d:u,b=d>u?1:d/u,j=d>u?u/d:1;t.translate(o,c),t.rotate(x),t.scale(b,j),t.arc(0,0,_,m,m+f,1-y),t.scale(1/b,1/j),t.rotate(-x),t.translate(-o,-c);break;case"z":n=!0,t.closePath();break}}!n&&!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],m=c.points[4]+u;let f=Math.PI/180;if(Math.abs(d-m)m;x-=f){const y=Qx.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],x,0);t.push(y.x,y.y)}else for(let x=d+f;xr[a].pathLength;)t-=r[a].pathLength,++a;if(a===i)return n=r[a-1].points.slice(-2),{x:n[0],y:n[1]};if(t<.01)return r[a].command==="M"?(n=r[a].points.slice(0,2),{x:n[0],y:n[1]}):{x:r[a].start.x,y:r[a].start.y};const l=r[a],o=l.points;switch(l.command){case"L":return Qx.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return Qx.getPointOnCubicBezier(R$e(t,Qx.getPathLength(r),_=>L$e([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 Qx.getPointOnQuadraticBezier(R$e(t,Qx.getPathLength(r),_=>D$e([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],m=o[3],f=o[5],x=o[6];let y=o[4];return y+=f*t/l.pathLength,Qx.getPointOnEllipticalArc(c,d,u,m,y,x)}return null}static getPointOnLine(t,r,n,a,i,l,o){l=l??r,o=o??n;const c=this.getLineLength(r,n,a,i);if(c<1e-10)return{x:r,y:n};if(a===r)return{x:l,y:o+(i>n?t:-t)};const d=(i-n)/(a-r),u=Math.sqrt(t*t/(1+d*d))*(a=0&&(_+=2,_>=7&&(_-=7));continue}if(_>=0){if(_===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(N)){y.push(parseInt(N[0],10)),y.push(parseInt(N[1],10)),y.push(parseFloat(N.slice(2))),_+=3,_>=7&&(_-=7);continue}if(N==="11"||N==="10"||N==="01"){y.push(parseInt(N[0],10)),y.push(parseInt(N[1],10)),_+=2,_>=7&&(_-=7);continue}if(N==="0"||N==="1"){y.push(parseInt(N,10)),_+=1,_>=7&&(_-=7);continue}}else if(_===4){if(/^[01]\d+(?:\.\d+)?$/.test(N)){y.push(parseInt(N[0],10)),y.push(parseFloat(N.slice(1))),_+=2,_>=7&&(_-=7);continue}if(N==="0"||N==="1"){y.push(parseInt(N,10)),_+=1,_>=7&&(_-=7);continue}}const C=parseFloat(N);isNaN(C)?y.push(0):y.push(C),_+=1,_>=7&&(_-=7)}else{const C=parseFloat(N);isNaN(C)?y.push(0):y.push(C)}}for(;y.length>0&&!isNaN(y[0]);){let b="",j=[];const N=o,C=c;let A,E,D,R,F,O,B,K,Z,Q;switch(x){case"l":o+=y.shift(),c+=y.shift(),b="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(),te=y.shift();if(o+=W,c+=te,b="M",i.length>2&&i[i.length-1].command==="z"){for(let ne=i.length-2;ne>=0;ne--)if(i[ne].command==="M"){o=i[ne].points[0]+W,c=i[ne].points[1]+te;break}}j.push(o,c),x="l";break;case"M":o=y.shift(),c=y.shift(),b="M",j.push(o,c),x="L";break;case"h":o+=y.shift(),b="L",j.push(o,c);break;case"H":o=y.shift(),b="L",j.push(o,c);break;case"v":c+=y.shift(),b="L",j.push(o,c);break;case"V":c=y.shift(),b="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(),b="C",j.push(o,c);break;case"S":E=o,D=c,A=i[i.length-1],A.command==="C"&&(E=o+(o-A.points[2]),D=c+(c-A.points[3])),j.push(E,D,y.shift(),y.shift()),o=y.shift(),c=y.shift(),b="C",j.push(o,c);break;case"s":E=o,D=c,A=i[i.length-1],A.command==="C"&&(E=o+(o-A.points[2]),D=c+(c-A.points[3])),j.push(E,D,o+y.shift(),c+y.shift()),o+=y.shift(),c+=y.shift(),b="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(),b="Q",j.push(o,c);break;case"T":E=o,D=c,A=i[i.length-1],A.command==="Q"&&(E=o+(o-A.points[0]),D=c+(c-A.points[1])),o=y.shift(),c=y.shift(),b="Q",j.push(E,D,o,c);break;case"t":E=o,D=c,A=i[i.length-1],A.command==="Q"&&(E=o+(o-A.points[0]),D=c+(c-A.points[1])),o+=y.shift(),c+=y.shift(),b="Q",j.push(E,D,o,c);break;case"A":R=y.shift(),F=y.shift(),O=y.shift(),B=y.shift(),K=y.shift(),Z=o,Q=c,o=y.shift(),c=y.shift(),b="A",j=this.convertEndpointToCenterParameterization(Z,Q,o,c,B,K,R,F,O);break;case"a":R=y.shift(),F=y.shift(),O=y.shift(),B=y.shift(),K=y.shift(),Z=o,Q=c,o+=y.shift(),c+=y.shift(),b="A",j=this.convertEndpointToCenterParameterization(Z,Q,o,c,B,K,R,F,O);break}i.push({command:b||x,points:j,start:{x:N,y:C},pathLength:this.calcLength(N,C,b||x,j)})}(x==="z"||x==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,r,n,a){let i,l,o,c;const d=Qx;switch(n){case"L":return d.getLineLength(t,r,a[0],a[1]);case"C":return L$e([t,a[0],a[2],a[4]],[r,a[1],a[3],a[5]],1);case"Q":return D$e([t,a[0],a[2]],[r,a[1],a[3]],1);case"A":i=0;const u=a[4],m=a[5],f=a[4]+m;let x=Math.PI/180;if(Math.abs(u-f)f;c-=x)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+x;c1&&(o*=Math.sqrt(x),c*=Math.sqrt(x));let y=Math.sqrt((o*o*(c*c)-o*o*(f*f)-c*c*(m*m))/(o*o*(f*f)+c*c*(m*m)));i===l&&(y*=-1),isNaN(y)&&(y=0);const _=y*o*f/c,b=y*-c*m/o,j=(t+n)/2+Math.cos(u)*_-Math.sin(u)*b,N=(r+a)/2+Math.sin(u)*_+Math.cos(u)*b,C=function(B){return Math.sqrt(B[0]*B[0]+B[1]*B[1])},A=function(B,K){return(B[0]*K[0]+B[1]*K[1])/(C(B)*C(K))},E=function(B,K){return(B[0]*K[1]=1&&(O=0),l===0&&O>0&&(O=O-2*Math.PI),l===1&&O<0&&(O=O+2*Math.PI),[j,N,o,c,D,O,u,l]}};Uy.prototype.className="Path";Uy.prototype._attrsAffectingSize=["data"];wu(Uy);ks.addGetterSetter(Uy,"data");class tM extends z2{_sceneFunc(t){super._sceneFunc(t);const r=Math.PI*2,n=this.points();let a=n;const i=this.tension()!==0&&n.length>4;i&&(a=this.getTensionPoints());const l=this.pointerLength(),o=n.length;let c,d;if(i){const f=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],n[o-2],n[o-1]],x=Uy.calcLength(a[a.length-4],a[a.length-3],"C",f),y=Uy.getPointOnQuadraticBezier(Math.min(1,1-l/x),f[0],f[1],f[2],f[3],f[4],f[5]);c=n[o-2]-y.x,d=n[o-1]-y.y}else c=n[o-2]-n[o-4],d=n[o-1]-n[o-3];const u=(Math.atan2(d,c)+r)%r,m=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(n[o-2],n[o-1]),t.rotate(u),t.moveTo(0,0),t.lineTo(-l,m/2),t.lineTo(-l,-m/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(n[0],n[1]),i?(c=(a[0]+a[2])/2-n[0],d=(a[1]+a[3])/2-n[1]):(c=n[2]-n[0],d=n[3]-n[1]),t.rotate((Math.atan2(-d,-c)+r)%r),t.moveTo(0,0),t.lineTo(-l,m/2),t.lineTo(-l,-m/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const r=this.dashEnabled();r&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),r&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),r=this.pointerWidth()/2;return{x:t.x,y:t.y-r,width:t.width,height:t.height+r*2}}}tM.prototype.className="Arrow";wu(tM);ks.addGetterSetter(tM,"pointerLength",10,Zn());ks.addGetterSetter(tM,"pointerWidth",10,Zn());ks.addGetterSetter(tM,"pointerAtBeginning",!1);ks.addGetterSetter(tM,"pointerAtEnding",!0);class D8 extends Un{_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)}}D8.prototype._centroid=!0;D8.prototype.className="Circle";D8.prototype._attrsAffectingSize=["radius"];wu(D8);ks.addGetterSetter(D8,"radius",0,Zn());class c4 extends Un{_sceneFunc(t){const r=this.radiusX(),n=this.radiusY();t.beginPath(),t.save(),r!==n&&t.scale(1,n/r),t.arc(0,0,r,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)}}c4.prototype.className="Ellipse";c4.prototype._centroid=!0;c4.prototype._attrsAffectingSize=["radiusX","radiusY"];wu(c4);ks.addComponentsGetterSetter(c4,"radius",["x","y"]);ks.addGetterSetter(c4,"radiusX",0,Zn());ks.addGetterSetter(c4,"radiusY",0,Zn());let G1=class pmt extends Un{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",r=>{this._removeImageLoad(r.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(),r=this.hasShadow();return t&&r?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const r=this.getWidth(),n=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,r,n]:l=[i,0,0,r,n]}(this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?fr.drawRoundedRectPath(t,r,n,a):t.rect(0,0,r,n),t.closePath(),t.fillStrokeShape(this)),i&&(a&&t.clip(),t.drawImage.apply(t,l))}_hitFunc(t){const r=this.width(),n=this.height(),a=this.cornerRadius();t.beginPath(),a?fr.drawRoundedRectPath(t,r,n,a):t.rect(0,0,r,n),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,r,n;return(n=(t=this.attrs.width)!==null&&t!==void 0?t:(r=this.image())===null||r===void 0?void 0:r.width)!==null&&n!==void 0?n:0}getHeight(){var t,r,n;return(n=(t=this.attrs.height)!==null&&t!==void 0?t:(r=this.image())===null||r===void 0?void 0:r.height)!==null&&n!==void 0?n:0}static fromURL(t,r,n=null){const a=fr.createImageElement();a.onload=function(){const i=new pmt({image:a});r(i)},a.onerror=n,a.crossOrigin="Anonymous",a.src=t}};G1.prototype.className="Image";G1.prototype._attrsAffectingSize=["image"];wu(G1);ks.addGetterSetter(G1,"cornerRadius",0,n0e(4));ks.addGetterSetter(G1,"image");ks.addComponentsGetterSetter(G1,"crop",["x","y","width","height"]);ks.addGetterSetter(G1,"cropX",0,Zn());ks.addGetterSetter(G1,"cropY",0,Zn());ks.addGetterSetter(G1,"cropWidth",0,Zn());ks.addGetterSetter(G1,"cropHeight",0,Zn());const xmt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],Ous="Change.konva",Fus="none",kSe="up",SSe="right",CSe="down",TSe="left",zus=xmt.length;let AAe=class extends wL{constructor(t){super(t),this.on("add.konva",function(r){this._addListeners(r.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){let r=this,n;const a=function(){r._sync()};for(n=0;n{r=Math.min(r,l.x),n=Math.max(n,l.x),a=Math.min(a,l.y),i=Math.max(i,l.y)}),{x:r,y:a,width:n-r,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)}}d4.prototype.className="RegularPolygon";d4.prototype._centroid=!0;d4.prototype._attrsAffectingSize=["radius"];wu(d4);ks.addGetterSetter(d4,"radius",0,Zn());ks.addGetterSetter(d4,"sides",0,Zn());ks.addGetterSetter(d4,"cornerRadius",0,n0e(4));const O$e=Math.PI*2;class rM extends Un{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,O$e,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),O$e,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)}}rM.prototype.className="Ring";rM.prototype._centroid=!0;rM.prototype._attrsAffectingSize=["innerRadius","outerRadius"];wu(rM);ks.addGetterSetter(rM,"innerRadius",0,Zn());ks.addGetterSetter(rM,"outerRadius",0,Zn());class ow extends Un{constructor(t){super(t),this._updated=!0,this.anim=new $y(()=>{const r=this._updated;return this._updated=!1,r}),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 r=this.animation(),n=this.frameIndex(),a=n*4,i=this.animations()[r],l=this.frameOffsets(),o=i[a+0],c=i[a+1],d=i[a+2],u=i[a+3],m=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,d,u),t.closePath(),t.fillStrokeShape(this)),m)if(l){const f=l[r],x=n*2;t.drawImage(m,o,c,d,u,f[x+0],f[x+1],d,u)}else t.drawImage(m,o,c,d,u,0,0,d,u)}_hitFunc(t){const r=this.animation(),n=this.frameIndex(),a=n*4,i=this.animations()[r],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[r],u=n*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(),r=this.animation(),n=this.animations(),a=n[r],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(r)){const i=a[n+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(r+i),a[n+1]=""):t.push(r)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(r+(a[n+1]||""))?t.push(r+a[n+1]):n>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(r)?t[t.length-1]+=r:r&&t.push(r);return t},[])}const M6="auto",Bus="center",gmt="inherit",JR="justify",$us="Change.konva",ymt="2d",F$e="-",vmt="left",Uus="text",qus="Text",Vus="top",Hus="bottom",z$e="middle",bmt="normal",Gus="px ",Gq=" ",Wus="right",B$e="rtl",Kus="word",Yus="char",$$e="none",cwe="…",_mt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Zus=_mt.length;let eO=null;function Xus(){if(eO!==null)return eO;eO=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(ymt);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 r=t.getImageData(0,0,10,10).data;for(let n=3;n0){eO=!0;break}}}catch{}return eO}function Qus(s){return s.split(",").map(t=>{t=t.trim();const r=t.indexOf(" ")>=0,n=t.indexOf('"')>=0||t.indexOf("'")>=0;return r&&!n&&(t=`"${t}"`),t}).join(", ")}let Wq;function dwe(){return Wq||(Wq=fr.createCanvasElement().getContext(ymt),Wq)}function Jus(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function ehs(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function ths(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let dd=class extends Un{constructor(t){super(ths(t)),this._partialTextX=0,this._partialTextY=0;for(let r=0;rje+ek(xe.text).length,0),fe=ae+de;_({char:ue,index:fe,x:F,y:D+O,lineIndex:E,column:ae,isLastInLine:Q,width:this.measureSize(ue).width,context:t})}t.fillStrokeShape(this),_&&t.restore(),F+=this.measureSize(ue).width+y}}else y!==0&&t.setAttr("letterSpacing",`${y}px`),this._partialTextX=F,this._partialTextY=D+O,this._partialText=K,t.fillStrokeShape(this);if(A){t.save(),t.beginPath();const te=ra.legacyTextRendering?0:-Math.round(o/4),ne=W;t.moveTo(ne,D+O+te);const ae=f===JR&&!Q?x-l*2:Z;t.lineTo(ne+Math.round(ae),D+O+te),t.lineWidth=o/15;const ue=this._getLinearGradient();t.strokeStyle=ue||b,t.stroke(),t.restore()}t.restore(),i>1&&(D+=c)}}_hitFunc(t){const r=this.getWidth(),n=this.getHeight();t.beginPath(),t.rect(0,0,r,n),t.closePath(),t.fillStrokeShape(this)}setText(t){const r=fr._isString(t)?t:t==null?"":t+"";return this._setAttr(Uus,r),this}getWidth(){return this.attrs.width===M6||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===M6||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return fr.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var r,n,a,i,l,o,c,d,u,m,f;let x=dwe(),y=this.fontSize(),_;x.save(),x.font=this._getContextFont(),_=x.measureText(t),x.restore();const b=y/100;return{actualBoundingBoxAscent:(r=_.actualBoundingBoxAscent)!==null&&r!==void 0?r:71.58203125*b,actualBoundingBoxDescent:(n=_.actualBoundingBoxDescent)!==null&&n!==void 0?n:0,actualBoundingBoxLeft:(a=_.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*b,actualBoundingBoxRight:(i=_.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*b,alphabeticBaseline:(l=_.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=_.emHeightAscent)!==null&&o!==void 0?o:100*b,emHeightDescent:(c=_.emHeightDescent)!==null&&c!==void 0?c:-20*b,fontBoundingBoxAscent:(d=_.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*b,fontBoundingBoxDescent:(u=_.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*b,hangingBaseline:(m=_.hangingBaseline)!==null&&m!==void 0?m:72.80000305175781*b,ideographicBaseline:(f=_.ideographicBaseline)!==null&&f!==void 0?f:-21*b,width:_.width,height:y}}_getContextFont(){return this.fontStyle()+Gq+this.fontVariant()+Gq+(this.fontSize()+Gus)+Qus(this.fontFamily())}_addTextLine(t){this.align()===JR&&(t=t.trim());const n=this._getTextWidth(t);return this.textArr.push({text:t,width:n,lastInParagraph:!1})}_getTextWidth(t){const r=this.letterSpacing(),n=t.length;return dwe().measureText(t).width+r*n}_setTextData(){let t=this.text().split(` `),r=+this.fontSize(),n=0,a=this.lineHeight()*r,i=this.attrs.width,l=this.attrs.height,o=i!==M6&&i!==void 0,c=l!==M6&&l!==void 0,d=this.padding(),u=i-d*2,m=l-d*2,f=0,x=this.wrap(),y=x!==$$e,_=x!==Yus&&y,b=this.ellipsis();this.textArr=[],dwe().font=this._getContextFont();const j=b?this._getTextWidth(cwe):0;for(let N=0,C=t.length;Nu)for(;A.length>0;){let D=0,R=ek(A).length,F="",O=0;for(;D>>1,K=ek(A),Z=K.slice(0,B+1).join(""),Q=this._getTextWidth(Z);(b&&c&&f+a>m?Q+j:Q)<=u?(D=B+1,F=Z,O=Q):R=B}if(F){if(_){const Z=ek(A),Q=ek(F),W=Z[Q.length],te=W===Gq||W===F$e;let ne;if(te&&O<=u)ne=Q.length;else{const ae=Q.lastIndexOf(Gq),ue=Q.lastIndexOf(F$e);ne=Math.max(ae,ue)+1}ne>0&&(D=ne,F=Z.slice(0,D).join(""),O=this._getTextWidth(F))}if(F=F.trimRight(),this._addTextLine(F),n=Math.max(n,O),f+=a,this._shouldHandleEllipsis(f)){this._tryToAddEllipsisToLastLine();break}if(A=ek(A).slice(D).join("").trimLeft(),A.length>0&&(E=this._getTextWidth(A),E<=u)){this._addTextLine(A),f+=a,n=Math.max(n,E);break}}else break}else this._addTextLine(A),f+=a,n=Math.max(n,E),this._shouldHandleEllipsis(f)&&Nm)break}this.textHeight=r,this.textWidth=n}_shouldHandleEllipsis(t){const r=+this.fontSize(),n=this.lineHeight()*r,a=this.attrs.height,i=a!==M6&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==$$e)||i&&t+n>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,r=t!==M6&&t!==void 0,n=this.padding(),a=t-n*2,i=this.ellipsis(),l=this.textArr[this.textArr.length-1];!l||!i||(r&&(this._getTextWidth(l.text+cwe)r?null:Uy.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=Uy.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 r=this.textDecoration(),n=this.fill(),a=this.fontSize(),i=this.glyphInfo,l=r.indexOf("underline")!==-1,o=r.indexOf("line-through")!==-1;l&&t.beginPath();for(let c=0;c=1){const n=r[0].p0;t.moveTo(n.x,n.y)}for(let n=0;nthis.pathLength&&j-this.pathLength<=d?this.pathLength:j);if(!N)return;const C=Uy.getLineLength(y.x,y.y,N.x,N.y);let A=0;if(c)try{A=c(r[x-1].char,_)*this.fontSize()}catch{A=0}y.x+=A,N.x+=A,this.textWidth+=A;const E=Uy.getPointOnLine(A+C/2,y.x,y.y,N.x,N.y),D=Math.atan2(N.y-y.y,N.x-y.x);this.glyphInfo.push({transposeX:E.x,transposeY:E.y,text:t[x],rotation:D,p0:y,p1:N,width:C}),f+=b}}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 r=t[0]||0,n=t[0]||0,a=t[1]||0,i=t[1]||0,l,o;for(let d=0;ds+`.${kmt}`).join(" "),U$e="nodesRect",nhs=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],ahs={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},ihs="ontouchstart"in ra._global;function ohs(s,t,r){if(s==="rotater")return r;t+=fr.degToRad(ahs[s]||0);const n=(fr.radToDeg(t)%360+360)%360;return fr._inRange(n,315+22.5,360)||fr._inRange(n,0,22.5)?"ns-resize":fr._inRange(n,45-22.5,45+22.5)?"nesw-resize":fr._inRange(n,90-22.5,90+22.5)?"ew-resize":fr._inRange(n,135-22.5,135+22.5)?"nwse-resize":fr._inRange(n,180-22.5,180+22.5)?"ns-resize":fr._inRange(n,225-22.5,225+22.5)?"nesw-resize":fr._inRange(n,270-22.5,270+22.5)?"ew-resize":fr._inRange(n,315-22.5,315+22.5)?"nwse-resize":(fr.error("Transformer has unknown angle for cursor detection: "+n),"pointer")}const wfe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],q$e=1e8;function lhs(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 Smt(s,t,r){const n=r.x+(s.x-r.x)*Math.cos(t)-(s.y-r.y)*Math.sin(t),a=r.y+(s.x-r.x)*Math.sin(t)+(s.y-r.y)*Math.cos(t);return{...s,rotation:s.rotation+t,x:n,y:a}}function chs(s,t){const r=lhs(s);return Smt(s,t,r)}function dhs(s,t,r){let n=t;for(let a=0;aa.isAncestorOf(this)?(fr.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=t=r,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(nhs.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 r;t.on(`dragstart.${this._getEventNamespace()}`,n=>{r=t.getAbsolutePosition(),!this.isDragging()&&t!==this.findOne(".back")&&this.startDrag(n,!1)}),t.on(`dragmove.${this._getEventNamespace()}`,n=>{if(!r)return;const a=t.getAbsolutePosition(),i=a.x-r.x,l=a.y-r.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(n)}),r=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(U$e),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(U$e,this.__getNodeRect)}__getNodeShape(t,r=this.rotation(),n){const a=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),i=t.getAbsoluteScale(n),l=t.getAbsolutePosition(n),o=a.x*i.x-t.offsetX()*i.x,c=a.y*i.y-t.offsetY()*i.y,d=(ra.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 Smt(u,-ra.getAngle(r),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-q$e,y:-q$e,width:0,height:0,rotation:0};const r=[];this.nodes().map(d=>{const u=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),m=[{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}],f=d.getAbsoluteTransform();m.forEach(function(x){const y=f.point(x);r.push(y)})});const n=new _0;n.rotate(-ra.getAngle(this.rotation()));let a=1/0,i=1/0,l=-1/0,o=-1/0;r.forEach(function(d){const u=n.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)}),n.invert();const c=n.point({x:a,y:i});return{x:c.x,y:c.y,width:l-a,height:o-i,rotation:ra.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(),wfe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const r=new FB({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:ihs?10:"auto"}),n=this;r.on("mousedown touchstart",function(a){n._handleMouseDown(a)}),r.on("dragstart",a=>{r.stopDrag(),a.cancelBubble=!0}),r.on("dragend",a=>{a.cancelBubble=!0}),r.on("mouseenter",()=>{const a=ra.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=ohs(t,a,i);r.getStage().content&&(r.getStage().content.style.cursor=l),this._cursorChange=!0}),r.on("mouseout",()=>{r.getStage().content&&(r.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(r)}_createBack(){const t=new Un({name:"back",width:0,height:0,sceneFunc(r,n){const a=n.getParent(),i=a.padding(),l=n.width(),o=n.height();if(r.beginPath(),r.rect(-i,-i,l+i*2,o+i*2),a.rotateEnabled()&&a.rotateLineVisible()){const c=a.rotateAnchorAngle(),d=a.rotateAnchorOffset(),u=fr.degToRad(c),m=Math.sin(u),f=-Math.cos(u),x=l/2,y=o/2;let _=1/0;f<0?_=Math.min(_,-y/f):f>0&&(_=Math.min(_,(o-y)/f)),m<0?_=Math.min(_,-x/m):m>0&&(_=Math.min(_,(l-x)/m));const b=x+m*_,j=y+f*_,N=fr._sign(o),C=b+m*d*N,A=j+f*d*N;r.moveTo(b,j),r.lineTo(C,A)}r.fillStrokeShape(n)},hitFunc:(r,n)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();r.beginPath(),r.rect(-a,-a,n.width()+a*2,n.height()+a*2),r.fillStrokeShape(n)}});this.add(t),this._proxyDrag(t),t.on("dragstart",r=>{r.cancelBubble=!0}),t.on("dragmove",r=>{r.cancelBubble=!0}),t.on("dragend",r=>{r.cancelBubble=!0}),this.on("dragmove",r=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const r=this._getNodeRect(),n=r.width,a=r.height,i=Math.sqrt(Math.pow(n,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(n/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},ESe++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(c=>{c._fire("transformstart",{evt:t.evt,target:c})})}_handleMouseMove(t){let r,n,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 N=this._getNodeRect();r=i.x()-N.width/2,n=-i.y()+N.height/2;const C=ra.getAngle(this.rotateAnchorAngle());let A=Math.atan2(-n,r)+Math.PI/2-C;N.height<0&&(A-=Math.PI);const D=ra.getAngle(this.rotation())+A,R=ra.getAngle(this.rotationSnapTolerance()),O=dhs(this.rotationSnaps(),D,R)-N.rotation,B=chs(N,O);this._fitNodesInto(B,t);return}const m=this.shiftBehavior();let f;m==="inverted"?f=this.keepRatio()&&!t.shiftKey:m==="none"?f=this.keepRatio():f=this.keepRatio()||t.shiftKey;let x=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(f){const N=x?{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(N.x-i.x(),2)+Math.pow(N.y-i.y(),2));const C=this.findOne(".top-left").x()>N.x?-1:1,A=this.findOne(".top-left").y()>N.y?-1:1;r=a*this.cos*C,n=a*this.sin*A,this.findOne(".top-left").x(N.x-r),this.findOne(".top-left").y(N.y-n)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(f){const N=x?{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()-N.x,2)+Math.pow(N.y-i.y(),2));const C=this.findOne(".top-right").x()N.y?-1:1;r=a*this.cos*C,n=a*this.sin*A,this.findOne(".top-right").x(N.x+r),this.findOne(".top-right").y(N.y-n)}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(f){const N=x?{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(N.x-i.x(),2)+Math.pow(i.y()-N.y,2));const C=N.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,r){const n=this._getNodeRect(),a=1;if(fr._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(fr._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new _0;if(i.rotate(ra.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const f=i.point({x:-this.padding()*2,y:0});t.x+=f.x,t.y+=f.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=f.x,this._anchorDragOffset.y-=f.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const f=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=f.x,this._anchorDragOffset.y-=f.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const f=i.point({x:0,y:-this.padding()*2});t.x+=f.x,t.y+=f.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=f.x,this._anchorDragOffset.y-=f.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const f=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=f.x,this._anchorDragOffset.y-=f.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const f=this.boundBoxFunc()(n,t);f?t=f:fr.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new _0;o.translate(n.x,n.y),o.rotate(n.rotation),o.scale(n.width/l,n.height/l);const c=new _0,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 m=c.multiply(o.invert());this._nodes.forEach(f=>{var x;if(!f.getStage())return;const y=f.getParent().getAbsoluteTransform(),_=f.getTransform().copy();_.translate(f.offsetX(),f.offsetY());const b=new _0;b.multiply(y.copy().invert()).multiply(m).multiply(y).multiply(_);const j=b.decompose();f.setAttrs(j),(x=f.getLayer())===null||x===void 0||x.batchDraw()}),this.rotation(fr._getRotation(t.rotation)),this._nodes.forEach(f=>{this._fire("transform",{evt:r,target:f}),f._fire("transform",{evt:r,target:f})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,r){this.findOne(t).setAttrs(r)}update(){var t;const r=this._getNodeRect();this.rotation(fr._getRotation(r.rotation));const n=r.width,a=r.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize(),d=this.find("._anchor");d.forEach(D=>{D.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:n/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:n,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:n,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:n/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:n,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),m=this.rotateAnchorOffset(),f=fr.degToRad(u),x=Math.sin(f),y=-Math.cos(f),_=n/2,b=a/2;let j=1/0;y<0?j=Math.min(j,-b/y):y>0&&(j=Math.min(j,(a-b)/y)),x<0?j=Math.min(j,-_/x):x>0&&(j=Math.min(j,(n-_)/x));const N=_+x*j,C=b+y*j,A=fr._sign(a);this._batchChangeChild(".rotater",{x:N+x*m*A,y:C+y*m*A-o*y,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:n,height:a,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(D=>D.draggable()),x:0,y:0});const E=this.anchorStyleFunc();E&&d.forEach(D=>{E(D)}),(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=""),wL.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(fr.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return oa.prototype.toObject.call(this)}clone(t){return oa.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};yl.isTransforming=()=>ESe>0;function uhs(s){return s instanceof Array||fr.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){wfe.indexOf(t)===-1&&fr.warn("Unknown anchor name: "+t+". Available names are: "+wfe.join(", "))}),s||[]}yl.prototype.className="Transformer";wu(yl);ks.addGetterSetter(yl,"enabledAnchors",wfe,uhs);ks.addGetterSetter(yl,"flipEnabled",!0,H1());ks.addGetterSetter(yl,"resizeEnabled",!0);ks.addGetterSetter(yl,"anchorSize",10,Zn());ks.addGetterSetter(yl,"rotateEnabled",!0);ks.addGetterSetter(yl,"rotateLineVisible",!0);ks.addGetterSetter(yl,"rotationSnaps",[]);ks.addGetterSetter(yl,"rotateAnchorOffset",50,Zn());ks.addGetterSetter(yl,"rotateAnchorAngle",0,Zn());ks.addGetterSetter(yl,"rotateAnchorCursor","crosshair");ks.addGetterSetter(yl,"rotationSnapTolerance",5,Zn());ks.addGetterSetter(yl,"borderEnabled",!0);ks.addGetterSetter(yl,"anchorStroke","rgb(0, 161, 255)");ks.addGetterSetter(yl,"anchorStrokeWidth",1,Zn());ks.addGetterSetter(yl,"anchorFill","white");ks.addGetterSetter(yl,"anchorCornerRadius",0,Zn());ks.addGetterSetter(yl,"borderStroke","rgb(0, 161, 255)");ks.addGetterSetter(yl,"borderStrokeWidth",1,Zn());ks.addGetterSetter(yl,"borderDash");ks.addGetterSetter(yl,"keepRatio",!0);ks.addGetterSetter(yl,"shiftBehavior","default");ks.addGetterSetter(yl,"centeredScaling",!1);ks.addGetterSetter(yl,"ignoreStroke",!1);ks.addGetterSetter(yl,"padding",0,Zn());ks.addGetterSetter(yl,"nodes");ks.addGetterSetter(yl,"node");ks.addGetterSetter(yl,"boundBoxFunc");ks.addGetterSetter(yl,"anchorDragBoundFunc");ks.addGetterSetter(yl,"anchorStyleFunc");ks.addGetterSetter(yl,"shouldOverdrawWholeArea",!1);ks.addGetterSetter(yl,"useSingleNodeRotation",!0);ks.backCompat(yl,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class B2 extends Un{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,ra.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)}}B2.prototype.className="Wedge";B2.prototype._centroid=!0;B2.prototype._attrsAffectingSize=["radius"];wu(B2);ks.addGetterSetter(B2,"radius",0,Zn());ks.addGetterSetter(B2,"angle",0,Zn());ks.addGetterSetter(B2,"clockwise",!1);ks.backCompat(B2,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function V$e(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const hhs=[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],mhs=[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 fhs(s,t){const r=s.data,n=s.width,a=s.height;let i,l,o,c,d,u,m,f,x,y,_,b,j,N,C,A,E,D,R,F;const O=t+t+1,B=n-1,K=a-1,Z=t+1,Q=Z*(Z+1)/2,W=new V$e,te=hhs[t],ne=mhs[t];let ae=null,ue=W,me=null,de=null;for(let fe=1;fe>ne,R!==0?(R=255/R,r[l]=(c*te>>ne)*R,r[l+1]=(d*te>>ne)*R,r[l+2]=(u*te>>ne)*R):r[l]=r[l+1]=r[l+2]=0,c-=f,d-=x,u-=y,m-=_,f-=me.r,x-=me.g,y-=me.b,_-=me.a,i=o+((i=je+t+1)>ne,R>0?(R=255/R,r[i]=(c*te>>ne)*R,r[i+1]=(d*te>>ne)*R,r[i+2]=(u*te>>ne)*R):r[i]=r[i+1]=r[i+2]=0,c-=f,d-=x,u-=y,m-=_,f-=me.r,x-=me.g,y-=me.b,_-=me.a,i=fe+((i=xe+Z)0&&fhs(t,r)};ks.addGetterSetter(oa,"blurRadius",0,Zn(),ks.afterSetFilter);const xhs=function(s){const t=this.brightness()*255,r=s.data,n=r.length;for(let a=0;a255?255:a,i=i<0?0:i>255?255:i,l=l<0?0:l>255?255:l,r[o]=a,r[o+1]=i,r[o+2]=l};ks.addGetterSetter(oa,"contrast",0,Zn(),ks.afterSetFilter);const vhs=function(s){var t,r,n,a,i,l,o,c,d;const u=s.data,m=s.width,f=s.height,x=Math.min(1,Math.max(0,(r=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&r!==void 0?r:.5)),y=Math.min(1,Math.max(0,(a=(n=this.embossWhiteLevel)===null||n===void 0?void 0:n.call(this))!==null&&a!==void 0?a:.5)),b=(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),N=x*10,C=y*255,A=b*Math.PI/180,E=Math.cos(A),D=Math.sin(A),R=128/1020*N,F=new Uint8ClampedArray(u),O=new Float32Array(m*f);for(let W=0,te=0;teW<0?0:W>255?255:W;for(let W=1;Wa&&(a=i),c=t[C+1],co&&(o=c),m=t[C+2],mu&&(u=m);a===n&&(a=255,n=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let x,y,_,b,j,N;if(f>0)x=a+f*(255-a),y=n-f*(n-0),_=o+f*(255-o),b=l-f*(l-0),j=u+f*(255-u),N=d-f*(d-0);else{const C=(a+n)*.5;x=a+f*(a-C),y=n+f*(n-C);const A=(o+l)*.5;_=o+f*(o-A),b=l+f*(l-A);const E=(u+d)*.5;j=u+f*(u-E),N=d+f*(d-E)}for(let C=0;Cd?f:d;const x=l,y=i,_=360/y*Math.PI/180;for(let b=0;bd?f:d;const x=l,y=i,_=0;let b,j;for(u=0;ut&&(A=C,E=0,D=-1),a=0;a=0&&x=0&&y=0&&x=0&&y=255*4?255:0}return l}function Phs(s,t,r){const n=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(n.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&x=0&&y=r))for(let C=_;C=n)continue;const A=(r*C+N)*4;d+=l[A+0],u+=l[A+1],m+=l[A+2],f+=l[A+3],j+=1}d=d/j,u=u/j,m=m/j,f=f/j;for(let N=x;N=r))for(let C=_;C=n)continue;const A=(r*C+N)*4;l[A+0]=d,l[A+1]=u,l[A+2]=m,l[A+3]=f}}};ks.addGetterSetter(oa,"pixelSize",8,Zn(),ks.afterSetFilter);const Ohs=function(s){const t=Math.round(this.levels()*254)+1,r=s.data,n=r.length,a=255/t;for(let i=0;i255?255:s<0?0:Math.round(s)});ks.addGetterSetter(oa,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});ks.addGetterSetter(oa,"blue",0,Kht,ks.afterSetFilter);const zhs=function(s){const t=s.data,r=t.length,n=this.red(),a=this.green(),i=this.blue(),l=this.alpha();for(let o=0;o255?255:s<0?0:Math.round(s)});ks.addGetterSetter(oa,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});ks.addGetterSetter(oa,"blue",0,Kht,ks.afterSetFilter);ks.addGetterSetter(oa,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const Bhs=function(s){const t=s.data,r=t.length;for(let n=0;n=128&&(r[n]=255-a,r[n+1]=255-i,r[n+2]=255-l)}return s},Uhs=function(s){const t=this.threshold()*255,r=s.data,n=r.length;for(let a=0;aur||Je[ns]!==yt[ur]){var Hr=` `+Je[ns].replace(" at new "," at ");return Y.displayName&&Hr.includes("")&&(Hr=Hr.replace("",Y.displayName)),Hr}while(1<=ns&&0<=ur);break}}}finally{mn=!1,Error.prepareStackTrace=be}return(Y=Y?Y.displayName||Y.name:"")?Kr(Y):""}var wn=Object.prototype.hasOwnProperty,ca=[],Vi=-1;function so(Y){return{current:Y}}function Ka(Y){0>Vi||(Y.current=ca[Vi],ca[Vi]=null,Vi--)}function kn(Y,J){Vi++,ca[Vi]=Y.current,Y.current=J}var Fi={},zi=so(Fi),Qa=so(!1),Hi=Fi;function Gi(Y,J){var be=Y.type.contextTypes;if(!be)return Fi;var Ue=Y.stateNode;if(Ue&&Ue.__reactInternalMemoizedUnmaskedChildContext===J)return Ue.__reactInternalMemoizedMaskedChildContext;var Je={},yt;for(yt in be)Je[yt]=J[yt];return Ue&&(Y=Y.stateNode,Y.__reactInternalMemoizedUnmaskedChildContext=J,Y.__reactInternalMemoizedMaskedChildContext=Je),Je}function Qn(Y){return Y=Y.childContextTypes,Y!=null}function vr(){Ka(Qa),Ka(zi)}function Ca(Y,J,be){if(zi.current!==Fi)throw Error(l(168));kn(zi,J),kn(Qa,be)}function Ji(Y,J,be){var Ue=Y.stateNode;if(J=J.childContextTypes,typeof Ue.getChildContext!="function")return be;Ue=Ue.getChildContext();for(var Je in Ue)if(!(Je in J))throw Error(l(108,F(Y)||"Unknown",Je));return i({},be,Ue)}function Zo(Y){return Y=(Y=Y.stateNode)&&Y.__reactInternalMemoizedMergedChildContext||Fi,Hi=zi.current,kn(zi,Y),kn(Qa,Qa.current),!0}function vl(Y,J,be){var Ue=Y.stateNode;if(!Ue)throw Error(l(169));be?(Y=Ji(Y,J,Hi),Ue.__reactInternalMemoizedMergedChildContext=Y,Ka(Qa),Ka(zi),kn(zi,Y)):Ka(Qa),kn(Qa,be)}var vo=Math.clz32?Math.clz32:sp,hd=Math.log,ju=Math.LN2;function sp(Y){return Y>>>=0,Y===0?32:31-(hd(Y)/ju|0)|0}var Nu=64,qh=4194304;function ku(Y){switch(Y&-Y){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 Y&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return Y&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return Y}}function Cd(Y,J){var be=Y.pendingLanes;if(be===0)return 0;var Ue=0,Je=Y.suspendedLanes,yt=Y.pingedLanes,ns=be&268435455;if(ns!==0){var ur=ns&~Je;ur!==0?Ue=ku(ur):(yt&=ns,yt!==0&&(Ue=ku(yt)))}else ns=be&~Je,ns!==0?Ue=ku(ns):yt!==0&&(Ue=ku(yt));if(Ue===0)return 0;if(J!==0&&J!==Ue&&!(J&Je)&&(Je=Ue&-Ue,yt=J&-J,Je>=yt||Je===16&&(yt&4194240)!==0))return J;if(Ue&4&&(Ue|=be&16),J=Y.entangledLanes,J!==0)for(Y=Y.entanglements,J&=Ue;0be;be++)J.push(Y);return J}function rp(Y,J,be){Y.pendingLanes|=J,J!==536870912&&(Y.suspendedLanes=0,Y.pingedLanes=0),Y=Y.eventTimes,J=31-vo(J),Y[J]=be}function Xu(Y,J){var be=Y.pendingLanes&~J;Y.pendingLanes=J,Y.suspendedLanes=0,Y.pingedLanes=0,Y.expiredLanes&=J,Y.mutableReadLanes&=J,Y.entangledLanes&=J,J=Y.entanglements;var Ue=Y.eventTimes;for(Y=Y.expirationTimes;0>=ns,Je-=ns,Mc=1<<32-vo(J)+Je|be<eo?(Pd=Ja,Ja=null):Pd=Ja.sibling;var Qo=ga(Fr,Ja,rr[eo],Na);if(Qo===null){Ja===null&&(Ja=Pd);break}Y&&Ja&&Qo.alternate===null&&J(Fr,Ja),Us=yt(Qo,Us,eo),Ai===null?Ra=Qo:Ai.sibling=Qo,Ai=Qo,Ja=Pd}if(eo===rr.length)return be(Fr,Ja),na&&xf(Fr,eo),Ra;if(Ja===null){for(;eoeo?(Pd=Ja,Ja=null):Pd=Ja.sibling;var Vx=ga(Fr,Ja,Qo.value,Na);if(Vx===null){Ja===null&&(Ja=Pd);break}Y&&Ja&&Vx.alternate===null&&J(Fr,Ja),Us=yt(Vx,Us,eo),Ai===null?Ra=Vx:Ai.sibling=Vx,Ai=Vx,Ja=Pd}if(Qo.done)return be(Fr,Ja),na&&xf(Fr,eo),Ra;if(Ja===null){for(;!Qo.done;eo++,Qo=rr.next())Qo=ro(Fr,Qo.value,Na),Qo!==null&&(Us=yt(Qo,Us,eo),Ai===null?Ra=Qo:Ai.sibling=Qo,Ai=Qo);return na&&xf(Fr,eo),Ra}for(Ja=Ue(Fr,Ja);!Qo.done;eo++,Qo=rr.next())Qo=oc(Ja,Fr,eo,Qo.value,Na),Qo!==null&&(Y&&Qo.alternate!==null&&Ja.delete(Qo.key===null?eo:Qo.key),Us=yt(Qo,Us,eo),Ai===null?Ra=Qo:Ai.sibling=Qo,Ai=Qo);return Y&&Ja.forEach(function($4){return J(Fr,$4)}),na&&xf(Fr,eo),Ra}function Cf(Fr,Us,rr,Na){if(typeof rr=="object"&&rr!==null&&rr.type===u&&rr.key===null&&(rr=rr.props.children),typeof rr=="object"&&rr!==null){switch(rr.$$typeof){case c:e:{for(var Ra=rr.key,Ai=Us;Ai!==null;){if(Ai.key===Ra){if(Ra=rr.type,Ra===u){if(Ai.tag===7){be(Fr,Ai.sibling),Us=Je(Ai,rr.props.children),Us.return=Fr,Fr=Us;break e}}else if(Ai.elementType===Ra||typeof Ra=="object"&&Ra!==null&&Ra.$$typeof===C&&eb(Ra)===Ai.type){be(Fr,Ai.sibling),Us=Je(Ai,rr.props),Us.ref=Vp(Fr,Ai,rr),Us.return=Fr,Fr=Us;break e}be(Fr,Ai);break}else J(Fr,Ai);Ai=Ai.sibling}rr.type===u?(Us=as(rr.props.children,Fr.mode,Na,rr.key),Us.return=Fr,Fr=Us):(Na=Io(rr.type,rr.key,rr.props,null,Fr.mode,Na),Na.ref=Vp(Fr,Us,rr),Na.return=Fr,Fr=Na)}return ns(Fr);case d:e:{for(Ai=rr.key;Us!==null;){if(Us.key===Ai)if(Us.tag===4&&Us.stateNode.containerInfo===rr.containerInfo&&Us.stateNode.implementation===rr.implementation){be(Fr,Us.sibling),Us=Je(Us,rr.children||[]),Us.return=Fr,Fr=Us;break e}else{be(Fr,Us);break}else J(Fr,Us);Us=Us.sibling}Us=Qw(rr,Fr.mode,Na),Us.return=Fr,Fr=Us}return ns(Fr);case C:return Ai=rr._init,Cf(Fr,Us,Ai(rr._payload),Na)}if(te(rr))return no(Fr,Us,rr,Na);if(D(rr))return eh(Fr,Us,rr,Na);J0(Fr,rr)}return typeof rr=="string"&&rr!==""||typeof rr=="number"?(rr=""+rr,Us!==null&&Us.tag===6?(be(Fr,Us.sibling),Us=Je(Us,rr),Us.return=Fr,Fr=Us):(be(Fr,Us),Us=jb(rr,Fr.mode,Na),Us.return=Fr,Fr=Us),ns(Fr)):be(Fr,Us)}return Cf}var Il=Tu(!0),xM=Tu(!1),ey=so(null),tb=null,Hp=null,Gp=null;function vw(){Gp=Hp=tb=null}function sb(Y,J,be){Le?(kn(ey,J._currentValue),J._currentValue=be):(kn(ey,J._currentValue2),J._currentValue2=be)}function Td(Y){var J=ey.current;Ka(ey),Le?Y._currentValue=J:Y._currentValue2=J}function Rm(Y,J,be){for(;Y!==null;){var Ue=Y.alternate;if((Y.childLanes&J)!==J?(Y.childLanes|=J,Ue!==null&&(Ue.childLanes|=J)):Ue!==null&&(Ue.childLanes&J)!==J&&(Ue.childLanes|=J),Y===be)break;Y=Y.return}}function Ed(Y,J){tb=Y,Gp=Hp=null,Y=Y.dependencies,Y!==null&&Y.firstContext!==null&&(Y.lanes&J&&(Zh=!0),Y.firstContext=null)}function gf(Y){var J=Le?Y._currentValue:Y._currentValue2;if(Gp!==Y)if(Y={context:Y,memoizedValue:J,next:null},Hp===null){if(tb===null)throw Error(l(308));Hp=Y,tb.dependencies={lanes:0,firstContext:Y}}else Hp=Hp.next=Y;return J}var op=null;function kl(Y){op===null?op=[Y]:op.push(Y)}function Hn(Y,J,be,Ue){var Je=J.interleaved;return Je===null?(be.next=be,kl(J)):(be.next=Je.next,Je.next=be),J.interleaved=be,Jr(Y,Ue)}function Jr(Y,J){Y.lanes|=J;var be=Y.alternate;for(be!==null&&(be.lanes|=J),be=Y,Y=Y.return;Y!==null;)Y.childLanes|=J,be=Y.alternate,be!==null&&(be.childLanes|=J),be=Y,Y=Y.return;return be.tag===3?be.stateNode:null}var hl=!1;function Xn(Y){Y.updateQueue={baseState:Y.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Om(Y,J){Y=Y.updateQueue,J.updateQueue===Y&&(J.updateQueue={baseState:Y.baseState,firstBaseUpdate:Y.firstBaseUpdate,lastBaseUpdate:Y.lastBaseUpdate,shared:Y.shared,effects:Y.effects})}function Wh(Y,J){return{eventTime:Y,lane:J,tag:0,payload:null,callback:null,next:null}}function Cn(Y,J,be){var Ue=Y.updateQueue;if(Ue===null)return null;if(Ue=Ue.shared,uo&2){var Je=Ue.pending;return Je===null?J.next=J:(J.next=Je.next,Je.next=J),Ue.pending=J,Jr(Y,be)}return Je=Ue.interleaved,Je===null?(J.next=J,kl(Ue)):(J.next=Je.next,Je.next=J),Ue.interleaved=J,Jr(Y,be)}function ty(Y,J,be){if(J=J.updateQueue,J!==null&&(J=J.shared,(be&4194240)!==0)){var Ue=J.lanes;Ue&=Y.pendingLanes,be|=Ue,J.lanes=be,Bp(Y,be)}}function bw(Y,J){var be=Y.updateQueue,Ue=Y.alternate;if(Ue!==null&&(Ue=Ue.updateQueue,be===Ue)){var Je=null,yt=null;if(be=be.firstBaseUpdate,be!==null){do{var ns={eventTime:be.eventTime,lane:be.lane,tag:be.tag,payload:be.payload,callback:be.callback,next:null};yt===null?Je=yt=ns:yt=yt.next=ns,be=be.next}while(be!==null);yt===null?Je=yt=J:yt=yt.next=J}else Je=yt=J;be={baseState:Ue.baseState,firstBaseUpdate:Je,lastBaseUpdate:yt,shared:Ue.shared,effects:Ue.effects},Y.updateQueue=be;return}Y=be.lastBaseUpdate,Y===null?be.firstBaseUpdate=J:Y.next=J,be.lastBaseUpdate=J}function bv(Y,J,be,Ue){var Je=Y.updateQueue;hl=!1;var yt=Je.firstBaseUpdate,ns=Je.lastBaseUpdate,ur=Je.shared.pending;if(ur!==null){Je.shared.pending=null;var Hr=ur,Ln=Hr.next;Hr.next=null,ns===null?yt=Ln:ns.next=Ln,ns=Hr;var La=Y.alternate;La!==null&&(La=La.updateQueue,ur=La.lastBaseUpdate,ur!==ns&&(ur===null?La.firstBaseUpdate=Ln:ur.next=Ln,La.lastBaseUpdate=Hr))}if(yt!==null){var ro=Je.baseState;ns=0,La=Ln=Hr=null,ur=yt;do{var ga=ur.lane,oc=ur.eventTime;if((Ue&ga)===ga){La!==null&&(La=La.next={eventTime:oc,lane:0,tag:ur.tag,payload:ur.payload,callback:ur.callback,next:null});e:{var no=Y,eh=ur;switch(ga=J,oc=be,eh.tag){case 1:if(no=eh.payload,typeof no=="function"){ro=no.call(oc,ro,ga);break e}ro=no;break e;case 3:no.flags=no.flags&-65537|128;case 0:if(no=eh.payload,ga=typeof no=="function"?no.call(oc,ro,ga):no,ga==null)break e;ro=i({},ro,ga);break e;case 2:hl=!0}}ur.callback!==null&&ur.lane!==0&&(Y.flags|=64,ga=Je.effects,ga===null?Je.effects=[ur]:ga.push(ur))}else oc={eventTime:oc,lane:ga,tag:ur.tag,payload:ur.payload,callback:ur.callback,next:null},La===null?(Ln=La=oc,Hr=ro):La=La.next=oc,ns|=ga;if(ur=ur.next,ur===null){if(ur=Je.shared.pending,ur===null)break;ga=ur,ur=ga.next,ga.next=null,Je.lastBaseUpdate=ga,Je.shared.pending=null}}while(!0);if(La===null&&(Hr=ro),Je.baseState=Hr,Je.firstBaseUpdate=Ln,Je.lastBaseUpdate=La,J=Je.shared.interleaved,J!==null){Je=J;do ns|=Je.lane,Je=Je.next;while(Je!==J)}else yt===null&&(Je.shared.lanes=0);Gg|=ns,Y.lanes=ns,Y.memoizedState=ro}}function rb(Y,J,be){if(Y=J.effects,J.effects=null,Y!==null)for(J=0;Jbe?be:4,Y(!0);var Ue=v4.transition;v4.transition={};try{Y(!1),J()}finally{co=be,v4.transition=Ue}}function j4(){return Ic().memoizedState}function N4(Y,J,be){var Ue=Ux(Y);if(be={lane:Ue,action:be,hasEagerState:!1,eagerState:null,next:null},k4(Y))gM(J,be);else if(be=Hn(Y,J,be,Ue),be!==null){var Je=Ju();Um(be,Y,Ue,Je),nl(be,J,Ue)}}function yD(Y,J,be){var Ue=Ux(Y),Je={lane:Ue,action:be,hasEagerState:!1,eagerState:null,next:null};if(k4(Y))gM(J,Je);else{var yt=Y.alternate;if(Y.lanes===0&&(yt===null||yt.lanes===0)&&(yt=J.lastRenderedReducer,yt!==null))try{var ns=J.lastRenderedState,ur=yt(ns,be);if(Je.hasEagerState=!0,Je.eagerState=ur,Mm(ur,ns)){var Hr=J.interleaved;Hr===null?(Je.next=Je,kl(J)):(Je.next=Hr.next,Hr.next=Je),J.interleaved=Je;return}}catch{}finally{}be=Hn(Y,J,Je,Ue),be!==null&&(Je=Ju(),Um(be,Y,Ue,Je),nl(be,J,Ue))}}function k4(Y){var J=Y.alternate;return Y===zl||J!==null&&J===zl}function gM(Y,J){dp=nb=!0;var be=Y.pending;be===null?J.next=J:(J.next=be.next,be.next=J),Y.pending=J}function nl(Y,J,be){if(be&4194240){var Ue=J.lanes;Ue&=Y.pendingLanes,be|=Ue,J.lanes=be,Bp(Y,be)}}var Tw={readContext:gf,useCallback:_h,useContext:_h,useEffect:_h,useImperativeHandle:_h,useInsertionEffect:_h,useLayoutEffect:_h,useMemo:_h,useReducer:_h,useRef:_h,useState:_h,useDebugValue:_h,useDeferredValue:_h,useTransition:_h,useMutableSource:_h,useSyncExternalStore:_h,useId:_h,unstable_isNewReconciler:!1},vD={readContext:gf,useCallback:function(Y,J){return up().memoizedState=[Y,J===void 0?null:J],Y},useContext:gf,useEffect:ry,useImperativeHandle:function(Y,J,be){return be=be!=null?be.concat([Y]):null,Sw(4194308,4,ob.bind(null,J,Y),be)},useLayoutEffect:function(Y,J){return Sw(4194308,4,Y,J)},useInsertionEffect:function(Y,J){return Sw(4,2,Y,J)},useMemo:function(Y,J){var be=up();return J=J===void 0?null:J,Y=Y(),be.memoizedState=[Y,J],Y},useReducer:function(Y,J,be){var Ue=up();return J=be!==void 0?be(J):J,Ue.memoizedState=Ue.baseState=J,Y={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Y,lastRenderedState:J},Ue.queue=Y,Y=Y.dispatch=N4.bind(null,zl,Y),[Ue.memoizedState,Y]},useRef:function(Y){var J=up();return Y={current:Y},J.memoizedState=Y},useState:zm,useDebugValue:b4,useDeferredValue:function(Y){return up().memoizedState=Y},useTransition:function(){var Y=zm(!1),J=Y[0];return Y=hi.bind(null,Y[1]),up().memoizedState=Y,[J,Y]},useMutableSource:function(){},useSyncExternalStore:function(Y,J,be){var Ue=zl,Je=up();if(na){if(be===void 0)throw Error(l(407));be=be()}else{if(be=J(),ec===null)throw Error(l(349));Rg&30||Y2(Ue,J,be)}Je.memoizedState=be;var yt={value:be,getSnapshot:J};return Je.queue=yt,ry(kv.bind(null,Ue,yt,Y),[Y]),Ue.flags|=2048,Og(9,Nv.bind(null,Ue,yt,be,J),void 0,null),be},useId:function(){var Y=up(),J=ec.identifierPrefix;if(na){var be=Dm,Ue=Mc;be=(Ue&~(1<<32-vo(Ue)-1)).toString(32)+be,J=":"+J+"R"+be,be=ww++,0mp&&(J.flags|=128,Ue=!0,hb(Je,!1),J.lanes=4194304)}else{if(!Ue)if(Y=_v(yt),Y!==null){if(J.flags|=128,Ue=!0,Y=Y.updateQueue,Y!==null&&(J.updateQueue=Y,J.flags|=4),hb(Je,!0),Je.tail===null&&Je.tailMode==="hidden"&&!yt.alternate&&!na)return Yc(J),null}else 2*Xo()-Je.renderingStartTime>mp&&be!==1073741824&&(J.flags|=128,Ue=!0,hb(Je,!1),J.lanes=4194304);Je.isBackwards?(yt.sibling=J.child,J.child=yt):(Y=Je.last,Y!==null?Y.sibling=yt:J.child=yt,Je.last=yt)}return Je.tail!==null?(J=Je.tail,Je.rendering=J,Je.tail=J.sibling,Je.renderingStartTime=Xo(),J.sibling=null,Y=Vl.current,kn(Vl,Ue?Y&1|2:Y&1),J):(Yc(J),null);case 22:case 23:return Yw(),be=J.memoizedState!==null,Y!==null&&Y.memoizedState!==null!==be&&(J.flags|=8192),be&&J.mode&1?jh&1073741824&&(Yc(J),$e&&J.subtreeFlags&6&&(J.flags|=8192)):Yc(J),null;case 24:return null;case 25:return null}throw Error(l(156,J.tag))}function rN(Y,J){switch(Pr(J),J.tag){case 1:return Qn(J.type)&&vr(),Y=J.flags,Y&65536?(J.flags=Y&-65537|128,J):null;case 3:return yf(),Ka(Qa),Ka(zi),vf(),Y=J.flags,Y&65536&&!(Y&128)?(J.flags=Y&-65537|128,J):null;case 5:return H2(J),null;case 13:if(Ka(Vl),Y=J.memoizedState,Y!==null&&Y.dehydrated!==null){if(J.alternate===null)throw Error(l(340));wi()}return Y=J.flags,Y&65536?(J.flags=Y&-65537|128,J):null;case 19:return Ka(Vl),null;case 4:return yf(),null;case 10:return Td(J.type._context),null;case 22:case 23:return Yw(),null;case 24:return null;default:return null}}var nN=!1,Qu=!1,_D=typeof WeakSet=="function"?WeakSet:Set,Pa=null;function Bg(Y,J){var be=Y.ref;if(be!==null)if(typeof be=="function")try{be(null)}catch(Ue){ja(Y,J,Ue)}else be.current=null}function mb(Y,J,be){try{be()}catch(Ue){ja(Y,J,Ue)}}var M4=!1;function fb(Y,J){for(me(Y.containerInfo),Pa=J;Pa!==null;)if(Y=Pa,J=Y.child,(Y.subtreeFlags&1028)!==0&&J!==null)J.return=Y,Pa=J;else for(;Pa!==null;){Y=Pa;try{var be=Y.alternate;if(Y.flags&1024)switch(Y.tag){case 0:case 11:case 15:break;case 1:if(be!==null){var Ue=be.memoizedProps,Je=be.memoizedState,yt=Y.stateNode,ns=yt.getSnapshotBeforeUpdate(Y.elementType===Y.type?Ue:hp(Y.type,Ue),Je);yt.__reactInternalSnapshotBeforeUpdate=ns}break;case 3:$e&&Js(Y.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(ur){ja(Y,Y.return,ur)}if(J=Y.sibling,J!==null){J.return=Y.return,Pa=J;break}Pa=Y.return}return be=M4,M4=!1,be}function pb(Y,J,be){var Ue=J.updateQueue;if(Ue=Ue!==null?Ue.lastEffect:null,Ue!==null){var Je=Ue=Ue.next;do{if((Je.tag&Y)===Y){var yt=Je.destroy;Je.destroy=void 0,yt!==void 0&&mb(J,be,yt)}Je=Je.next}while(Je!==Ue)}}function zw(Y,J){if(J=J.updateQueue,J=J!==null?J.lastEffect:null,J!==null){var be=J=J.next;do{if((be.tag&Y)===Y){var Ue=be.create;be.destroy=Ue()}be=be.next}while(be!==J)}}function Dv(Y){var J=Y.ref;if(J!==null){var be=Y.stateNode;switch(Y.tag){case 5:Y=ne(be);break;default:Y=be}typeof J=="function"?J(Y):J.current=Y}}function Bw(Y){var J=Y.alternate;J!==null&&(Y.alternate=null,Bw(J)),Y.child=null,Y.deletions=null,Y.sibling=null,Y.tag===5&&(J=Y.stateNode,J!==null&&Ge(J)),Y.stateNode=null,Y.return=null,Y.dependencies=null,Y.memoizedProps=null,Y.memoizedState=null,Y.pendingProps=null,Y.stateNode=null,Y.updateQueue=null}function $g(Y){return Y.tag===5||Y.tag===3||Y.tag===4}function $w(Y){e:for(;;){for(;Y.sibling===null;){if(Y.return===null||$g(Y.return))return null;Y=Y.return}for(Y.sibling.return=Y.return,Y=Y.sibling;Y.tag!==5&&Y.tag!==6&&Y.tag!==18;){if(Y.flags&2||Y.child===null||Y.tag===4)continue e;Y.child.return=Y,Y=Y.child}if(!(Y.flags&2))return Y.stateNode}}function xb(Y,J,be){var Ue=Y.tag;if(Ue===5||Ue===6)Y=Y.stateNode,J?Ut(be,Y,J):es(be,Y);else if(Ue!==4&&(Y=Y.child,Y!==null))for(xb(Y,J,be),Y=Y.sibling;Y!==null;)xb(Y,J,be),Y=Y.sibling}function aN(Y,J,be){var Ue=Y.tag;if(Ue===5||Ue===6)Y=Y.stateNode,J?gt(be,Y,J):Yt(be,Y);else if(Ue!==4&&(Y=Y.child,Y!==null))for(aN(Y,J,be),Y=Y.sibling;Y!==null;)aN(Y,J,be),Y=Y.sibling}var jc=null,Xh=!1;function wf(Y,J,be){for(be=be.child;be!==null;)iN(Y,J,be),be=be.sibling}function iN(Y,J,be){if(qa&&typeof qa.onCommitFiberUnmount=="function")try{qa.onCommitFiberUnmount(np,be)}catch{}switch(be.tag){case 5:Qu||Bg(be,J);case 6:if($e){var Ue=jc,Je=Xh;jc=null,wf(Y,J,be),jc=Ue,Xh=Je,jc!==null&&(Xh?Jt(jc,be.stateNode):ht(jc,be.stateNode))}else wf(Y,J,be);break;case 18:$e&&jc!==null&&(Xh?Bs(jc,be.stateNode):Xt(jc,be.stateNode));break;case 4:$e?(Ue=jc,Je=Xh,jc=be.stateNode.containerInfo,Xh=!0,wf(Y,J,be),jc=Ue,Xh=Je):(ve&&(Ue=be.stateNode.containerInfo,Je=Er(Ue),Yr(Ue,Je)),wf(Y,J,be));break;case 0:case 11:case 14:case 15:if(!Qu&&(Ue=be.updateQueue,Ue!==null&&(Ue=Ue.lastEffect,Ue!==null))){Je=Ue=Ue.next;do{var yt=Je,ns=yt.destroy;yt=yt.tag,ns!==void 0&&(yt&2||yt&4)&&mb(be,J,ns),Je=Je.next}while(Je!==Ue)}wf(Y,J,be);break;case 1:if(!Qu&&(Bg(be,J),Ue=be.stateNode,typeof Ue.componentWillUnmount=="function"))try{Ue.props=be.memoizedProps,Ue.state=be.memoizedState,Ue.componentWillUnmount()}catch(ur){ja(be,J,ur)}wf(Y,J,be);break;case 21:wf(Y,J,be);break;case 22:be.mode&1?(Qu=(Ue=Qu)||be.memoizedState!==null,wf(Y,J,be),Qu=Ue):wf(Y,J,be);break;default:wf(Y,J,be)}}function oN(Y){var J=Y.updateQueue;if(J!==null){Y.updateQueue=null;var be=Y.stateNode;be===null&&(be=Y.stateNode=new _D),J.forEach(function(Ue){var Je=wb.bind(null,Y,Ue);be.has(Ue)||(be.add(Ue),Ue.then(Je,Je))})}}function $m(Y,J){var be=J.deletions;if(be!==null)for(var Ue=0;Ue";case Rv:return":has("+(jf(Y)||"")+")";case cy:return'[role="'+Y.value+'"]';case Ug:return'"'+Y.value+'"';case Yp:return'[data-testname="'+Y.value+'"]';default:throw Error(l(365))}}function cN(Y,J){var be=[];Y=[Y,0];for(var Ue=0;UeJe&&(Je=ns),Ue&=~yt}if(Ue=Je,Ue=Xo()-Ue,Ue=(120>Ue?120:480>Ue?480:1080>Ue?1080:1920>Ue?1920:3e3>Ue?3e3:4320>Ue?4320:1960*Vw(Ue/1960))-Ue,10Y?16:Y,$x===null)var Ue=!1;else{if(Y=$x,$x=null,vb=0,uo&6)throw Error(l(331));var Je=uo;for(uo|=4,Pa=Y.current;Pa!==null;){var yt=Pa,ns=yt.child;if(Pa.flags&16){var ur=yt.deletions;if(ur!==null){for(var Hr=0;HrXo()-yb?qx(Y,0):Ov|=be),kh(Y,J)}function Zw(Y,J){J===0&&(Y.mode&1?(J=qh,qh<<=1,!(qh&130023424)&&(qh=4194304)):J=1);var be=Ju();Y=Jr(Y,J),Y!==null&&(rp(Y,J,be),kh(Y,be))}function mN(Y){var J=Y.memoizedState,be=0;J!==null&&(be=J.retryLane),Zw(Y,be)}function wb(Y,J){var be=0;switch(Y.tag){case 13:var Ue=Y.stateNode,Je=Y.memoizedState;Je!==null&&(be=Je.retryLane);break;case 19:Ue=Y.stateNode;break;default:throw Error(l(314))}Ue!==null&&Ue.delete(J),Zw(Y,be)}var fN;fN=function(Y,J,be){if(Y!==null)if(Y.memoizedProps!==J.pendingProps||Qa.current)Zh=!0;else{if(!(Y.lanes&be)&&!(J.flags&128))return Zh=!1,Ow(Y,J,be);Zh=!!(Y.flags&131072)}else Zh=!1,na&&J.flags&1048576&&It(J,J1,J.index);switch(J.lanes=0,J.tag){case 2:var Ue=J.type;Pv(Y,J),Y=J.pendingProps;var Je=Gi(J,zi.current);Ed(J,be),Je=jw(null,J,Ue,Y,Je,be);var yt=ab();return J.flags|=1,typeof Je=="object"&&Je!==null&&typeof Je.render=="function"&&Je.$$typeof===void 0?(J.tag=1,J.memoizedState=null,J.updateQueue=null,Qn(Ue)?(yt=!0,Zo(J)):yt=!1,J.memoizedState=Je.state!==null&&Je.state!==void 0?Je.state:null,Xn(J),Je.updater=Tv,J.stateNode=Je,Je._reactInternals=J,iy(J,Ue,Y,be),J=Dw(null,J,Ue,!0,yt,be)):(J.tag=0,na&&yt&&ar(J),wh(null,J,Je,be),J=J.child),J;case 16:Ue=J.elementType;e:{switch(Pv(Y,J),Y=J.pendingProps,Je=Ue._init,Ue=Je(Ue._payload),J.type=Ue,Je=J.tag=gr(Ue),Y=hp(Ue,Y),Je){case 0:J=T4(null,J,Ue,Y,be);break e;case 1:J=tN(null,J,Ue,Y,be);break e;case 11:J=S4(null,J,Ue,Y,be);break e;case 14:J=Av(null,J,Ue,hp(Ue.type,Y),be);break e}throw Error(l(306,Ue,""))}return J;case 0:return Ue=J.type,Je=J.pendingProps,Je=J.elementType===Ue?Je:hp(Ue,Je),T4(Y,J,Ue,Je,be);case 1:return Ue=J.type,Je=J.pendingProps,Je=J.elementType===Ue?Je:hp(Ue,Je),tN(Y,J,Ue,Je,be);case 3:e:{if(lb(J),Y===null)throw Error(l(387));Ue=J.pendingProps,yt=J.memoizedState,Je=yt.element,Om(Y,J),bv(J,Ue,null,be);var ns=J.memoizedState;if(Ue=ns.element,Qe&&yt.isDehydrated)if(yt={element:Ue,isDehydrated:!1,cache:ns.cache,pendingSuspenseBoundaries:ns.pendingSuspenseBoundaries,transitions:ns.transitions},J.updateQueue.baseState=yt,J.memoizedState=yt,J.flags&256){Je=Yh(Error(l(423)),J),J=Mv(Y,J,Ue,be,Je);break e}else if(Ue!==Je){Je=Yh(Error(l(424)),J),J=Mv(Y,J,Ue,be,Je);break e}else for(Qe&&(Vr=Re(J.stateNode.containerInfo),Sn=J,na=!0,ri=null,Va=!1),be=xM(J,null,Ue,be),J.child=be;be;)be.flags=be.flags&-3|4096,be=be.sibling;else{if(wi(),Ue===Je){J=_f(Y,J,be);break e}wh(Y,J,Ue,be)}J=J.child}return J;case 5:return _w(J),Y===null&&Cu(J),Ue=J.type,Je=J.pendingProps,yt=Y!==null?Y.memoizedProps:null,ns=Je.children,Me(Ue,Je)?ns=null:yt!==null&&Me(Ue,yt)&&(J.flags|=32),bM(Y,J),wh(Y,J,ns,be),J.child;case 6:return Y===null&&Cu(J),null;case 13:return _M(Y,J,be);case 4:return wc(J,J.stateNode.containerInfo),Ue=J.pendingProps,Y===null?J.child=Il(J,null,Ue,be):wh(Y,J,Ue,be),J.child;case 11:return Ue=J.type,Je=J.pendingProps,Je=J.elementType===Ue?Je:hp(Ue,Je),S4(Y,J,Ue,Je,be);case 7:return wh(Y,J,J.pendingProps,be),J.child;case 8:return wh(Y,J,J.pendingProps.children,be),J.child;case 12:return wh(Y,J,J.pendingProps.children,be),J.child;case 10:e:{if(Ue=J.type._context,Je=J.pendingProps,yt=J.memoizedProps,ns=Je.value,sb(J,Ue,ns),yt!==null)if(Mm(yt.value,ns)){if(yt.children===Je.children&&!Qa.current){J=_f(Y,J,be);break e}}else for(yt=J.child,yt!==null&&(yt.return=J);yt!==null;){var ur=yt.dependencies;if(ur!==null){ns=yt.child;for(var Hr=ur.firstContext;Hr!==null;){if(Hr.context===Ue){if(yt.tag===1){Hr=Wh(-1,be&-be),Hr.tag=2;var Ln=yt.updateQueue;if(Ln!==null){Ln=Ln.shared;var La=Ln.pending;La===null?Hr.next=Hr:(Hr.next=La.next,La.next=Hr),Ln.pending=Hr}}yt.lanes|=be,Hr=yt.alternate,Hr!==null&&(Hr.lanes|=be),Rm(yt.return,be,J),ur.lanes|=be;break}Hr=Hr.next}}else if(yt.tag===10)ns=yt.type===J.type?null:yt.child;else if(yt.tag===18){if(ns=yt.return,ns===null)throw Error(l(341));ns.lanes|=be,ur=ns.alternate,ur!==null&&(ur.lanes|=be),Rm(ns,be,J),ns=yt.sibling}else ns=yt.child;if(ns!==null)ns.return=yt;else for(ns=yt;ns!==null;){if(ns===J){ns=null;break}if(yt=ns.sibling,yt!==null){yt.return=ns.return,ns=yt;break}ns=ns.return}yt=ns}wh(Y,J,Je.children,be),J=J.child}return J;case 9:return Je=J.type,Ue=J.pendingProps.children,Ed(J,be),Je=gf(Je),Ue=Ue(Je),J.flags|=1,wh(Y,J,Ue,be),J.child;case 14:return Ue=J.type,Je=hp(Ue,J.pendingProps),Je=hp(Ue.type,Je),Av(Y,J,Ue,Je,be);case 15:return C4(Y,J,J.type,J.pendingProps,be);case 17:return Ue=J.type,Je=J.pendingProps,Je=J.elementType===Ue?Je:hp(Ue,Je),Pv(Y,J),J.tag=1,Qn(Ue)?(Y=!0,Zo(J)):Y=!1,Ed(J,be),ny(J,Ue,Je),iy(J,Ue,Je,be),Dw(null,J,Ue,!0,Y,be);case 19:return db(Y,J,be);case 22:return vM(Y,J,be)}throw Error(l(156,J.tag))};function pN(Y,J){return Hh(Y,J)}function zv(Y,J,be,Ue){this.tag=Y,this.key=be,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=Ue,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Id(Y,J,be,Ue){return new zv(Y,J,be,Ue)}function yr(Y){return Y=Y.prototype,!(!Y||!Y.isReactComponent)}function gr(Y){if(typeof Y=="function")return yr(Y)?1:0;if(Y!=null){if(Y=Y.$$typeof,Y===_)return 11;if(Y===N)return 14}return 2}function Sf(Y,J){var be=Y.alternate;return be===null?(be=Id(Y.tag,J,Y.key,Y.mode),be.elementType=Y.elementType,be.type=Y.type,be.stateNode=Y.stateNode,be.alternate=Y,Y.alternate=be):(be.pendingProps=J,be.type=Y.type,be.flags=0,be.subtreeFlags=0,be.deletions=null),be.flags=Y.flags&14680064,be.childLanes=Y.childLanes,be.lanes=Y.lanes,be.child=Y.child,be.memoizedProps=Y.memoizedProps,be.memoizedState=Y.memoizedState,be.updateQueue=Y.updateQueue,J=Y.dependencies,be.dependencies=J===null?null:{lanes:J.lanes,firstContext:J.firstContext},be.sibling=Y.sibling,be.index=Y.index,be.ref=Y.ref,be}function Io(Y,J,be,Ue,Je,yt){var ns=2;if(Ue=Y,typeof Y=="function")yr(Y)&&(ns=1);else if(typeof Y=="string")ns=5;else e:switch(Y){case u:return as(be.children,Je,yt,J);case m:ns=8,Je|=8;break;case f:return Y=Id(12,be,J,Je|2),Y.elementType=f,Y.lanes=yt,Y;case b:return Y=Id(13,be,J,Je),Y.elementType=b,Y.lanes=yt,Y;case j:return Y=Id(19,be,J,Je),Y.elementType=j,Y.lanes=yt,Y;case A:return Xw(be,Je,yt,J);default:if(typeof Y=="object"&&Y!==null)switch(Y.$$typeof){case x:ns=10;break e;case y:ns=9;break e;case _:ns=11;break e;case N:ns=14;break e;case C:ns=16,Ue=null;break e}throw Error(l(130,Y==null?Y:typeof Y,""))}return J=Id(ns,be,J,Je),J.elementType=Y,J.type=Ue,J.lanes=yt,J}function as(Y,J,be,Ue){return Y=Id(7,Y,Ue,J),Y.lanes=be,Y}function Xw(Y,J,be,Ue){return Y=Id(22,Y,Ue,J),Y.elementType=A,Y.lanes=be,Y.stateNode={isHidden:!1},Y}function jb(Y,J,be){return Y=Id(6,Y,null,J),Y.lanes=be,Y}function Qw(Y,J,be){return J=Id(4,Y.children!==null?Y.children:[],Y.key,J),J.lanes=be,J.stateNode={containerInfo:Y.containerInfo,pendingChildren:null,implementation:Y.implementation},J}function xN(Y,J,be,Ue,Je){this.tag=J,this.containerInfo=Y,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Ve,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Y0(0),this.expirationTimes=Y0(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Y0(0),this.identifierPrefix=Ue,this.onRecoverableError=Je,Qe&&(this.mutableSourceEagerHydrationData=null)}function F4(Y,J,be,Ue,Je,yt,ns,ur,Hr){return Y=new xN(Y,J,be,ur,Hr),J===1?(J=1,yt===!0&&(J|=8)):J=0,yt=Id(3,null,null,J),Y.current=yt,yt.stateNode=Y,yt.memoizedState={element:Ue,isDehydrated:be,cache:null,transitions:null,pendingSuspenseBoundaries:null},Xn(yt),Y}function z4(Y){if(!Y)return Fi;Y=Y._reactInternals;e:{if(O(Y)!==Y||Y.tag!==1)throw Error(l(170));var J=Y;do{switch(J.tag){case 3:J=J.stateNode.context;break e;case 1:if(Qn(J.type)){J=J.stateNode.__reactInternalMemoizedMergedChildContext;break e}}J=J.return}while(J!==null);throw Error(l(171))}if(Y.tag===1){var be=Y.type;if(Qn(be))return Ji(Y,be,J)}return J}function Bv(Y){var J=Y._reactInternals;if(J===void 0)throw typeof Y.render=="function"?Error(l(188)):(Y=Object.keys(Y).join(","),Error(l(268,Y)));return Y=Z(J),Y===null?null:Y.stateNode}function B4(Y,J){if(Y=Y.memoizedState,Y!==null&&Y.dehydrated!==null){var be=Y.retryLane;Y.retryLane=be!==0&&be=Ln&&yt>=ro&&Je<=La&&ns<=ga){Y.splice(J,1);break}else if(Ue!==Ln||be.width!==Hr.width||gans){if(!(yt!==ro||be.height!==Hr.height||LaJe)){Ln>Ue&&(Hr.width+=Ln-Ue,Hr.x=Ue),Layt&&(Hr.height+=ro-yt,Hr.y=yt),gabe&&(be=ns)),ns ")+` No matching component was found for: `)+Y.join(" > ")}return null},r.getPublicRootInstance=function(Y){if(Y=Y.current,!Y.child)return null;switch(Y.child.tag){case 5:return ne(Y.child.stateNode);default:return Y.child.stateNode}},r.injectIntoDevTools=function(Y){if(Y={bundleType:Y.bundleType,version:Y.version,rendererPackageName:Y.rendererPackageName,rendererConfig:Y.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:AM,findFiberByHostInstance:Y.findFiberByHostInstance||yN,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")Y=!1;else{var J=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(J.isDisabled||!J.supportsFiber)Y=!0;else{try{np=J.inject(Y),qa=J}catch{}Y=!!J.checkDCE}}return Y},r.isAlreadyRendering=function(){return!1},r.observeVisibleRects=function(Y,J,be,Ue){if(!qe)throw Error(l(363));Y=dN(Y,J);var Je=St(Y,be,Ue).disconnect;return{disconnect:function(){Je()}}},r.registerMutableSourceForHydration=function(Y,J){var be=J._getVersion;be=be(J._source),Y.mutableSourceEagerHydrationData==null?Y.mutableSourceEagerHydrationData=[J,be]:Y.mutableSourceEagerHydrationData.push(J,be)},r.runWithPriority=function(Y,J){var be=co;try{return co=Y,J()}finally{co=be}},r.shouldError=function(){return null},r.shouldSuspend=function(){return!1},r.updateContainer=function(Y,J,be,Ue){var Je=J.current,yt=Ju(),ns=Ux(Je);return be=z4(be),J.context===null?J.context=be:J.pendingContext=be,J=Wh(yt,ns),J.payload={element:Y},Ue=Ue===void 0?null:Ue,Ue!==null&&(J.callback=Ue),Y=Cn(Je,J,ns),Y!==null&&(Um(Y,Je,ns,yt),ty(Y,Je,ns)),ns},r};Cmt.exports=qhs;var Vhs=Cmt.exports;const Hhs=gl(Vhs);var Tmt={exports:{}},nM={};/** * @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. */nM.ConcurrentRoot=1;nM.ContinuousEventPriority=4;nM.DefaultEventPriority=16;nM.DiscreteEventPriority=1;nM.IdleEventPriority=536870912;nM.LegacyRoot=0;Tmt.exports=nM;var Emt=Tmt.exports;const H$e={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let G$e=!1,W$e=!1;const MAe=".react-konva-event",Ghs=`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 `,Whs=`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 `,Khs={};function i0e(s,t,r=Khs){if(!G$e&&"zIndex"in t&&(console.warn(Whs),G$e=!0),!W$e&&t.draggable){var n=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;n&&!a&&(console.warn(Ghs),W$e=!0)}for(var i in r)if(!H$e[i]){var l=i.slice(0,2)==="on",o=r[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,r[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var u=t._useStrictMode,m={},f=!1;const x={};for(var i in t)if(!H$e[i]){var l=i.slice(0,2)==="on",y=r[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]&&(x[c]=t[i])}!l&&(t[i]!==r[i]||u&&t[i]!==s.getAttr(i))&&(f=!0,m[i]=t[i])}f&&(s.setAttrs(m),h4(s));for(var c in x)s.on(c+MAe,x[c])}function h4(s){if(!ra.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const Amt={},Yhs={};MA.Node.prototype._applyProps=i0e;function Zhs(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),h4(s)}function Xhs(s,t,r){let n=MA[s];n||(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`),n=MA.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 n(a);return i0e(c,i),c}function Qhs(s,t,r){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function Jhs(s,t,r){return!1}function ems(s){return s}function tms(){return null}function sms(){return null}function rms(s,t,r,n){return Yhs}function nms(){}function ams(s){}function ims(s,t){return!1}function oms(){return Amt}function lms(){return Amt}const cms=setTimeout,dms=clearTimeout,ums=-1;function hms(s,t){return!1}const mms=!1,fms=!0,pms=!0;function xms(s,t){t.parent===s?t.moveToTop():s.add(t),h4(s)}function gms(s,t){t.parent===s?t.moveToTop():s.add(t),h4(s)}function Mmt(s,t,r){t._remove(),s.add(t),t.setZIndex(r.getZIndex()),h4(s)}function yms(s,t,r){Mmt(s,t,r)}function vms(s,t){t.destroy(),t.off(MAe),h4(s)}function bms(s,t){t.destroy(),t.off(MAe),h4(s)}function _ms(s,t,r){console.error(`Text components are not yet supported in ReactKonva. You text is: "${r}"`)}function wms(s,t,r){}function jms(s,t,r,n,a){i0e(s,a,n)}function Nms(s){s.hide(),h4(s)}function kms(s){}function Sms(s,t){(t.visible==null||t.visible)&&s.show()}function Cms(s,t){}function Tms(s){}function Ems(){}const Ams=()=>Emt.DefaultEventPriority,Mms=Object.freeze(Object.defineProperty({__proto__:null,appendChild:xms,appendChildToContainer:gms,appendInitialChild:Zhs,cancelTimeout:dms,clearContainer:Tms,commitMount:wms,commitTextUpdate:_ms,commitUpdate:jms,createInstance:Xhs,createTextInstance:Qhs,detachDeletedInstance:Ems,finalizeInitialChildren:Jhs,getChildHostContext:lms,getCurrentEventPriority:Ams,getPublicInstance:ems,getRootHostContext:oms,hideInstance:Nms,hideTextInstance:kms,idlePriority:QO.unstable_IdlePriority,insertBefore:Mmt,insertInContainerBefore:yms,isPrimaryRenderer:mms,noTimeout:ums,now:QO.unstable_now,prepareForCommit:tms,preparePortalMount:sms,prepareUpdate:rms,removeChild:vms,removeChildFromContainer:bms,resetAfterCommit:nms,resetTextContent:ams,run:QO.unstable_runWithPriority,scheduleTimeout:cms,shouldDeprioritizeSubtree:ims,shouldSetTextContent:hms,supportsMutation:pms,unhideInstance:Sms,unhideTextInstance:Cms,warnsIfNotActing:fms},Symbol.toStringTag,{value:"Module"}));var Ims=Object.defineProperty,Pms=Object.defineProperties,Lms=Object.getOwnPropertyDescriptors,K$e=Object.getOwnPropertySymbols,Dms=Object.prototype.hasOwnProperty,Rms=Object.prototype.propertyIsEnumerable,Y$e=(s,t,r)=>t in s?Ims(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,Z$e=(s,t)=>{for(var r in t||(t={}))Dms.call(t,r)&&Y$e(s,r,t[r]);if(K$e)for(var r of K$e(t))Rms.call(t,r)&&Y$e(s,r,t[r]);return s},Oms=(s,t)=>Pms(s,Lms(t)),X$e,Q$e;typeof window<"u"&&((X$e=window.document)!=null&&X$e.createElement||((Q$e=window.navigator)==null?void 0:Q$e.product)==="ReactNative")?k.useLayoutEffect:k.useEffect;function Imt(s,t,r){if(!s)return;if(r(s)===!0)return s;let n=s.child;for(;n;){const a=Imt(n,t,r);if(a)return a;n=n.sibling}}function Pmt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const J$e=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=J$e;return}return J$e.apply(this,arguments)};const IAe=Pmt(k.createContext(null));class Lmt extends k.Component{render(){return k.createElement(IAe.Provider,{value:this._reactInternals},this.props.children)}}function Fms(){const s=k.useContext(IAe);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=k.useId();return k.useMemo(()=>{for(const n of[s,s==null?void 0:s.alternate]){if(!n)continue;const a=Imt(n,!1,i=>{let l=i.memoizedState;for(;l;){if(l.memoizedState===t)return!0;l=l.next}});if(a)return a}},[s,t])}function zms(){const s=Fms(),[t]=k.useState(()=>new Map);t.clear();let r=s;for(;r;){if(r.type&&typeof r.type=="object"){const a=r.type._context===void 0&&r.type.Provider===r.type?r.type:r.type._context;a&&a!==IAe&&!t.has(a)&&t.set(a,k.useContext(Pmt(a)))}r=r.return}return t}function Bms(){const s=zms();return k.useMemo(()=>Array.from(s.keys()).reduce((t,r)=>n=>k.createElement(t,null,k.createElement(r.Provider,Oms(Z$e({},n),{value:s.get(r)}))),t=>k.createElement(Lmt,Z$e({},t))),[s])}function $ms(s){const t=Ct.useRef({});return Ct.useLayoutEffect(()=>{t.current=s}),Ct.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const Ums=s=>{const t=Ct.useRef(null),r=Ct.useRef(null),n=Ct.useRef(null),a=$ms(s),i=Bms(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Ct.useLayoutEffect(()=>(r.current=new MA.Stage({width:s.width,height:s.height,container:t.current}),l(r.current),n.current=qO.createContainer(r.current,Emt.LegacyRoot,!1,null),qO.updateContainer(Ct.createElement(i,{},s.children),n.current),()=>{MA.isBrowser&&(l(null),qO.updateContainer(null,n.current,null),r.current.destroy())}),[]),Ct.useLayoutEffect(()=>{l(r.current),i0e(r.current,s,a),qO.updateContainer(Ct.createElement(i,{},s.children),n.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})},qms="Layer",$k="Group",qb="Rect",CI="Image",I6="Text",dar="Transformer",qO=Hhs(Mms);qO.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Ct.version,rendererPackageName:"react-konva"});const Vms=Ct.forwardRef((s,t)=>Ct.createElement(Lmt,{},Ct.createElement(Ums,{...s,forwardedRef:t})));function Hms({imageUrl:s,preset:t,barStyleId:r,overrides:n,maxDisplayWidth:a=720,stageRef:i}){const l=k.useRef(null),[o,c]=k.useState(null),[d,u]=k.useState(null),[m,f]=k.useState(null),x=(t==null?void 0:t.headshot_url)??"",y=(t==null?void 0:t.brokerage_logo_url)??"";k.useEffect(()=>{if(!s){c(null);return}const Q=new window.Image;Q.crossOrigin="anonymous",Q.onload=()=>c(Q),Q.onerror=()=>c(null),Q.src=s},[s]),k.useEffect(()=>{if(!x){u(null);return}const Q=new window.Image;Q.crossOrigin="anonymous",Q.onload=()=>u(Q),Q.onerror=()=>u(null),Q.src=x},[x]),k.useEffect(()=>{if(!y){f(null);return}const Q=new window.Image;Q.crossOrigin="anonymous",Q.onload=()=>f(Q),Q.onerror=()=>f(null),Q.src=y},[y]);const _=xds(r),b=(o==null?void 0:o.naturalWidth)??1080,j=(o==null?void 0:o.naturalHeight)??1080,N=k.useMemo(()=>Math.min(1,a/b),[b,a]),C=b*N,A=j*N,E=(n==null?void 0:n.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",D=(n==null?void 0:n.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",R=(n==null?void 0:n.display_name)??(t==null?void 0:t.display_name)??"",F=(n==null?void 0:n.phone)??(t==null?void 0:t.phone)??"",O=(n==null?void 0:n.email)??(t==null?void 0:t.email)??"",B=(n==null?void 0:n.tagline)??(t==null?void 0:t.tagline)??"",K=new Set((n==null?void 0:n.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),Z=Q=>_.fields.includes(Q)&&!K.has(Q);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(Vms,{ref:Q=>{l.current=Q,i&&(i.current=Q)},width:C,height:A,scaleX:N,scaleY:N,children:e.jsxs(qms,{children:[o&&e.jsx(CI,{image:o,width:b,height:j,listening:!1}),!o&&e.jsx(qb,{x:0,y:0,width:b,height:j,fill:"#e2e8f0"}),e.jsx(Gms,{style:_,canvasW:b,canvasH:j,brandColor:E,accentColor:D,name:R,phone:F,email:O,tagline:B,headshot:d,logo:m,hidden:K,has:Z})]})})})}function Gms({style:s,canvasW:t,canvasH:r,brandColor:n,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:m}){const f=r*s.heightRatio,x=f*.18,y=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":gds(n),_=y==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const b=s.position==="bottom"?r-f:0;return e.jsxs($k,{children:[e.jsx(qb,{x:0,y:b,width:t,height:f,fill:n}),e.jsx(qb,{x:0,y:s.position==="bottom"?b:f-4,width:t,height:4,fill:a}),e.jsx(Yq,{x,y:b+x,width:t-x*2,height:f-x*2,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:m,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const b=t*.42,j=f,N=t-b-r*.025,C=r-j-r*.025;return e.jsxs($k,{children:[e.jsx(qb,{x:N,y:C,width:b,height:j,fill:n,cornerRadius:j*.12,opacity:.92}),e.jsx(qb,{x:N,y:C+j-4,width:b,height:4,fill:a,cornerRadius:2}),e.jsx(Yq,{x:N+x,y:C+x,width:b-x*2,height:j-x*2,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:m,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const b=Math.max(t*.22,Math.min(t*.3,260)),j=b*.12;return e.jsxs($k,{children:[e.jsx(qb,{x:t-b,y:0,width:b,height:r,fill:n}),e.jsx(qb,{x:t-b,y:0,width:4,height:r,fill:a}),e.jsx(Yq,{x:t-b+j,y:r*.08,width:b-j*2,height:r*.84,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:m,circular:s.circularHeadshot,vertical:!0,railWidth:b})]})}return s.position==="letterbox"?e.jsxs($k,{children:[e.jsx(qb,{x:0,y:0,width:t,height:f,fill:"#0a0a0a"}),e.jsx(qb,{x:0,y:r-f,width:t,height:f,fill:"#0a0a0a"}),e.jsx(qb,{x:0,y:r-f,width:t,height:3,fill:a}),e.jsx(Yq,{x,y:r-f+x,width:t-x*2,height:f-x*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:m,circular:s.circularHeadshot}),u&&m("logo")&&e.jsx(CI,{image:u,x:t-x-f*.7,y:x,height:f-x*2,width:f*.7})]}):null}function Yq({x:s,y:t,width:r,height:n,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:m,has:f,circular:x,vertical:y,railWidth:_}){if(y){const Q=_??r,W=Math.min(r,Q*.7),te=Math.max(14,Q*.13),ne=Math.max(11,Q*.085),ae=Q*.08,ue=Q*.35;let me=t;const de=me;me+=W+ae;const fe=me,je=l.length>12?2:1;me+=te*1.15*je+ae*.5;const xe=me;f("phone")&&o&&(me+=ne*1.3+ae*.4);const Ee=me;f("email")&&c&&(me+=ne*1.3+ae*.4);const Me=me+ae*.5;return e.jsxs($k,{children:[f("headshot")&&u&&e.jsx($k,{clipFunc:x?Oe=>{Oe.beginPath(),Oe.arc(s+r/2,de+W/2,W/2,0,Math.PI*2),Oe.closePath()}:void 0,children:e.jsx(CI,{image:u,x:s+(r-W)/2,y:de,width:W,height:W})}),f("name")&&l&&e.jsx(I6,{text:l,x:s,y:fe,width:r,align:"center",fontSize:te,fontStyle:"bold",fill:a}),f("phone")&&o&&e.jsx(I6,{text:o,x:s,y:xe,width:r,align:"center",fontSize:ne,fill:i}),f("email")&&c&&e.jsx(I6,{text:c,x:s,y:Ee,width:r,align:"center",fontSize:ne,fill:i,ellipsis:!0,wrap:"none"}),f("logo")&&m&&e.jsx(CI,{image:m,x:s,y:Me,width:r,height:ue})]})}const b=n*.95,j=u&&f("headshot")?s+b+n*.18:s,N=r-(j-s)-(m&&f("logo")?n*1.6:0),C=Math.max(20,n*.34),A=Math.max(13,n*.22),E=n*.06,D=f("tagline")&&d?1:0,R=f("phone")&&o?1:0,F=f("email")&&c?1:0,O=1+D+(R||F?1:0),B=O*C+(O-1)*E;let Z=t+(n-B)/2;return e.jsxs($k,{children:[f("headshot")&&u&&e.jsx($k,{clipFunc:x?Q=>{Q.beginPath(),Q.arc(s+b/2,t+b/2,b/2,0,Math.PI*2),Q.closePath()}:void 0,children:e.jsx(CI,{image:u,x:s,y:t+(n-b)/2,width:b,height:b})}),f("name")&&l&&e.jsx(I6,{text:l,x:j,y:Z,width:N,fontSize:C,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(Z+=C+E,null),f("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(I6,{text:d,x:j,y:Z,width:N,fontSize:A*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(Z+=A*1.1+E,null)]}),R||F?e.jsx(I6,{text:[o,c].filter(Boolean).join(" • "),x:j,y:Z,width:N,fontSize:A,fill:i,ellipsis:!0,wrap:"none"}):null,f("logo")&&m&&e.jsx(CI,{image:m,x:s+r-n*1.4,y:t+(n-n*.8)/2,width:n*1.4,height:n*.8})]})}function Wms(){const{data:s}=OB(),t=(s==null?void 0:s.find(Z=>Z.is_default))??(s==null?void 0:s[0])??null,[r,n]=k.useState(void 0),a=(s==null?void 0:s.find(Z=>Z.id===r))??t,[i,l]=k.useState([]),[o,c]=k.useState(0),[d,u]=k.useState("minimal-stripe"),[m,f]=k.useState({}),[x,y]=k.useState(!1),_=k.useRef(null),[b,j]=k.useState(780),N=k.useRef(null),C=Z=>{if(N.current&&(N.current.disconnect(),N.current=null),!Z)return;const Q=()=>{const te=Z.clientWidth;te>0&&j(Math.min(780,te-16))};Q();const W=new ResizeObserver(Q);W.observe(Z),N.current=W};k.useEffect(()=>()=>{var Z;(Z=N.current)==null||Z.disconnect()},[]);const A=k.useRef(null),E=Z=>{if(!Z)return;const Q=[];Array.from(Z).forEach(W=>{W.type.startsWith("image/")&&Q.push({id:crypto.randomUUID(),url:URL.createObjectURL(W),file:W,name:W.name})}),l(W=>[...W,...Q])},D=Z=>{l(Q=>{const W=Q.find(te=>te.id===Z);return W&&URL.revokeObjectURL(W.url),Q.filter(te=>te.id!==Z)}),c(0)},R=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),F=Z=>{var ue;const[Q,W]=Z.split(","),te=((ue=Q.match(/:(.*?);/))==null?void 0:ue[1])??"image/jpeg",ne=atob(W),ae=new Uint8Array(ne.length);for(let me=0;me{var Z;if(A.current){y(!0);try{const Q=A.current,W=Q.toDataURL({pixelRatio:1/(Q.scaleX()||1),mimeType:"image/jpeg",quality:.95}),ne=`${((Z=i[o])==null?void 0:Z.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,ae=F(W),ue=URL.createObjectURL(ae);if(R)window.open(ue,"_blank")||(window.location.href=ue),he.success('Long-press the image and tap "Save to Photos"');else{const me=document.createElement("a");me.href=ue,me.download=ne,document.body.appendChild(me),me.click(),me.remove(),he.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(ue),6e4)}catch(Q){he.error(Q.message||"Export failed")}finally{y(!1)}}},B=async()=>{if(i.length){y(!0);try{const Z=new Wht,Q=i.length,W=o;for(let ae=0;aesetTimeout(je,600)),!A.current)continue;const ue=A.current,de=ue.toDataURL({pixelRatio:1/(ue.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],fe=i[ae].name.replace(/\.[^.]+$/,"")||`image-${ae+1}`;Z.file(`${fe}-branded.jpg`,de,{base64:!0})}c(W);const te=await Z.generateAsync({type:"blob"}),ne=document.createElement("a");ne.href=URL.createObjectURL(te),ne.download=`branded-images-${Date.now()}.zip`,ne.click(),URL.revokeObjectURL(ne.href),he.success(`${Q} images exported`)}catch(Z){he.error(Z.message||"Batch export failed")}finally{y(!1)}}},K=i[o];return e.jsx(ws,{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(Yo,{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(Vn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Aa,{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(q,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(Vn,{to:"/marketing-studio/brand-kit",children:[e.jsx(dl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(ke,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Pe,{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(q,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(Vn,{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(ke,{className:"overflow-hidden",children:e.jsxs(Pe,{className:"p-4",children:[K?e.jsx("div",{ref:C,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(Hms,{imageUrl:K.url,preset:a,barStyleId:d,overrides:m,maxDisplayWidth:b,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(zo,{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(q,{type:"button",children:[e.jsx(ka,{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(ke,{className:"overflow-hidden",children:e.jsx(Pe,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((Z,Q)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(Q),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${Q===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:()=>D(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($r,{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(Ys,{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(q,{variant:"outline",onClick:()=>{i.forEach(Z=>URL.revokeObjectURL(Z.url)),l([])},children:"Clear all"}),e.jsxs(q,{onClick:O,disabled:x||!K,children:[x?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(li,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(q,{onClick:B,disabled:x,children:[x?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(li,{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(ke,{className:"overflow-hidden",children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-base",children:"Brand preset"})}),e.jsx(Pe,{children:e.jsxs(Ds,{value:(a==null?void 0:a.id)??"",onValueChange:n,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Choose preset"})}),e.jsx(Ls,{children:s==null?void 0:s.map(Z=>e.jsxs(lt,{value:Z.id,children:[Z.name," ",Z.is_default?"(default)":""]},Z.id))})]})})]}),e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-base",children:"Bar style"})}),e.jsx(Pe,{children:e.jsx(yds,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-base",children:"Tweak this design"})}),e.jsx(Pe,{children:e.jsxs(ta,{defaultValue:"text",children:[e.jsxs(ea,{className:"grid grid-cols-2 w-full",children:[e.jsx(rs,{value:"text",children:"Text"}),e.jsx(rs,{value:"colors",children:"Colors"})]}),e.jsxs(fs,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Display name"}),e.jsx(Ne,{value:m.display_name??(a==null?void 0:a.display_name)??"",onChange:Z=>f({...m,display_name:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Phone"}),e.jsx(Ne,{value:m.phone??(a==null?void 0:a.phone)??"",onChange:Z=>f({...m,phone:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Email"}),e.jsx(Ne,{value:m.email??(a==null?void 0:a.email)??"",onChange:Z=>f({...m,email:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Tagline"}),e.jsx(Ne,{value:m.tagline??(a==null?void 0:a.tagline)??"",onChange:Z=>f({...m,tagline:Z.target.value})})]})]}),e.jsxs(fs,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Bar color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:m.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:Z=>f({...m,brand_color:Z.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(Ne,{value:m.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:Z=>f({...m,brand_color:Z.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Accent line"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:m.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:Z=>f({...m,accent_color:Z.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(Ne,{value:m.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:Z=>f({...m,accent_color:Z.target.value})})]})]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>f({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function Kms(s,t){if(s.match(/^[a-z]+:\/\//i))return s;if(s.match(/^\/\//))return window.location.protocol+s;if(s.match(/^[a-z]+:/i))return s;const r=document.implementation.createHTMLDocument(),n=r.createElement("base"),a=r.createElement("a");return r.head.appendChild(n),r.body.appendChild(a),t&&(n.href=t),a.href=s,a.href}const Yms=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function jS(s){const t=[];for(let r=0,n=s.length;rJg||s.height>Jg)&&(s.width>Jg&&s.height>Jg?s.width>s.height?(s.height*=Jg/s.width,s.width=Jg):(s.width*=Jg/s.height,s.height=Jg):s.width>Jg?(s.height*=Jg/s.width,s.width=Jg):(s.width*=Jg/s.height,s.height=Jg))}function Nfe(s){return new Promise((t,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{requestAnimationFrame(()=>t(n))})},n.onerror=r,n.crossOrigin="anonymous",n.decoding="async",n.src=s})}async function efs(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function tfs(s,t,r){const n="http://www.w3.org/2000/svg",a=document.createElementNS(n,"svg"),i=document.createElementNS(n,"foreignObject");return a.setAttribute("width",`${t}`),a.setAttribute("height",`${r}`),a.setAttribute("viewBox",`0 0 ${t} ${r}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),a.appendChild(i),i.appendChild(s),efs(a)}const wg=(s,t)=>{if(s instanceof t)return!0;const r=Object.getPrototypeOf(s);return r===null?!1:r.constructor.name===t.name||wg(r,t)};function sfs(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function rfs(s,t){return Dmt(t).map(r=>{const n=s.getPropertyValue(r),a=s.getPropertyPriority(r);return`${r}: ${n}${a?" !important":""};`}).join(" ")}function nfs(s,t,r,n){const a=`.${s}:${t}`,i=r.cssText?sfs(r):rfs(r,n);return document.createTextNode(`${a}{${i}}`)}function eUe(s,t,r,n){const a=window.getComputedStyle(s,r),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=Yms();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(nfs(l,r,a,n)),t.appendChild(o)}function afs(s,t,r){eUe(s,t,":before",r),eUe(s,t,":after",r)}const tUe="application/font-woff",sUe="image/jpeg",ifs={woff:tUe,woff2:tUe,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:sUe,jpeg:sUe,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function ofs(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function PAe(s){const t=ofs(s).toLowerCase();return ifs[t]||""}function lfs(s){return s.split(/,/)[1]}function ASe(s){return s.search(/^(data:)/)!==-1}function cfs(s,t){return`data:${t};base64,${s}`}async function Omt(s,t,r){const n=await fetch(s,t);if(n.status===404)throw new Error(`Resource "${n.url}" not found`);const a=await n.blob();return new Promise((i,l)=>{const o=new FileReader;o.onerror=l,o.onloadend=()=>{try{i(r({res:n,result:o.result}))}catch(c){l(c)}},o.readAsDataURL(a)})}const hwe={};function dfs(s,t,r){let n=s.replace(/\?.*/,"");return r&&(n=s),/ttf|otf|eot|woff2?/i.test(n)&&(n=n.replace(/.*\//,"")),t?`[${t}]${n}`:n}async function LAe(s,t,r){const n=dfs(s,t,r.includeQueryParams);if(hwe[n]!=null)return hwe[n];r.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await Omt(s,r.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),lfs(o)));a=cfs(i,t)}catch(i){a=r.imagePlaceholder||"";let l=`Failed to fetch resource: ${s}`;i&&(l=typeof i=="string"?i:i.message),l&&console.warn(l)}return hwe[n]=a,a}async function ufs(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):Nfe(t)}async function hfs(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 Nfe(o)}const r=s.poster,n=PAe(r),a=await LAe(r,n,t);return Nfe(a)}async function mfs(s,t){var r;try{if(!((r=s==null?void 0:s.contentDocument)===null||r===void 0)&&r.body)return await o0e(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function ffs(s,t){return wg(s,HTMLCanvasElement)?ufs(s):wg(s,HTMLVideoElement)?hfs(s,t):wg(s,HTMLIFrameElement)?mfs(s,t):s.cloneNode(Fmt(s))}const pfs=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",Fmt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function xfs(s,t,r){var n,a;if(Fmt(t))return t;let i=[];return pfs(s)&&s.assignedNodes?i=jS(s.assignedNodes()):wg(s,HTMLIFrameElement)&&(!((n=s.contentDocument)===null||n===void 0)&&n.body)?i=jS(s.contentDocument.body.childNodes):i=jS(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||wg(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>o0e(o,r)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function gfs(s,t,r){const n=t.style;if(!n)return;const a=window.getComputedStyle(s);a.cssText?(n.cssText=a.cssText,n.transformOrigin=a.transformOrigin):Dmt(r).forEach(i=>{let l=a.getPropertyValue(i);i==="font-size"&&l.endsWith("px")&&(l=`${Math.floor(parseFloat(l.substring(0,l.length-2)))-.1}px`),wg(s,HTMLIFrameElement)&&i==="display"&&l==="inline"&&(l="block"),i==="d"&&t.getAttribute("d")&&(l=`path(${t.getAttribute("d")})`),n.setProperty(i,l,a.getPropertyPriority(i))})}function yfs(s,t){wg(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),wg(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function vfs(s,t){if(wg(s,HTMLSelectElement)){const r=t,n=Array.from(r.children).find(a=>s.value===a.getAttribute("value"));n&&n.setAttribute("selected","")}}function bfs(s,t,r){return wg(t,Element)&&(gfs(s,t,r),afs(s,t,r),yfs(s,t),vfs(s,t)),t}async function _fs(s,t){const r=s.querySelectorAll?s.querySelectorAll("use"):[];if(r.length===0)return s;const n={};for(let i=0;iffs(n,t)).then(n=>xfs(s,n,t)).then(n=>bfs(s,n,t)).then(n=>_fs(n,t))}const zmt=/url\((['"]?)([^'"]+?)\1\)/g,wfs=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,jfs=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Nfs(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function kfs(s){const t=[];return s.replace(zmt,(r,n,a)=>(t.push(a),r)),t.filter(r=>!ASe(r))}async function Sfs(s,t,r,n,a){try{const i=r?Kms(t,r):t,l=PAe(t);let o;return a||(o=await LAe(i,l,n)),s.replace(Nfs(t),`$1${o}$3`)}catch{}return s}function Cfs(s,{preferredFontFormat:t}){return t?s.replace(jfs,r=>{for(;;){const[n,,a]=wfs.exec(r)||[];if(!a)return"";if(a===t)return`src: ${n};`}}):s}function Bmt(s){return s.search(zmt)!==-1}async function $mt(s,t,r){if(!Bmt(s))return s;const n=Cfs(s,r);return kfs(n).reduce((i,l)=>i.then(o=>Sfs(o,l,t,r)),Promise.resolve(n))}async function L6(s,t,r){var n;const a=(n=t.style)===null||n===void 0?void 0:n.getPropertyValue(s);if(a){const i=await $mt(a,null,r);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function Tfs(s,t){await L6("background",s,t)||await L6("background-image",s,t),await L6("mask",s,t)||await L6("-webkit-mask",s,t)||await L6("mask-image",s,t)||await L6("-webkit-mask-image",s,t)}async function Efs(s,t){const r=wg(s,HTMLImageElement);if(!(r&&!ASe(s.src))&&!(wg(s,SVGImageElement)&&!ASe(s.href.baseVal)))return;const n=r?s.src:s.href.baseVal,a=await LAe(n,PAe(n),t);await new Promise((i,l)=>{s.onload=i,s.onerror=t.onImageErrorHandler?(...c)=>{try{i(t.onImageErrorHandler(...c))}catch(d){l(d)}}:l;const o=s;o.decode&&(o.decode=i),o.loading==="lazy"&&(o.loading="eager"),r?(s.srcset="",s.src=a):s.href.baseVal=a})}async function Afs(s,t){const n=jS(s.childNodes).map(a=>Umt(a,t));await Promise.all(n).then(()=>s)}async function Umt(s,t){wg(s,Element)&&(await Tfs(s,t),await Efs(s,t),await Afs(s,t))}function Mfs(s,t){const{style:r}=s;t.backgroundColor&&(r.backgroundColor=t.backgroundColor),t.width&&(r.width=`${t.width}px`),t.height&&(r.height=`${t.height}px`);const n=t.style;return n!=null&&Object.keys(n).forEach(a=>{r[a]=n[a]}),s}const rUe={};async function nUe(s){let t=rUe[s];if(t!=null)return t;const n=await(await fetch(s)).text();return t={url:s,cssText:n},rUe[s]=t,t}async function aUe(s,t){let r=s.cssText;const n=/url\(["']?([^"')]+)["']?\)/g,i=(r.match(/url\([^)]+\)/g)||[]).map(async l=>{let o=l.replace(n,"$1");return o.startsWith("https://")||(o=new URL(o,s.url).href),Omt(o,t.fetchRequestInit,({result:c})=>(r=r.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>r)}function iUe(s){if(s==null)return[];const t=[],r=/(\/\*[\s\S]*?\*\/)/gi;let n=s.replace(r,"");const a=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const c=a.exec(n);if(c===null)break;t.push(c[0])}n=n.replace(a,"");const i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,l="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",o=new RegExp(l,"gi");for(;;){let c=i.exec(n);if(c===null){if(c=o.exec(n),c===null)break;i.lastIndex=o.lastIndex}else o.lastIndex=i.lastIndex;t.push(c[0])}return t}async function Ifs(s,t){const r=[],n=[];return s.forEach(a=>{if("cssRules"in a)try{jS(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=nUe(c).then(u=>aUe(u,t)).then(u=>iUe(u).forEach(m=>{try{a.insertRule(m,m.startsWith("@import")?o+=1:a.cssRules.length)}catch(f){console.error("Error inserting rule from remote css",{rule:m,error:f})}})).catch(u=>{console.error("Error loading remote css",u.toString())});n.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&n.push(nUe(a.href).then(o=>aUe(o,t)).then(o=>iUe(o).forEach(c=>{l.insertRule(c,l.cssRules.length)})).catch(o=>{console.error("Error loading remote stylesheet",o)})),console.error("Error inlining remote css file",i)}}),Promise.all(n).then(()=>(s.forEach(a=>{if("cssRules"in a)try{jS(a.cssRules||[]).forEach(i=>{r.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),r))}function Pfs(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>Bmt(t.style.getPropertyValue("src")))}async function Lfs(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const r=jS(s.ownerDocument.styleSheets),n=await Ifs(r,t);return Pfs(n)}function qmt(s){return s.trim().replace(/["']/g,"")}function Dfs(s){const t=new Set;function r(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach(i=>{t.add(qmt(i))}),Array.from(n.children).forEach(i=>{i instanceof HTMLElement&&r(i)})}return r(s),t}async function Rfs(s,t){const r=await Lfs(s,t),n=Dfs(s);return(await Promise.all(r.filter(i=>n.has(qmt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return $mt(i.cssText,l,t)}))).join(` `)}async function Ofs(s,t){const r=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Rfs(s,t);if(r){const n=document.createElement("style"),a=document.createTextNode(r);n.appendChild(a),s.firstChild?s.insertBefore(n,s.firstChild):s.appendChild(n)}}async function Ffs(s,t={}){const{width:r,height:n}=Rmt(s,t),a=await o0e(s,t,!0);return await Ofs(a,t),await Umt(a,t),Mfs(a,t),await tfs(a,r,n)}async function zfs(s,t={}){const{width:r,height:n}=Rmt(s,t),a=await Ffs(s,t),i=await Nfe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||Qms(),d=t.canvasWidth||r,u=t.canvasHeight||n;return l.width=d*c,l.height=u*c,t.skipAutoScale||Jms(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 DAe(s,t={}){return(await zfs(s,t)).toDataURL()}const jL=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),l0e={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},Uk={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},Bfs=({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})]})]}),RAe=Ct.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var m;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=l0e[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:jL(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",jL(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(Bfs,{branding:n,dim:l})]})]})]})});RAe.displayName="LuxuryDarkTemplate";const $fs=({branding:s,dim:t,accentColor:r})=>!(s!=null&&s.enabled)||!s.agentName?null:e.jsxs("div",{style:{borderTop:"2px solid #E5E7EB",paddingTop:t.w*.025,display:"flex",alignItems:"center",justifyContent:"center",gap:t.w*.025},children:[s.agentPhotoUrl&&e.jsx("img",{src:s.agentPhotoUrl,alt:"",crossOrigin:"anonymous",style:{width:t.w*.14,height:t.w*.14,borderRadius:"50%",objectFit:"cover",border:`3px solid ${r}`,flexShrink:0}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:t.w*.042,fontWeight:800,color:"#1A1A1A"},children:s.agentName}),s.brokerage&&e.jsx("div",{style:{fontSize:t.w*.028,color:"#6B7280",marginTop:t.w*.005},children:s.brokerage})]})]}),OAe=Ct.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var x;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(x=s.photos)==null?void 0:x[a],d=l0e[t],u=r==="instagram-story",m=r==="facebook-post",f=t==="just-sold"?"#7C3AED":t==="open-house"?"#2563EB":t==="price-drop"?"#DC2626":"#059669";return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Helvetica Neue', Arial, sans-serif",color:"#1A1A1A",background:"#FFFFFF",display:"flex",flexDirection:m?"row":"column"},children:[e.jsxs("div",{style:{width:m?"55%":"100%",height:m?"100%":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:f,color:"#FFFFFF",padding:`${l.w*.012}px ${l.w*.04}px`,fontSize:l.w*.026,fontWeight:800,letterSpacing:"0.15em"},children:d})]}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05},children:[e.jsx("div",{style:{fontSize:l.w*(m?.055:.065),fontWeight:800,lineHeight:1.1,color:f,marginBottom:l.w*.012},children:jL(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:`${f}10`,border:`2px solid ${f}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:f,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx($fs,{branding:n,dim:l,accentColor:f})]})]})});OAe.displayName="ModernCleanTemplate";const Ufs=({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})]})]}),FAe=Ct.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var f;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(f=s.photos)==null?void 0:f[a],d=l0e[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)"},m=[s.bedrooms?`${s.bedrooms} BD`:null,s.bathrooms?`${s.bathrooms} BA`:null,s.sqft?`${s.sqft.toLocaleString()} SF`:null].filter(Boolean).join(" | ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Arial Black', 'Helvetica Neue', sans-serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.4)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",padding:l.w*.05},children:[e.jsx("div",{style:{background: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:jL(s.price)}),e.jsx("div",{style:{fontSize:l.w*.028,fontWeight:700,marginBottom:l.w*.005},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.8,marginBottom:l.w*.015},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"inline-block",background:"rgba(255,255,255,0.15)",borderRadius:l.w*.008,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,letterSpacing:"0.08em"},children:m}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.015,background: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(Ufs,{branding:n,dim:l})]})]})]})});FAe.displayName="BoldColorfulTemplate";const qfs=({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})]})]}),zAe=Ct.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var m;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=l0e[t],u=r==="instagram-story";return e.jsx("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#1A1A1A",background:"#F5F0EB"},children:e.jsxs("div",{style:{display:"flex",flexDirection: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:jL(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",jL(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(qfs,{branding:n,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"}})]})]})})});zAe.displayName="EditorialTemplate";const Vfs=[{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:"📉"}],oUe=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(gu,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(gu,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(mh,{className:"h-4 w-4"})}],Hfs=[{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:"📰"}],lUe={"luxury-dark":RAe,"modern-clean":OAe,"bold-colorful":FAe,editorial:zAe},mwe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function Gfs(s){var l;const[t,r]=s.split(","),n=((l=t.match(/:(.*?);/))==null?void 0:l[1])||"image/png",a=atob(r),i=new Uint8Array(a.length);for(let o=0;oze.is_default))??(s==null?void 0:s[0])??null,[r,n]=k.useState(void 0),a=(s==null?void 0:s.find(ze=>ze.id===r))??t,i=xa(),[l,o]=k.useState("mine"),[c,d]=k.useState(""),[u,m]=k.useState("address"),[f,x]=k.useState(!1),[y,_]=k.useState([]),[b,j]=k.useState(null),[N,C]=k.useState(0),[A,E]=k.useState("just-listed"),[D,R]=k.useState(["instagram-square"]),[F,O]=k.useState("luxury-dark"),[B,K]=k.useState(!0),[Z,Q]=k.useState(!1),[W,te]=k.useState([]),[ne,ae]=k.useState("search"),ue=k.useRef({}),{data:me=[],isLoading:de}=pt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:ze,error:Ve}=await U.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Ve)throw Ve;return(ze||[]).map(Le=>{const $e=(Le.listing_photos||[]).slice().sort((Qe,we)=>(we.is_primary?1:0)-(Qe.is_primary?1:0)||(Qe.sort_order??0)-(we.sort_order??0)).map(Qe=>Qe.photo_url).filter(Boolean),ve=String(Le.status||"");return{mlsNumber:Le.id,address:Le.property_address||"",city:Le.city||"",state:Le.state||"",zip:"",price:Number(Le.price||0),status:ve,bedrooms:Number(Le.bedrooms||0),bathrooms:Number(Le.bathrooms||0),sqft:Number(Le.square_footage||0),lotSize:"",yearBuilt:Le.year_built??null,propertyType:Le.property_type||"",description:Le.description||"",photos:$e,listDate:Le.created_at,soldDate:ve.toLowerCase().includes("sold")?Le.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),fe=k.useMemo(()=>!B||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[B,a]),je=async()=>{if(c.trim()){x(!0),_([]);try{const{data:ze,error:Ve}=await U.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Ve)throw Ve;if(ze!=null&&ze.error)throw new Error(ze.error);_((ze==null?void 0:ze.listings)||[]),((ze==null?void 0:ze.listings)||[]).length===0&&he.info("No listings found. Try a different search.")}catch(ze){he.error(ze.message||"Search failed")}finally{x(!1)}}},xe=ze=>{var Ve;j(ze),C(0),ae("customize"),ze.soldDate||(Ve=ze.status)!=null&&Ve.toLowerCase().includes("sold")?E("just-sold"):E("just-listed")},Ee=ze=>R(Ve=>Ve.includes(ze)?Ve.filter(Le=>Le!==ze):[...Ve,ze]),Me=b?{listing:b,postType:A,format:"instagram-square",branding:fe,selectedPhotoIndex:N}:null,Oe=k.useCallback(async()=>{if(!(!b||D.length===0)){Q(!0),te([]),ae("generate");try{await new Promise(Ve=>setTimeout(Ve,600));const ze=[];for(const Ve of D){const Le=`${F}-${Ve}`,$e=ue.current[Le];if(!$e)continue;const ve=Uk[Ve],Qe=await DAe($e,{width:ve.width,height:ve.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});ze.push({format:Ve,url:Qe})}te(ze),he.success(`Generated ${ze.length} design${ze.length>1?"s":""}!`)}catch(ze){he.error(ze.message||"Generation failed")}finally{Q(!1)}}},[b,D,F]),Ie=(ze,Ve)=>{const Le=`${((b==null?void 0:b.address)||"listing").replace(/\s+/g,"-")}-${A}-${Ve}.png`;try{const $e=Gfs(ze),ve=URL.createObjectURL($e);if(Wfs)window.open(ve,"_blank"),he.message("Long-press the image to save to Photos");else{const Qe=document.createElement("a");Qe.href=ve,Qe.download=Le,document.body.appendChild(Qe),Qe.click(),document.body.removeChild(Qe)}setTimeout(()=>URL.revokeObjectURL(ve),6e4)}catch{const $e=document.createElement("a");$e.href=ze,$e.download=Le,$e.click()}};return k.useEffect(()=>{!r&&t&&n(t.id)},[t,r]),e.jsx(ws,{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(Yo,{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(q,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(Vn,{to:"/marketing-studio",children:[e.jsx(Aa,{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(Xe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(Ir,{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(ce,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(Ds,{value:r,onValueChange:n,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Default"})}),e.jsx(Ls,{children:s.map(ze=>e.jsxs(lt,{value:ze.id,children:[ze.name,ze.is_default?" (default)":""]},ze.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:()=>ae("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ne==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(_n,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>b&&ae("customize"),disabled:!b,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ne==="customize"?"bg-primary text-primary-foreground":b?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Ir,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ne==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(li,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),ne==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ta,{value:l,onValueChange:ze=>o(ze),children:e.jsxs(ea,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(rs,{value:"mine",children:[e.jsx(Pn,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(rs,{value:"mls",children:[e.jsx(_n,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:de?e.jsx(ke,{children:e.jsx(Pe,{className:"py-12 flex items-center justify-center",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):me.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-10 text-center space-y-2",children:[e.jsx(Pn,{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(q,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(Vn,{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:[me.length," listing",me.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:me.map((ze,Ve)=>{var Le;return e.jsx(ke,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>xe(ze),children:e.jsx(Pe,{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:(Le=ze.photos)!=null&&Le[0]?e.jsx("img",{src:ze.photos[0],alt:ze.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(Pn,{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:ze.price>0?mwe(ze.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ze.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ze.city,ze.state?`, ${ze.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ze.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(e2,{className:"h-3 w-3"})," ",ze.bedrooms]}),ze.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(of,{className:"h-3 w-3"})," ",ze.bathrooms]}),ze.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(zE,{className:"h-3 w-3"})," ",ze.sqft.toLocaleString()]})]}),ze.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:ze.status})})]})]})})},ze.mlsNumber||Ve)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(_n,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(Ur,{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(Pe,{className:"space-y-3",children:[e.jsx(ta,{value:u,onValueChange:ze=>m(ze),children:e.jsxs(ea,{children:[e.jsxs(rs,{value:"address",children:[e.jsx(Ma,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(rs,{value:"mls",children:[e.jsx(Fh,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(Ne,{value:c,onChange:ze=>d(ze.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:ze=>ze.key==="Enter"&&je()}),e.jsxs(q,{onClick:je,disabled:f||!c.trim(),className:"sm:w-auto w-full",children:[f?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(_n,{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((ze,Ve)=>{var Le;return e.jsx(ke,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>xe(ze),children:e.jsx(Pe,{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:(Le=ze.photos)!=null&&Le[0]?e.jsx("img",{src:ze.photos[0],alt:ze.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(Pn,{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:mwe(ze.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ze.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ze.city,", ",ze.state," ",ze.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ze.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(e2,{className:"h-3 w-3"})," ",ze.bedrooms]}),ze.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(of,{className:"h-3 w-3"})," ",ze.bathrooms]}),ze.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(zE,{className:"h-3 w-3"})," ",ze.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[ze.mlsNumber&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:ze.mlsNumber}),ze.status&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:ze.status})]})]})]})})},ze.mlsNumber||Ve)})})]})]})]}),ne==="customize"&&b&&Me&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(ke,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Pt,{className:"pb-3",children:e.jsx(Dt,{className:"text-base",children:"Selected listing"})}),e.jsxs(Pe,{className:"space-y-3",children:[b.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:b.photos[N],alt:"",className:"w-full h-full object-cover"})}),b.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(q,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>C(ze=>Math.max(0,ze-1)),disabled:N===0,children:e.jsx(jl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[N+1," of ",b.photos.length]}),e.jsx(q,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>C(ze=>Math.min(b.photos.length-1,ze+1)),disabled:N===b.photos.length-1,children:e.jsx(Ia,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:mwe(b.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.city,", ",b.state," ",b.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[b.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:b.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),b.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:b.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),b.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:b.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(q,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ae("search"),j(null)},children:[e.jsx(ev,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(ke,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ir,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Ur,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Pe,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(dl,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Hfs.map(ze=>e.jsxs("button",{onClick:()=>O(ze.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${F===ze.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:ze.preview}),e.jsx("span",{className:"text-sm font-medium",children:ze.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:ze.description})]},ze.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Vfs.map(ze=>e.jsxs("button",{onClick:()=>E(ze.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===ze.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:ze.icon})," ",e.jsx("span",{className:"truncate",children:ze.label})]},ze.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:oUe.map(ze=>e.jsxs("button",{onClick:()=>Ee(ze.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${D.includes(ze.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[ze.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:ze.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:ze.dimensions})]})]},ze.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ce,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(qi,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(Rr,{checked:B,onCheckedChange:K})]}),B&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(Vn,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),B&&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(ce,{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*(Uk[D[0]||"instagram-square"].height/Uk[D[0]||"instagram-square"].width)},children:(()=>{const ze=lUe[F],Ve=D[0]||"instagram-square";return e.jsx(ze,{...Me,format:Ve})})()})})]}),e.jsx(q,{onClick:Oe,disabled:D.length===0||Z,size:"lg",className:"w-full gap-2",children:Z?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-5 w-5"})," Generate ",D.length," design",D.length>1?"s":""]})})]})]})]}),ne==="generate"&&e.jsxs("div",{className:"space-y-4",children:[Z&&e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ls,{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(q,{variant:"outline",size:"sm",onClick:()=>ae("customize"),children:[e.jsx(ev,{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((ze,Ve)=>{const Le=oUe.find($e=>$e.value===ze.format);return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:ze.url,alt:"",className:"w-full rounded"})}),e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Le==null?void 0:Le.icon,e.jsx("span",{className:"text-sm font-medium",children:Le==null?void 0:Le.label})]}),e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:Le==null?void 0:Le.dimensions})]}),e.jsxs(q,{size:"sm",className:"w-full gap-1.5",onClick:()=>Ie(ze.url,ze.format),children:[e.jsx(li,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ve)})})]})]}),ne==="generate"&&b&&Me&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:D.map(ze=>{const Ve=lUe[F],Le=Uk[ze];return e.jsx("div",{style:{width:Le.width,height:Le.height},children:e.jsx(Ve,{ref:$e=>{ue.current[`${F}-${ze}`]=$e},...Me,format:ze})},`${F}-${ze}`)})})]})})}var Vmt="Toggle",BAe=k.forwardRef((s,t)=>{const{pressed:r,defaultPressed:n,onPressedChange:a,...i}=s,[l,o]=df({prop:r,onChange:a,defaultProp:n??!1,caller:Vmt});return e.jsx(Yn.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:dn(s.onClick,()=>{s.disabled||o(!l)})})});BAe.displayName=Vmt;var Hmt=BAe,m4="ToggleGroup",[Gmt,uar]=bu(m4,[XS]),Wmt=XS(),$Ae=Ct.forwardRef((s,t)=>{const{type:r,...n}=s;if(r==="single"){const a=n;return e.jsx(Yfs,{...a,ref:t})}if(r==="multiple"){const a=n;return e.jsx(Zfs,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${m4}\``)});$Ae.displayName=m4;var[Kmt,Ymt]=Gmt(m4),Yfs=Ct.forwardRef((s,t)=>{const{value:r,defaultValue:n,onValueChange:a=()=>{},...i}=s,[l,o]=df({prop:r,defaultProp:n??"",onChange:a,caller:m4});return e.jsx(Kmt,{scope:s.__scopeToggleGroup,type:"single",value:Ct.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Ct.useCallback(()=>o(""),[o]),children:e.jsx(Zmt,{...i,ref:t})})}),Zfs=Ct.forwardRef((s,t)=>{const{value:r,defaultValue:n,onValueChange:a=()=>{},...i}=s,[l,o]=df({prop:r,defaultProp:n??[],onChange:a,caller:m4}),c=Ct.useCallback(u=>o((m=[])=>[...m,u]),[o]),d=Ct.useCallback(u=>o((m=[])=>m.filter(f=>f!==u)),[o]);return e.jsx(Kmt,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(Zmt,{...i,ref:t})})});$Ae.displayName=m4;var[Xfs,Qfs]=Gmt(m4),Zmt=Ct.forwardRef((s,t)=>{const{__scopeToggleGroup:r,disabled:n=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=Wmt(r),u=ZS(l),m={role:"group",dir:u,...c};return e.jsx(Xfs,{scope:r,rovingFocus:a,disabled:n,children:a?e.jsx(Fxe,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(Yn.div,{...m,ref:t})}):e.jsx(Yn.div,{...m,ref:t})})}),kfe="ToggleGroupItem",Xmt=Ct.forwardRef((s,t)=>{const r=Ymt(kfe,s.__scopeToggleGroup),n=Qfs(kfe,s.__scopeToggleGroup),a=Wmt(s.__scopeToggleGroup),i=r.value.includes(s.value),l=n.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Ct.useRef(null);return n.rovingFocus?e.jsx(zxe,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(cUe,{...o,ref:t})}):e.jsx(cUe,{...o,ref:t})});Xmt.displayName=kfe;var cUe=Ct.forwardRef((s,t)=>{const{__scopeToggleGroup:r,value:n,...a}=s,i=Ymt(kfe,r),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(BAe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(n):i.onItemDeactivate(n)}})}),Qmt=$Ae,Jmt=Xmt;const eft=WA("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"}}),Jfs=k.forwardRef(({className:s,variant:t,size:r,...n},a)=>e.jsx(Hmt,{ref:a,className:zt(eft({variant:t,size:r,className:s})),...n}));Jfs.displayName=Hmt.displayName;const tft=k.createContext({size:"default",variant:"default"}),SP=k.forwardRef(({className:s,variant:t,size:r,children:n,...a},i)=>e.jsx(Qmt,{ref:i,className:zt("flex items-center justify-center gap-1",s),...a,children:e.jsx(tft.Provider,{value:{variant:t,size:r},children:n})}));SP.displayName=Qmt.displayName;const tA=k.forwardRef(({className:s,children:t,variant:r,size:n,...a},i)=>{const l=k.useContext(tft);return e.jsx(Jmt,{ref:i,className:zt(eft({variant:l.variant||r,size:l.size||n}),s),...a,children:t})});tA.displayName=Jmt.displayName;const eps=[{id:"meet",label:"Meet Your Agent",icon:qi,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:u2,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:wo,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:o2,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:fh,description:"Personal philosophy, mantra, or rallying call."}],fwe={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"}},tps=[{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."}],dUe={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 sps(){const{data:s}=dds(),{data:t}=OB(),[r,n]=k.useState(void 0),a=k.useMemo(()=>(t==null?void 0:t.find(y=>y.id===r))??s??null,[t,r,s]),[i,l]=k.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...dUe.meet}),o=y=>l(_=>({..._,...y})),c=y=>l(_=>({..._,template:y,...dUe[y]})),d=k.useRef(null),[u,m]=k.useState(!1),f=async()=>{if(!d.current)return;m(!0);const y=d.current,_=y.style.transform;try{y.style.transform="none",await new Promise(N=>requestAnimationFrame(()=>N(null)));const b=await DAe(y,{cacheBust:!0,pixelRatio:2,width:y.offsetWidth,height:y.offsetHeight,backgroundColor:"#ffffff"}),j=document.createElement("a");j.href=b,j.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(j),j.click(),j.remove(),he.success("Downloaded to your device")}catch(b){he.error((b==null?void 0:b.message)||"Export failed")}finally{y.style.transform=_,m(!1)}},x=fwe[i.aspect];return e.jsx(ws,{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(Yo,{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(Vn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Aa,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ir,{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(q,{variant:"outline",asChild:!0,children:e.jsxs(Vn,{to:"/marketing-studio/brand-kit",children:[e.jsx(dl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(q,{onClick:f,disabled:u,children:[e.jsx(li,{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(ke,{children:e.jsxs(Pe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:eps.map(y=>{const _=y.icon,b=i.template===y.id;return e.jsxs("button",{onClick:()=>c(y.id),className:`text-left rounded-lg border p-3 transition-all ${b?"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(ce,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(SP,{type:"single",value:i.style,onValueChange:y=>y&&o({style:y}),className:"grid grid-cols-2 gap-1",children:tps.map(y=>e.jsx(tA,{value:y.id,className:"text-xs h-9",children:y.label},y.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(SP,{type:"single",value:i.aspect,onValueChange:y=>y&&o({aspect:y}),className:"grid grid-cols-3 gap-1",children:Object.keys(fwe).map(y=>e.jsx(tA,{value:y,className:"text-xs h-9",children:fwe[y].label},y))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(Ds,{value:r??(s==null?void 0:s.id)??"",onValueChange:n,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Choose preset"})}),e.jsx(Ls,{children:t.map(y=>e.jsx(lt,{value:y.id,children:y.name},y.id))})]})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsx(ce,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(pr,{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(ce,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(Ne,{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(ce,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(pr,{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(ce,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"Rating"}),e.jsx(SP,{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(tA,{value:String(y),className:"text-xs h-9",children:[y,"★"]},y))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(Ne,{id:"badge",value:i.badgeText,onChange:y=>o({badgeText:y.target.value})})]})]})})]}),e.jsx(rps,{aspect:x,canvasRef:d,children:e.jsx(nps,{form:i,preset:a,width:x.w,height:x.h})})]})]})})}function rps({aspect:s,canvasRef:t,children:r}){const n=k.useRef(null),[a,i]=k.useState(.5);return k.useEffect(()=>{const l=n.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:n,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:r})})}),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 nps({form:s,preset:t,width:r,height:n}){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)||"",m=(t==null?void 0:t.tagline)||"",f=(t==null?void 0:t.website_url)||"",x={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:m,website:f,width:r,height:n};return s.style==="editorial"?e.jsx(aps,{...x}):s.style==="bold"?e.jsx(ips,{...x}):s.style==="luxury"?e.jsx(lps,{...x}):e.jsx(ops,{...x})}function sft({name:s,phone:t,email:r,website:n,color:a}){const i=[t,r,n].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 c0e({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((r,n)=>e.jsx(fa,{size:28,fill:n1.5;return e.jsxs("div",{style:{width:m,height:f,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:r},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:m-128,height:x?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:n,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(c0e,{rating:t.rating,color:n}),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(sft,{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 ips(s){const{form:t,brandColor:r,accentColor:n,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:u,height:m}=s;return e.jsxs("div",{style:{width:u,height:m,position:"relative",overflow:"hidden",fontFamily:"Inter, system-ui, sans-serif",background:`linear-gradient(135deg, ${r} 0%, ${cps(r,-20)} 100%)`,color:"#fff"},children:[e.jsx("div",{style:{position:"absolute",top:-200,right:-200,width:700,height:700,borderRadius:"50%",background:n,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:n,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 ${n}`},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:n},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:n,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(c0e,{rating:t.rating,color:n}),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:n,marginBottom:20,width:80}}),e.jsx(sft,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function ops(s){const{form:t,brandColor:r,accentColor:n,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:u,height:m}=s;return e.jsxs("div",{style:{width:u,height:m,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:n}}),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:r,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(c0e,{rating:t.rating,color:n})}),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 lps(s){const{form:t,accentColor:r,headshot:n,logo:a,name:i,phone:l,email:o,website:c,width:d,height:u}=s,m=r||"#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 ${m}`,opacity:.6}}),e.jsx("div",{style:{position:"absolute",inset:50,border:`1px solid ${m}`,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:m},children:t.badgeText}),e.jsx("div",{style:{width:40,height:1,background:m,margin:"20px auto 0"}})]}),n&&(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 ${m}`},children:e.jsx("img",{src:n,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:n&&(t.template==="meet"||t.template==="milestone")?680:280,textAlign:"center"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:100,lineHeight:.6,color:m},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:m,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(c0e,{rating:t.rating,color:m})}),t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:16,marginTop:16,color:m,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:m,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 cps(s,t){const r=s.replace("#",""),n=parseInt(r.length===3?r.split("").map(o=>o+o).join(""):r,16);let a=(n>>16)+Math.round(t/100*255),i=(n>>8&255)+Math.round(t/100*255),l=(n&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 dps=()=>{const{swagId:s}=xo(),{user:t}=Cs(),{toast:r}=Ba(),n=is(),{trackEngagement:a}=M8(),[i,l]=k.useState(""),{data:o,isLoading:c}=pt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:j,error:N}=await U.from("social_swag").select("*").eq("id",s).single();if(N)throw N;const{data:C}=await U.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...j,links:C||[]}},enabled:!!s});k.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=pt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:j,error:N}=await U.from("social_swag_likes").select("*").eq("swag_id",s);if(N)throw N;return j},enabled:!!s}),{data:u=[]}=pt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:j,error:N}=await U.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(N)throw N;const C=[...new Set(j.map(D=>D.user_id))],{data:A}=await U.from("profiles").select("id, name").in("id",C),E=new Map((A==null?void 0:A.map(D=>[D.id,D.name]))||[]);return j.map(D=>({...D,user_name:E.get(D.user_id)||"Unknown User"}))},enabled:!!s}),m=Mt({mutationFn:async j=>{const{error:N}=await U.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:j});if(N)throw N},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),r({title:"Comment added!"})},onError:j=>{r({title:"Error adding comment",description:j.message,variant:"destructive"})}}),f=Mt({mutationFn:async j=>{const{error:N}=await U.from("social_swag_comments").delete().eq("id",j);if(N)throw N},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",s]}),r({title:"Comment deleted"})}}),x=Mt({mutationFn:async()=>{const j=d.find(N=>N.user_id===(t==null?void 0:t.id));if(j){const{error:N}=await U.from("social_swag_likes").delete().eq("id",j.id);if(N)throw N}else{const{error:N}=await U.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(N)throw N}},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-likes",s]})}}),y=d.some(j=>j.user_id===(t==null?void 0:t.id)),_=j=>j.split(" ").map(N=>N[0]).join("").toUpperCase().slice(0,2),b=j=>{j.preventDefault(),!(!i.trim()||!t)&&m.mutate(i.trim())};return c?e.jsx(ws,{title:"Social Swag",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):o?e.jsx(ws,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(q,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Vn,{to:"/social-swag",children:[e.jsx(Aa,{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(L8,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(q,{variant:y?"default":"outline",className:"gap-2 w-fit",onClick:()=>x.mutate(),disabled:!t||x.isPending,children:[e.jsx(wm,{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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(tl,{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(q,{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(un,{className:"h-4 w-4 text-muted-foreground"})]},j.id))})]})}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(gc,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(pr,{placeholder:"Add a comment...",value:i,onChange:j=>l(j.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(q,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||m.isPending,children:e.jsx(hn,{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(ke,{children:e.jsx(Pe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):u.map(j=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Kn,{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:Nl(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(j.id),children:e.jsx(zr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(ws,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(tl,{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(q,{asChild:!0,className:"mt-4",children:e.jsx(Vn,{to:"/social-swag",children:"Back to Social Swag"})})]})})},ups=({categories:s,privateGroups:t,selectedFilter:r,onFilterChange:n,onlineUsers:a})=>{const[i,l]=k.useState(!0),[o,c]=k.useState(!0),[d,u]=k.useState(!0),m=f=>f.split(" ").map(x=>x[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(q,{variant:r==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>n("all"),children:[e.jsx(sS,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(E0,{open:i,onOpenChange:l,children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{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(Co,{className:"h-4 w-4"}):e.jsx(Ia,{className:"h-4 w-4"})]})}),e.jsx(M0,{className:"space-y-1 pl-2",children:s.map(f=>e.jsxs(q,{variant:r===f.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>n(f.id),children:[e.jsx("span",{className:"mr-2",children:f.icon||"📂"}),e.jsx("span",{className:"truncate",children:f.name})]},f.id))})]}),t.length>0&&e.jsxs(E0,{open:o,onOpenChange:c,children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{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(Co,{className:"h-4 w-4"}):e.jsx(Ia,{className:"h-4 w-4"})]})}),e.jsx(M0,{className:"space-y-1 pl-2",children:t.map(f=>e.jsxs(q,{variant:r===`group:${f.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>n(`group:${f.id}`),children:[e.jsx("span",{className:"mr-2",children:f.icon||"🔒"}),e.jsx("span",{className:"truncate",children:f.name})]},f.id))})]}),e.jsxs(E0,{open:d,onOpenChange:u,children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{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(Dr,{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(Co,{className:"h-4 w-4"}):e.jsx(Ia,{className:"h-4 w-4"})]})}),e.jsx(M0,{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(f=>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(Wn,{className:"h-7 w-7",children:[e.jsx(Xa,{src:f.avatarUrl}),e.jsx(Kn,{className:"text-xs",children:m(f.name)})]}),e.jsx(Rh,{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:f.name})]},f.id))})]})]})})})},hps=({categories:s,privateGroups:t,selectedFilter:r,onFilterChange:n,onlineUsers:a})=>{const[i,l]=k.useState(!1),o=d=>d.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2),c=()=>{if(r==="all")return"All Posts";if(r.startsWith("group:")){const u=r.replace("group:",""),m=t.find(f=>f.id===u);return m?`🔒 ${m.name}`:"Private Group"}const d=s.find(u=>u.id===r);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(Co,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(Sd,{className:"w-56 bg-background border",children:[e.jsxs(ti,{onClick:()=>n("all"),children:[e.jsx(sS,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(z_,{}),e.jsx(S9,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(ti,{onClick:()=>n(d.id),children:[e.jsx("span",{className:"mr-2",children:d.icon||"📂"}),d.name]},d.id)),t.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(z_,{}),e.jsxs(S9,{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(ti,{onClick:()=>n(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(sw,{open:i,onOpenChange:l,children:[e.jsx(mge,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Dr,{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(U1,{children:[e.jsx(rw,{children:e.jsxs(nw,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(ui,{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(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:d.avatarUrl}),e.jsx(Kn,{children:o(d.name)})]}),e.jsx(Rh,{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 pwe,d0e="HoverCard",[rft,har]=bu(d0e,[Q_]),u0e=Q_(),[mps,UAe]=rft(d0e),nft=s=>{const{__scopeHoverCard:t,children:r,open:n,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=u0e(t),d=k.useRef(0),u=k.useRef(0),m=k.useRef(!1),f=k.useRef(!1),[x,y]=df({prop:n,defaultProp:a??!1,onChange:i,caller:d0e}),_=k.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>y(!0),l)},[l,y]),b=k.useCallback(()=>{clearTimeout(d.current),!m.current&&!f.current&&(u.current=window.setTimeout(()=>y(!1),o))},[o,y]),j=k.useCallback(()=>y(!1),[y]);return k.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(mps,{scope:t,open:x,onOpenChange:y,onOpen:_,onClose:b,onDismiss:j,hasSelectionRef:m,isPointerDownOnContentRef:f,children:e.jsx(nB,{...c,children:r})})};nft.displayName=d0e;var aft="HoverCardTrigger",ift=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,...n}=s,a=UAe(aft,r),i=u0e(r);return e.jsx(x8,{asChild:!0,...i,children:e.jsx(Yn.a,{"data-state":a.open?"open":"closed",...n,ref:t,onPointerEnter:dn(s.onPointerEnter,Cfe(a.onOpen)),onPointerLeave:dn(s.onPointerLeave,Cfe(a.onClose)),onFocus:dn(s.onFocus,a.onOpen),onBlur:dn(s.onBlur,a.onClose),onTouchStart:dn(s.onTouchStart,l=>l.preventDefault())})})});ift.displayName=aft;var fps="HoverCardPortal",[mar,pps]=rft(fps,{forceMount:void 0}),Sfe="HoverCardContent",oft=k.forwardRef((s,t)=>{const r=pps(Sfe,s.__scopeHoverCard),{forceMount:n=r.forceMount,...a}=s,i=UAe(Sfe,s.__scopeHoverCard);return e.jsx(yh,{present:n||i.open,children:e.jsx(xps,{"data-state":i.open?"open":"closed",...a,onPointerEnter:dn(s.onPointerEnter,Cfe(i.onOpen)),onPointerLeave:dn(s.onPointerLeave,Cfe(i.onClose)),ref:t})})});oft.displayName=Sfe;var xps=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=UAe(Sfe,r),d=u0e(r),u=k.useRef(null),m=_i(t,u),[f,x]=k.useState(!1);return k.useEffect(()=>{if(f){const y=document.body;return pwe=y.style.userSelect||y.style.webkitUserSelect,y.style.userSelect="none",y.style.webkitUserSelect="none",()=>{y.style.userSelect=pwe,y.style.webkitUserSelect=pwe}}},[f]),k.useEffect(()=>{if(u.current){const y=()=>{x(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var b;((b=document.getSelection())==null?void 0:b.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]),k.useEffect(()=>{u.current&&vps(u.current).forEach(_=>_.setAttribute("tabindex","-1"))}),e.jsx(WS,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:dn(i,y=>{y.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(aB,{...d,...o,onPointerDown:dn(o.onPointerDown,y=>{y.currentTarget.contains(y.target)&&x(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:m,style:{...o.style,userSelect:f?"text":void 0,WebkitUserSelect:f?"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)"}})})}),gps="HoverCardArrow",yps=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,...n}=s,a=u0e(r);return e.jsx(iB,{...a,...n,ref:t})});yps.displayName=gps;function Cfe(s){return t=>t.pointerType==="touch"?void 0:s()}function vps(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;r.nextNode();)t.push(r.currentNode);return t}var bps=nft,_ps=ift,lft=oft;const wps=bps,jps=_ps,cft=k.forwardRef(({className:s,align:t="center",sideOffset:r=4,...n},a)=>e.jsx(lft,{ref:a,align:t,sideOffset:r,className:zt("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n}));cft.displayName=lft.displayName;const Nps=[{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"}],kps=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),dft=({reactions:s,children:t})=>{if(s.length===0)return e.jsx(e.Fragment,{children:t});const r={};return s.forEach(n=>{r[n.reaction_type]||(r[n.reaction_type]=[]),r[n.reaction_type].push(n)}),e.jsxs(wps,{openDelay:200,closeDelay:100,children:[e.jsx(jps,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(cft,{className:"w-64 p-3 bg-popover border shadow-lg z-50",side:"top",align:"start",children:e.jsx("div",{className:"space-y-3",children:Object.entries(r).map(([n,a])=>{const i=Nps.find(l=>l.type===n);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-lg",children:i==null?void 0:i.emoji}),e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[i==null?void 0:i.label," (",a.length,")"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[a.slice(0,10).map(l=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Wn,{className:"h-6 w-6",children:[e.jsx(Xa,{src:l.user_avatar||void 0}),e.jsx(Kn,{className:"text-[10px]",children:kps(l.user_name||"U")})]}),e.jsx("span",{className:"text-sm text-foreground truncate",children:l.user_name||"Unknown User"})]},l.id)),a.length>10&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",a.length-10," more"]})]})]},n)})})})]})};function Sps({images:s,initialIndex:t=0,open:r,onOpenChange:n}){const[a,i]=k.useState(t),[l,o]=k.useState(!1);k.useEffect(()=>{r&&(i(t),o(!1))},[r,t]);const c=()=>{i(f=>f>0?f-1:s.length-1),o(!1)},d=()=>{i(f=>f{r&&(f.key==="ArrowLeft"&&c(),f.key==="ArrowRight"&&d(),f.key==="Escape"&&n(!1))},[r,s.length]);k.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const m=s[a];return e.jsx(vs,{open:r,onOpenChange:n,children:e.jsxs(ys,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>n(!1),children:e.jsx($r,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(q,{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(jl,{className:"h-8 w-8"})}),e.jsx(q,{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(Ia,{className:"h-8 w-8"})})]}),s.length>1&&e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-50 text-white text-sm bg-black/50 px-3 py-1 rounded-full",children:[a+1," / ",s.length]}),(m==null?void 0:m.type)==="image"&&e.jsx(q,{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(hP,{className:"h-5 w-5"}):e.jsx(mS,{className:"h-5 w-5"})}),e.jsx("div",{className:zt("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(m==null?void 0:m.type)==="image"&&o(!l),children:(m==null?void 0:m.type)==="video"?e.jsx("video",{src:m.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:f=>f.stopPropagation()}):e.jsx("img",{src:m==null?void 0:m.url,alt:"",className:zt("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((f,x)=>e.jsx("button",{onClick:()=>{i(x),o(!1)},className:zt("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===x?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:f.type==="video"?e.jsx("video",{src:f.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:f.url,alt:"",className:"w-full h-full object-cover"})},x))})]})})}const Zq=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],Cps=({commentId:s,reactions:t,currentUserId:r})=>{var d,u;const n=is(),[a,i]=k.useState(!1),l=t.find(m=>m.user_id===r),o=Mt({mutationFn:async m=>{l?l.reaction_type===m?await U.from("community_comment_reactions").delete().eq("id",l.id):await U.from("community_comment_reactions").update({reaction_type:m}).eq("id",l.id):await U.from("community_comment_reactions").insert({comment_id:s,user_id:r,reaction_type:m})},onSuccess:()=>{n.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(m=>{c[m.reaction_type]=(c[m.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(dft,{reactions:t,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("div",{className:"flex -space-x-0.5",children:Object.keys(c).slice(0,2).map(m=>{var f;return e.jsx("span",{className:"text-sm",children:(f=Zq.find(x=>x.type===m))==null?void 0:f.emoji},m)})}),e.jsx("span",{children:t.length})]})}),r&&e.jsxs(sl,{open:a,onOpenChange:i,children:[e.jsx(rl,{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=Zq.find(m=>m.type===l.reaction_type))==null?void 0:d.emoji," ",(u=Zq.find(m=>m.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yi,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(Ko,{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:Zq.map(m=>e.jsx("button",{onClick:()=>o.mutate(m.type),className:"text-xl hover:scale-125 transition-transform p-1",title:m.label,children:m.emoji},m.type))})})]})]})};function qAe({content:s,className:t}){const r=/([@#])\[([^\]]+)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)/g,n=[];let a=0,i,l=0;for(;(i=r.exec(s))!==null;){if(i.index>a&&n.push(s.substring(a,i.index)),i[1]){const o=i[1],c=i[2],d=i[3],u=o==="#";n.push(e.jsx(Vn,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:zt("font-medium hover:underline",u?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:m=>m.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 m=new URL(c);u=m.hostname+(m.pathname!=="/"?m.pathname.slice(0,20)+(m.pathname.length>20?"...":""):"")}catch{u=c.length>40?c.slice(0,40)+"...":c}n.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:m=>m.stopPropagation(),children:u},`url-${l++}`)),d&&n.push(d)}a=i.index+i[0].length}return ae.jsx(k.Fragment,{children:o},c))})}function Tfe({value:s,onChange:t,placeholder:r="What's on your mind? Use @ to mention someone",className:n,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const u=k.useRef(null),m=k.useRef(null),[f,x]=k.useState(!1),[y,_]=k.useState("user"),[b,j]=k.useState(""),[N,C]=k.useState(null),[A,E]=k.useState(0),[D,R]=k.useState({top:0,left:0,width:0}),F=k.useRef(new Map),O=k.useRef(new Map),B=je=>{if(c==="plain"){const Oe=[];return F.current.forEach((ze,Ve)=>{je.includes(`@${Ve}`)&&Oe.push(ze)}),[...new Set(Oe)]}const xe=/@\[([^\]]+)\]\(([^)]+)\)/g,Ee=[];let Me;for(;(Me=xe.exec(je))!==null;)Ee.push(Me[2]);return[...new Set(Ee)]},K=je=>{if(c==="plain"){const Oe=[];return O.current.forEach((ze,Ve)=>{je.includes(`#${Ve}`)&&Oe.push(ze)}),[...new Set(Oe)]}const xe=/#\[([^\]]+)\]\(([^)]+)\)/g,Ee=[];let Me;for(;(Me=xe.exec(je))!==null;)Ee.push(Me[2]);return[...new Set(Ee)]};k.useEffect(()=>{if(i){const je=B(s);i(je)}if(l){const je=K(s);l(je)}},[s,i,l,c]);const{data:Z=[],isLoading:Q}=pt({queryKey:["mention-users",b],queryFn:async()=>{const je=U.from("profiles").select("id, name").limit(8),xe=b.length>=1?je.ilike("name",`%${b}%`):je.order("name"),{data:Ee,error:Me}=await xe;if(Me)throw Me;const Oe=Ee.map(ze=>ze.id),Ie=await klt(Oe);return Ee.map(ze=>({id:ze.id,name:ze.name||"Unknown",avatar_url:Ie.get(ze.id)}))},enabled:f&&y==="user",staleTime:3e4}),{data:W=[],isLoading:te}=pt({queryKey:["mention-templates",b],queryFn:async()=>{let je=U.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);b.length>=1&&(je=je.ilike("name",`%${b}%`));const{data:xe,error:Ee}=await je;if(Ee)throw Ee;return xe||[]},enabled:f&&y==="template"&&d,staleTime:3e4}),ne=y==="user"?Q:te,ae=y==="user"?Z:W,ue=je=>je.split(" ").map(xe=>xe[0]).join("").toUpperCase().slice(0,2),me=je=>{const xe=je.target.value,Ee=je.target.selectionStart;t(xe);const Me=xe.substring(0,Ee),Oe=Me.lastIndexOf("@"),Ie=d?Me.lastIndexOf("#"):-1;let ze=-1,Ve="user";if(Oe>Ie?(ze=Oe,Ve="user"):Ie>Oe&&d&&(ze=Ie,Ve="template"),ze!==-1){const Le=Me.substring(ze+1),$e=Le.includes(" "),ve=Le.includes(` `);if(!$e&&!ve&&Le.length<=30){C(ze),j(Le),_(Ve),x(!0),E(0);return}}x(!1),C(null)},de=je=>{if(N===null)return;const xe=s.substring(0,N),Ee=s.substring(N+b.length+1),Me=y==="user"?"@":"#",Oe=c==="plain"?`${Me}${je.name} `:`${Me}[${je.name}](${je.id}) `;c==="plain"&&(y==="user"?F.current.set(je.name,je.id):O.current.set(je.name,je.id));const Ie=xe+Oe+Ee;t(Ie),x(!1),C(null),j(""),setTimeout(()=>{if(u.current){const ze=xe.length+Oe.length;u.current.focus(),u.current.setSelectionRange(ze,ze)}},0)},fe=je=>{if(!(!f||ae.length===0))switch(je.key){case"ArrowDown":je.preventDefault(),E(xe=>(xe+1)%ae.length);break;case"ArrowUp":je.preventDefault(),E(xe=>(xe-1+ae.length)%ae.length);break;case"Enter":ae[A]&&(je.preventDefault(),de(ae[A]));break;case"Escape":je.preventDefault(),x(!1);break;case"Tab":ae[A]&&(je.preventDefault(),de(ae[A]));break}};return k.useEffect(()=>{const je=xe=>{m.current&&!m.current.contains(xe.target)&&u.current&&!u.current.contains(xe.target)&&x(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[]),k.useEffect(()=>{if(!f)return;const je=()=>{const xe=u.current;if(!xe)return;const Ee=xe.getBoundingClientRect();R({top:Ee.bottom+4,left:Ee.left,width:Ee.width})};return je(),window.addEventListener("resize",je),window.addEventListener("scroll",je,!0),()=>{window.removeEventListener("resize",je),window.removeEventListener("scroll",je,!0)}},[f,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(pr,{ref:u,value:s,onChange:me,onKeyDown:je=>{fe(je),je.defaultPrevented||o==null||o(je)},placeholder:r,className:zt("resize-none",n),style:{minHeight:a}}),f&&vx.createPortal(e.jsxs("div",{ref:m,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:D.top,left:D.left,width:D.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:y==="user"?"👤 Mention a person":"📋 Link a template"}),ne?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):ae.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:b.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:ae.map((je,xe)=>e.jsx("li",{className:zt("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",xe===A?"bg-accent":"hover:bg-accent/50"),onClick:()=>de(je),onMouseEnter:()=>E(xe),children:y==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Wn,{className:"h-6 w-6",children:[e.jsx(Xa,{src:je.avatar_url}),e.jsx(Kn,{className:"text-xs",children:ue(je.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:je.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:je.preview_image_url?e.jsx("img",{src:je.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(dl,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:je.name})]})},je.id))})]}),document.body)]})}function Tps(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,r=[];let n;for(;(n=t.exec(s))!==null;)r.push(n[2]);return[...new Set(r)]}const uUe=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function uft({comment:s,postId:t,currentUserId:r,currentUserAvatar:n,currentUserEmail:a,canModerate:i,depth:l=0}){const o=is(),[c,d]=k.useState(!1),[u,m]=k.useState(""),[f,x]=k.useState([]),y=Mt({mutationFn:async({content:N,parentCommentId:C})=>{const{data:A,error:E}=await U.from("community_comments").insert({post_id:t,user_id:r,content:N,parent_comment_id:C}).select("id").single();if(E)throw E;const D=f;if(D.length>0&&A){const R=D.filter(F=>F!==r).map(F=>({comment_id:A.id,mentioned_user_id:F,mentioned_by_user_id:r}));R.length>0&&await U.from("community_comment_mentions").insert(R)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),m(""),x([]),d(!1)}}),_=Mt({mutationFn:async N=>{const{error:C}=await U.from("community_comments").delete().eq("id",N);if(C)throw C},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),b=()=>{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(Wn,{className:"h-8 w-8 shrink-0",children:[e.jsx(Xa,{src:s.user_avatar||void 0}),e.jsx(Kn,{className:"text-xs",children:uUe(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(qAe,{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:Nl(new Date(s.created_at),{addSuffix:!0})}),e.jsx(Cps,{commentId:s.id,reactions:s.reactions,currentUserId:r}),r&&l<2&&e.jsxs("button",{onClick:()=>d(!c),className:"hover:text-primary flex items-center gap-1",children:[e.jsx(VF,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===r||i)&&e.jsx("button",{onClick:()=>_.mutate(s.id),className:"hover:text-destructive",children:s.user_id!==r?"Remove":"Delete"})]}),c&&r&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(Wn,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(Xa,{src:n||void 0}),e.jsx(Kn,{className:"text-xs",children:uUe((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(Tfe,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:m,onMentionsChange:x,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(q,{size:"sm",variant:"ghost",onClick:b,disabled:!u.trim()||y.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(hn,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(N=>e.jsx(uft,{comment:N,postId:t,currentUserId:r,currentUserAvatar:n,currentUserEmail:a,canModerate:i,depth:l+1},N.id))})]})}const Xq=[{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"}],Eps=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:r,isAdmin:n}=Cs(),{avatarUrl:a}=Nlt(s==null?void 0:s.id),{onlineUsers:i}=Htt(),{toast:l}=Ba(),o=is(),c=k.useRef(null),[d,u]=k.useState("all"),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState([]),[C,A]=k.useState([]),[E,D]=k.useState(""),[R,F]=k.useState(!1),[O,B]=k.useState(null),[K,Z]=k.useState(""),[Q,W]=k.useState(new Set),[te,ne]=k.useState({}),[ae,ue]=k.useState({}),[me,de]=k.useState([]),[fe,je]=k.useState([]),[xe,Ee]=k.useState({open:!1,images:[],index:0});k.useEffect(()=>{if(d.startsWith("group:")){const St=d.replace("group:","");b(St),y("")}else d!=="all"?(y(d),b("")):(y(""),b(""))},[d]);const{data:Me=[]}=pt({queryKey:["community-categories"],queryFn:async()=>{const{data:St,error:Yt}=await U.from("community_categories").select("*").order("sort_order");if(Yt)throw Yt;return St}}),{data:Oe=[]}=pt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:St,error:Yt}=await U.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(Yt)throw Yt;return St}}),Ie=20,{data:ze,isLoading:Ve,hasNextPage:Le,fetchNextPage:$e,isFetchingNextPage:ve}=kEt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:St})=>{var Ke;const Yt=St*Ie,es=Yt+Ie;let zs=U.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(Yt,es);if(d.startsWith("group:")){const at=d.replace("group:","");zs=zs.eq("private_group_id",at)}else d==="all"||(zs=zs.eq("category_id",d).is("private_group_id",null));const{data:sr,error:ms}=await zs;if(ms)throw ms;const gt=((sr==null?void 0:sr.length)||0)>Ie,Ut=(sr||[]).slice(0,Ie);if(Ut.length===0)return{posts:[],hasMore:!1,nextPage:St+1};const ht=Ut.map(at=>at.id),Jt=[...new Set(Ut.filter(at=>at.category_id).map(at=>at.category_id))].filter(Boolean),[Ms,ts,Xs,js,$s]=await Promise.all([Jt.length?U.from("community_categories").select("*").in("id",Jt):Promise.resolve({data:[]}),U.from("community_post_media").select("*").in("post_id",ht).order("sort_order"),U.from("community_reactions").select("*").in("post_id",ht),U.from("community_comments").select("*").in("post_id",ht).order("created_at",{ascending:!0}),U.from("community_post_resources").select("*").in("post_id",ht)]),Js=Ms==null?void 0:Ms.data,or=ts==null?void 0:ts.data,Er=Xs==null?void 0:Xs.data,Sr=js==null?void 0:js.data,Gr=$s==null?void 0:$s.data,Yr=(Sr||[]).map(at=>at.id),[Fn,sa]=await Promise.all([Yr.length?U.from("community_comment_reactions").select("*").in("comment_id",Yr):Promise.resolve({data:[]}),(()=>{const at=(Gr||[]).filter(Nt=>Nt.resource_type==="template").map(Nt=>Nt.resource_id);return at.length===0?Promise.resolve({data:[]}):U.from("canva_templates").select("id, name, preview_image_url").in("id",at)})()]),gs=(Fn==null?void 0:Fn.data)||[],mi=(sa==null?void 0:sa.data)||[],In=new Map(mi.map(at=>[at.id,{name:at.name,preview_image_url:at.preview_image_url}])),Br=Array.from(new Set([...Ut.map(at=>at.user_id),...(Er||[]).map(at=>at.user_id),...(Sr||[]).map(at=>at.user_id),...gs.map(at=>at.user_id)])),[ps,Or]=await Promise.all([Br.length?U.from("profiles").select("id, name").in("id",Br):Promise.resolve({data:[]}),klt(Br)]),Qr=new Map(((Ke=ps==null?void 0:ps.data)==null?void 0:Ke.map(at=>[at.id,at.name]))||[]),Tn=new Map((Js||[]).map(at=>[at.id,at])),Qt=at=>{const Nt=new Map,Ft=[];return at.forEach(qt=>{Nt.set(qt.id,{...qt,user_name:Qr.get(qt.user_id)||"Unknown User",user_avatar:Or.get(qt.user_id),reactions:gs.filter(cs=>cs.comment_id===qt.id).map(cs=>({...cs,user_name:Qr.get(cs.user_id)||"Unknown User",user_avatar:Or.get(cs.user_id)})),replies:[]})}),at.forEach(qt=>{const cs=Nt.get(qt.id);if(qt.parent_comment_id&&Nt.has(qt.parent_comment_id)){const it=Nt.get(qt.parent_comment_id);it.replies=it.replies||[],it.replies.push(cs)}else Ft.push(cs)}),Ft};return{posts:Ut.map(at=>{const Nt=(Gr||[]).filter(Ft=>Ft.post_id===at.id).map(Ft=>{let qt="",cs=null;if(Ft.resource_type==="template"){const it=In.get(Ft.resource_id);qt=(it==null?void 0:it.name)||"Unknown Template",cs=(it==null?void 0:it.preview_image_url)||null}return{id:Ft.id,resource_type:Ft.resource_type,resource_id:Ft.resource_id,resource_name:qt,resource_preview_url:cs}});return{...at,user_name:Qr.get(at.user_id)||"Unknown User",user_avatar:Or.get(at.user_id),category:at.category_id?Tn.get(at.category_id):null,media:(or||[]).filter(Ft=>Ft.post_id===at.id),reactions:((Er||[]).filter(Ft=>Ft.post_id===at.id)||[]).map(Ft=>({...Ft,user_name:Qr.get(Ft.user_id)||"Unknown User",user_avatar:Or.get(Ft.user_id)})),comments:Qt((Sr||[]).filter(Ft=>Ft.post_id===at.id)),resources:Nt}}),hasMore:gt,nextPage:St+1}},getNextPageParam:St=>St.hasMore?St.nextPage:void 0}),Qe=k.useMemo(()=>(ze==null?void 0:ze.pages.flatMap(St=>St.posts))??[],[ze]),we=Mt({mutationFn:async()=>{F(!0);const{data:St,error:Yt}=await U.from("community_posts").insert({user_id:s.id,category_id:_?null:x||null,private_group_id:_||null,content:m,link_url:E||null}).select().single();if(Yt)throw Yt;for(let zs=0;zs0){const zs=me.filter(sr=>sr!==s.id).map(sr=>({post_id:St.id,mentioned_user_id:sr,mentioned_by_user_id:s.id}));zs.length>0&&await U.from("community_post_mentions").insert(zs)}const es=Tps(m);if(es.length>0){const zs=es.map(sr=>({post_id:St.id,resource_type:"template",resource_id:sr}));await U.from("community_post_resources").insert(zs)}return St},onSuccess:async St=>{var Yt;o.invalidateQueries({queryKey:["community-posts"]}),f(""),de([]),je([]),y(""),b(""),N([]),A([]),D(""),l({title:"Post created!"});try{const es=((Yt=s==null?void 0:s.user_metadata)==null?void 0:Yt.name)||"Someone",zs=m.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),sr=zs.length>50?zs.substring(0,50)+"...":zs;await U.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${es}: ${sr}`,url:"/community"}})}catch(es){console.error("Failed to send push notification:",es)}},onError:St=>{l({title:"Error creating post",description:St.message,variant:"destructive"})},onSettled:()=>F(!1)}),nt=Mt({mutationFn:async({postId:St,content:Yt})=>{const{error:es}=await U.from("community_posts").update({content:Yt}).eq("id",St);if(es)throw es},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),B(null),Z(""),l({title:"Post updated!"})}}),Se=Mt({mutationFn:async St=>{const{error:Yt}=await U.from("community_posts").delete().eq("id",St);if(Yt)throw Yt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Ge=Mt({mutationFn:async({postId:St,isPinned:Yt})=>{const{error:es}=await U.from("community_posts").update({is_pinned:!Yt,pinned_at:Yt?null:new Date().toISOString(),pinned_by:Yt?null:s==null?void 0:s.id}).eq("id",St);if(es)throw es},onSuccess:(St,{isPinned:Yt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:Yt?"Post unpinned":"Post pinned to top"})}}),We=Mt({mutationFn:async({postId:St,reactionType:Yt})=>{var zs;const es=(zs=Qe.find(sr=>sr.id===St))==null?void 0:zs.reactions.find(sr=>sr.user_id===(s==null?void 0:s.id));es?es.reaction_type===Yt?await U.from("community_reactions").delete().eq("id",es.id):await U.from("community_reactions").update({reaction_type:Yt}).eq("id",es.id):await U.from("community_reactions").insert({post_id:St,user_id:s.id,reaction_type:Yt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ce=Mt({mutationFn:async({postId:St,content:Yt})=>{const{data:es,error:zs}=await U.from("community_comments").insert({post_id:St,user_id:s.id,content:Yt}).select("id").single();if(zs)throw zs;const sr=ae[St]||[];if(sr.length>0&&es){const ms=sr.filter(gt=>gt!==s.id).map(gt=>({comment_id:es.id,mentioned_user_id:gt,mentioned_by_user_id:s.id}));ms.length>0&&await U.from("community_comment_mentions").insert(ms)}},onSuccess:(St,{postId:Yt})=>{o.invalidateQueries({queryKey:["community-posts"]}),ne(es=>({...es,[Yt]:""})),ue(es=>({...es,[Yt]:[]}))}});Mt({mutationFn:async St=>{const{error:Yt}=await U.from("community_comments").delete().eq("id",St);if(Yt)throw Yt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const qe=St=>{const Yt=Array.from(St.target.files||[]);if(Yt.length+j.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}N(es=>[...es,...Yt]),Yt.forEach(es=>{const zs=new FileReader;zs.onloadend=()=>{A(sr=>[...sr,zs.result])},zs.readAsDataURL(es)})},et=St=>{N(Yt=>Yt.filter((es,zs)=>zs!==St)),A(Yt=>Yt.filter((es,zs)=>zs!==St))},Ze=St=>St.split(" ").map(Yt=>Yt[0]).join("").toUpperCase().slice(0,2),rt=St=>{const Yt={};return St.forEach(es=>{Yt[es.reaction_type]=(Yt[es.reaction_type]||0)+1}),Yt},ct=St=>{var Yt;return(Yt=St.find(es=>es.user_id===(s==null?void 0:s.id)))==null?void 0:Yt.reaction_type},vt=St=>St.reduce((Yt,es)=>Yt+1+(es.replies?vt(es.replies):0),0),kt=St=>{if(n)return!0;if(!t||!St.private_group_id)return!1;const Yt=Oe.find(es=>es.id===St.private_group_id);return Yt!=null&&Yt.brokerage_id?r.some(es=>es.id===Yt.brokerage_id):!1};return e.jsx(ws,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(ups,{categories:Me,privateGroups:Oe,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(hps,{categories:Me,privateGroups:Oe,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:a||void 0}),e.jsx(Kn,{children:s!=null&&s.email?Ze(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(Tfe,{placeholder:n?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:m,onChange:f,onMentionsChange:de,onTemplatesChange:je,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:n}),C.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:C.map((St,Yt)=>{var es;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(es=j[Yt])!=null&&es.type.startsWith("video/")?e.jsx("video",{src:St,className:"w-full h-full object-cover"}):e.jsx("img",{src:St,alt:"",className:"w-full h-full object-cover"}),e.jsx(q,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>et(Yt),children:e.jsx($r,{className:"h-3 w-3"})})]},Yt)})}),E&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:E,onChange:St=>D(St.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>D(""),children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[e.jsx("input",{type:"file",ref:c,onChange:qe,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>{var St;return(St=c.current)==null?void 0:St.click()},children:[e.jsx(zo,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>{var St;return(St=c.current)==null?void 0:St.click()},children:[e.jsx(bn,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>D("https://"),children:[e.jsx(tl,{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:[Oe.length>0?e.jsxs(Ds,{value:_||x||"none",onValueChange:St=>{St==="none"?(y(""),b("")):St.startsWith("group:")?(b(St.replace("group:","")),y("")):(y(St),b(""))},children:[e.jsx(Ps,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(Fs,{placeholder:"Select..."})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No category"}),Me.map(St=>e.jsxs(lt,{value:St.id,children:[St.icon," ",St.name]},St.id)),Oe.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"}),Oe.map(St=>e.jsxs(lt,{value:`group:${St.id}`,children:[St.icon||"🔒"," ",St.name]},St.id))]})]})]}):e.jsxs(Ds,{value:x,onValueChange:y,children:[e.jsx(Ps,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(Fs,{placeholder:"Category"})}),e.jsx(Ls,{children:Me.map(St=>e.jsxs(lt,{value:St.id,children:[St.icon," ",St.name]},St.id))})]}),e.jsxs(q,{size:"sm",onClick:()=>we.mutate(),disabled:!m.trim()||R,children:[e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Ve?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((St,Yt)=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(dr,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(dr,{className:"h-4 w-32"}),e.jsx(dr,{className:"h-4 w-full"}),e.jsx(dr,{className:"h-4 w-3/4"})]})]})})},Yt))}):Qe.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(gc,{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:[Qe.map(St=>{var Yt,es,zs,sr;return e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex gap-3 min-w-0",children:[e.jsxs(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:St.user_avatar||void 0}),e.jsx(Kn,{children:Ze(St.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:St.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Nl(new Date(St.created_at),{addSuffix:!0})}),St.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[St.category.icon," ",St.category.name]})]})]})]})]}),(St.user_id===(s==null?void 0:s.id)||kt(St))&&e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(f0,{className:"h-4 w-4"})})}),e.jsxs(Sd,{align:"end",children:[kt(St)&&St.private_group_id&&e.jsx(ti,{onClick:()=>Ge.mutate({postId:St.id,isPinned:St.is_pinned}),children:St.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(zF,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(lS,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),St.user_id===(s==null?void 0:s.id)&&e.jsxs(ti,{onClick:()=>{B(St),Z(St.content)},children:[e.jsx(Ua,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ti,{className:"text-destructive",onClick:()=>Se.mutate(St.id),children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),St.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),St.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(lS,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(qAe,{content:St.content})}),St.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${St.media.length===1?"grid-cols-1":St.media.length===2?"grid-cols-2":St.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:St.media.slice(0,4).map((ms,gt)=>{const Ut=gt===3&&St.media.length>4,ht=St.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${St.media.length===1?"max-h-[500px]":St.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>Ee({open:!0,images:St.media.map(Jt=>({url:Jt.media_url,type:Jt.media_type==="video"?"video":"image"})),index:gt}),children:[ms.media_type==="video"?e.jsx("video",{src:ms.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:ms.media_url,alt:"",className:"w-full h-full object-cover transition-transform group-hover:scale-105"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity text-white",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})}),Ut&&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:["+",ht]})})]},ms.id)})}),St.link_url&&e.jsxs("a",{href:St.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[St.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:St.link_image,alt:St.link_title||"Link preview",className:"w-full h-full object-cover",onError:ms=>{ms.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:St.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:St.link_title}),St.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:St.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(St.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(tl,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:St.link_url})]})})]}),St.reactions.length>0&&e.jsx(dft,{reactions:St.reactions,children:e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[e.jsx("div",{className:"flex -space-x-1",children:Object.entries(rt(St.reactions)).slice(0,3).map(([ms])=>{var gt;return e.jsx("span",{className:"text-base",children:(gt=Xq.find(Ut=>Ut.type===ms))==null?void 0:gt.emoji},ms)})}),e.jsx("span",{children:St.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:"flex-1",children:[ct(St.reactions)?e.jsx("span",{className:"mr-1",children:(Yt=Xq.find(ms=>ms.type===ct(St.reactions)))==null?void 0:Yt.emoji}):e.jsx(wm,{className:"h-4 w-4 mr-1"}),ct(St.reactions)?(es=Xq.find(ms=>ms.type===ct(St.reactions)))==null?void 0:es.label:"Like"]})}),e.jsx(Ko,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:Xq.map(ms=>e.jsx("button",{onClick:()=>We.mutate({postId:St.id,reactionType:ms.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:ms.label,children:ms.emoji},ms.type))})})]}),e.jsxs(q,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>W(ms=>{const gt=new Set(ms);return gt.has(St.id)?gt.delete(St.id):gt.add(St.id),gt}),children:[e.jsx(gc,{className:"h-4 w-4 mr-1"}),(()=>{const ms=vt(St.comments);return ms>0?`Comment (${ms})`:"Comment"})()]})]}),Q.has(St.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[St.comments.map(ms=>e.jsx(uft,{comment:ms,postId:St.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:kt(St)},ms.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:a||void 0}),e.jsx(Kn,{className:"text-xs",children:Ze(((zs=s.email)==null?void 0:zs.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(Tfe,{placeholder:"Write a comment... (use @ to mention)",value:te[St.id]||"",onChange:ms=>ne(gt=>({...gt,[St.id]:ms})),onMentionsChange:ms=>ue(gt=>({...gt,[St.id]:ms})),mentionFormat:"plain",onKeyDown:ms=>{var gt;ms.defaultPrevented||ms.key==="Enter"&&!ms.shiftKey&&((gt=te[St.id])!=null&>.trim())&&(ms.preventDefault(),Ce.mutate({postId:St.id,content:te[St.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>{var ms;(ms=te[St.id])!=null&&ms.trim()&&Ce.mutate({postId:St.id,content:te[St.id]})},disabled:!((sr=te[St.id])!=null&&sr.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(hn,{className:"h-4 w-4"})})]})]})]})]})},St.id)}),Le&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(q,{variant:"outline",onClick:()=>$e(),disabled:ve,children:ve?"Loading…":"Load more posts"})})]}),e.jsx(vs,{open:!!O,onOpenChange:()=>B(null),children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Edit Post"})}),e.jsx(pr,{value:K,onChange:St=>Z(St.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>B(null),children:"Cancel"}),e.jsx(q,{onClick:()=>{O&&nt.mutate({postId:O.id,content:K})},disabled:!K.trim(),children:"Save Changes"})]})]})}),e.jsx(Sps,{images:xe.images,initialIndex:xe.index,open:xe.open,onOpenChange:St=>Ee(Yt=>({...Yt,open:St}))})]})]})})},Aps=50*1024*1024;function hft({value:s,onChange:t,disabled:r}){const{user:n}=Cs(),a=k.useRef(null),[i,l]=k.useState(!1),o=async d=>{if(!d||!n)return;const u=[];l(!0);try{for(const m of Array.from(d)){if(!m.type.startsWith("image/")&&!m.type.startsWith("video/")){he.error(`${m.name}: only images and videos allowed`);continue}if(m.size>Aps){he.error(`${m.name}: must be under 50MB`);continue}const f=m.name.split(".").pop()||"bin",x=`${n.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${f}`,{error:y}=await U.storage.from("support-attachments").upload(x,m,{contentType:m.type,upsert:!1});if(y){he.error(`${m.name}: ${y.message}`);continue}u.push({path:x,type:m.type,name:m.name,size:m.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((m,f)=>f!==d)),await U.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(NF,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(t2,{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($r,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:r||i,className:"gap-1.5",children:[i?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(iS,{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 mft({attachments:s}){const[t,r]=k.useState({}),[n,a]=k.useState(!0);return k.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await U.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),r(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?n?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(ls,{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 D6={open:{label:"Open",icon:jn,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:gc,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Ti,color:"bg-green-500"},closed:{label:"Closed",icon:ad,color:"bg-muted-foreground"}},hUe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Mps(){const{user:s}=Cs(),t=is(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState([]),{data:c=[],isLoading:d}=pt({queryKey:["support-tickets"],queryFn:async()=>{const{data:x,error:y}=await U.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(y)throw y;return x},enabled:!!s}),{data:u=[]}=pt({queryKey:["ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:x,error:y}=await U.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(y)throw y;return x},enabled:!!r}),m=Mt({mutationFn:async({content:x,attachments:y})=>{if(!r||!s)throw new Error("Missing data");const{error:_}=await U.from("support_ticket_replies").insert({ticket_id:r.id,user_id:s.id,content:x,is_admin_reply:!1,attachments:y});if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",r==null?void 0:r.id]}),i(""),o([]),he.success("Reply sent!")},onError:()=>{he.error("Failed to send reply")}}),f=()=>{!a.trim()&&l.length===0||m.mutate({content:a,attachments:l})};if(r){const x=D6[r.status].icon;return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>n(null),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"secondary",children:hUe[r.category]}),e.jsxs(Xe,{className:D6[r.status].color,children:[e.jsx(x,{className:"h-3 w-3 mr-1"}),D6[r.status].label]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Ur,{children:["Created on ",As(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Pe,{children:[e.jsx(ui,{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:As(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(mft,{attachments:y.attachments})]},y.id)})})}),r.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pr,{placeholder:"Type your reply...",value:a,onChange:y=>i(y.target.value),className:"min-h-[80px]"}),e.jsx(q,{onClick:f,disabled:!a.trim()&&l.length===0||m.isPending,className:"self-end",children:e.jsx(hn,{className:"h-4 w-4"})})]}),e.jsx(hft,{value:l,onChange:o,disabled:m.isPending})]})]})]})]})]})})}return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Pe,{className:"p-6 sm:p-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-6",children:[e.jsx("div",{className:"p-4 bg-primary/20 rounded-full",children:e.jsx(e_,{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(Eke,{trigger:e.jsxs(q,{size:"lg",className:"gap-2",children:[e.jsx(Ys,{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(Mn,{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(Eke,{trigger:e.jsxs(q,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"New Ticket"]})})]}),d?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):c.length===0?e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"text-center py-12",children:[e.jsx(gc,{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(x=>{const y=D6[x.status].icon;return e.jsx(ke,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n(x),children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:x.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"outline",className:"text-xs",children:hUe[x.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(x.created_at),"MMM d, yyyy")})]})]}),e.jsxs(Xe,{className:D6[x.status].color,children:[e.jsx(y,{className:"h-3 w-3 mr-1"}),D6[x.status].label]})]})})},x.id)})})]})})}function Ips({open:s,onOpenChange:t}){return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(_s,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(vn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(bs,{children:"Schedule Agent Onboarding"}),e.jsx(an,{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 Pps({open:s,onOpenChange:t}){const{brokerageId:r}=Cs(),[n,a]=k.useState(""),[i,l]=k.useState([]),[o,c]=k.useState(!1),{data:d,isLoading:u}=pt({queryKey:["brokerage-agents-for-onboarding",r],queryFn:async()=>{if(!r)return[];const{data:_,error:b}=await U.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name",{ascending:!0});if(b)throw b;return _},enabled:s&&!!r}),m=d==null?void 0:d.filter(_=>_.name.toLowerCase().includes(n.toLowerCase())||_.email.toLowerCase().includes(n.toLowerCase())),f=_=>{l(b=>b.includes(_)?b.filter(j=>j!==_):[...b,_])},x=async()=>{if(i.length===0){he.error("Please select at least one agent");return}c(!0);try{const{data:_,error:b}=await U.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(b)throw b;he.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(_){console.error("Error sending onboarding link:",_),he.error(_.message||"Failed to send onboarding link")}finally{c(!1)}},y=_=>{_||(l([]),a("")),t(_)};return e.jsx(vs,{open:s,onOpenChange:y,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(hn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(bs,{children:"Send Onboarding Link"}),e.jsx(an,{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(_n,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:n,onChange:_=>a(_.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(m==null?void 0:m.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Dr,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(ui,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:m==null?void 0:m.map(_=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>f(_.id),children:[e.jsx(Ri,{checked:i.includes(_.id),onCheckedChange:()=>f(_.id)}),e.jsx(Wn,{className:"h-8 w-8",children:e.jsx(Kn,{className:"text-xs",children:_.name.split(" ").map(b=>b[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:_.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(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(q,{onClick:x,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function Lps(){const[s,t]=k.useState(!1),[r,n]=k.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"mb-8",children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Dr,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{children:"Agent Onboarding"}),e.jsx(Ur,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs(q,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(q,{variant:"outline",onClick:()=>n(!0),className:"flex items-center gap-2",children:[e.jsx(hn,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(Ips,{open:s,onOpenChange:t}),e.jsx(Pps,{open:r,onOpenChange:n})]})}function Dps({open:s,onOpenChange:t}){return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(_s,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(C_,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(bs,{children:"Schedule Launch Meeting"}),e.jsx(an,{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 Rps(){const[s,t]=k.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"mb-8",children:[e.jsx(Pt,{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(C_,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{children:"Launch or ReLaunch Meeting"}),e.jsx(Ur,{children:"Schedule a private LevelUp information session for your brokerage. Have one of our staff host a meeting to help your team get the most out of all our trainings, tools, and resources."})]})]})}),e.jsx(Pe,{children:e.jsxs(q,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(C_,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(Dps,{open:s,onOpenChange:t})]})}function Ops(){const s=qr(),[t,r]=k.useState(""),[n,a]=k.useState(null),{data:i,isLoading:l}=pt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:_,error:b}=await U.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(b)throw b;return _}}),{data:o}=pt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:_,error:b}=await U.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(b)throw b;return _}}),{data:c}=pt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:_,error:b}=await U.from("brokerage_resource_pdfs").select("resource_id");if(b)throw b;return _}}),{data:d}=pt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:_,error:b}=await U.from("brokerage_resource_videos").select("resource_id");if(b)throw b;return _}}),{data:u}=pt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:_,error:b}=await U.from("brokerage_resource_links").select("resource_id");if(b)throw b;return _}}),m=i==null?void 0:i.filter(_=>{var N;const b=_.title.toLowerCase().includes(t.toLowerCase())||((N=_.description)==null?void 0:N.toLowerCase().includes(t.toLowerCase())),j=!n||_.category_id===n;return b&&j}),f=o==null?void 0:o.filter(_=>i==null?void 0:i.some(b=>b.category_id===_.id)),x=_=>{const b=(c==null?void 0:c.filter(C=>C.resource_id===_).length)||0,j=(d==null?void 0:d.filter(C=>C.resource_id===_).length)||0,N=(u==null?void 0:u.filter(C=>C.resource_id===_).length)||0;return{pdfCount:b,videoCount:j,linkCount:N}},y=_=>{s(`/brokerage-resources/${_}`)};return e.jsx(ws,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Lps,{}),e.jsx(Rps,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search resources...",value:t,onChange:_=>r(_.target.value),className:"pl-10"})]}),f&&f.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Xe,{variant:n===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),f.map(_=>e.jsx(Xe,{variant:n===_.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(_.id),children:_.name},_.id))]}),!l&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(m==null?void 0:m.length)||0," resource",(m==null?void 0:m.length)!==1?"s":""," available"]}),l?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[...Array(6)].map((_,b)=>e.jsxs(ke,{children:[e.jsx(dr,{className:"h-40 w-full"}),e.jsx(Pt,{children:e.jsx(dr,{className:"h-5 w-3/4"})}),e.jsxs(Pe,{children:[e.jsx(dr,{className:"h-4 w-full mb-2"}),e.jsx(dr,{className:"h-4 w-2/3"})]})]},b))}):(m==null?void 0:m.length)===0?e.jsxs(ke,{className:"p-12 text-center",children:[e.jsx(bm,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resources found"}),e.jsx("p",{className:"text-muted-foreground",children:t||n?"Try adjusting your filters":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:m==null?void 0:m.map(_=>{const{pdfCount:b,videoCount:j,linkCount:N}=x(_.id),C=o==null?void 0:o.find(A=>A.id===_.category_id);return e.jsxs(ke,{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(bm,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Pt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Dt,{className:"text-lg line-clamp-1",children:_.title}),C&&e.jsx(Xe,{variant:"secondary",className:"shrink-0 text-xs",children:C.name})]})}),e.jsxs(Pe,{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:[b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(En,{className:"h-4 w-4"}),b]}),j>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(bn,{className:"h-4 w-4"}),j]}),N>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tl,{className:"h-4 w-4"}),N]})]})]})]},_.id)})})]})})}const Fps=()=>{const{resourceId:s}=xo(),{data:t,isLoading:r}=pt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await U.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await U.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await U.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await U.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),n=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return r?e.jsx(ws,{title:"Brokerage Resources",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):t?e.jsx(ws,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(q,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Vn,{to:"/brokerage-resources",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Resources"]})}),t.preview_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:t.preview_image_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),t.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:t.description}})]}),t.videos&&t.videos.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(bn,{className:"h-4 w-4"}),"Videos (",t.videos.length,")"]}),e.jsx("div",{className:"space-y-4",children:t.videos.map(a=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:a.title}),e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:a.video_url,className:"absolute top-0 left-0 w-full h-full rounded-lg border",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})]},a.id))})]})}),t.pdfs&&t.pdfs.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(En,{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(En,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:a.name}),a.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:n(a.file_size)})]})]}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(un,{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(un,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(un,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(ws,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(bm,{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(q,{asChild:!0,className:"mt-4",children:e.jsx(Vn,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function zps(){const{onlineUsers:s,totalOnline:t}=Htt();return e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(Xe,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Rh,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Pe,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No other users online right now"}):e.jsx(ui,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(r=>{var n;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Wn,{className:"h-9 w-9",children:[e.jsx(Xa,{src:r.avatarUrl,alt:r.name}),e.jsx(Kn,{className:"text-xs",children:(n=r.name)==null?void 0:n.split(" ").map(a=>a[0]).join("").slice(0,2).toUpperCase()})]}),e.jsx("span",{className:"absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-background"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:r.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",Nl(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const mUe={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Dr,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:e7,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:S0,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:bF,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:Fh,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Ec,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Dr,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:Hu,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:xl,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:wo,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:dl,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:ch,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:A_,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:Ir,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:Ir,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:E1,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:E1,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:xu,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:bm,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:bm,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:Ks,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:fh,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:LE,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Ey,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:Ks,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:fh,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:VI,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:T_,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:Di,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:wo,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:Ul,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Dr,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:fh,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:Ui,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:XI,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:o2,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:fa,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:Ks,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:Mo,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:vm,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:Jy,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:ch,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:yi,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:Pn,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:xl,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:xl,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:Jy,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:vm,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:zo,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:Ks,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:tS,path:"/admin/beta/homereel",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"}]},"lead-sites":{label:"Lead Sites",sections:[{title:"All Sites",description:"Overview of all agent websites with status and quick actions",icon:Ql,path:"/admin/lead-sites",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"MLS Feeds",description:"Manage MLS data feed connections, API keys, and coverage areas",icon:_F,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:Wo,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:En,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:En,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:Xl,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function fUe(){const s=qr();return console.log("[AdminDashboard] render"),e.jsx(ws,{title:"Admin Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Admin Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage all aspects of your platform"})]}),e.jsx("div",{className:"w-full lg:w-80",children:e.jsx(zps,{})})]}),e.jsxs(ta,{defaultValue:"users",className:"w-full",children:[e.jsx(ea,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(mUe).map(([t,r])=>e.jsx(rs,{value:t,className:"data-[state=active]:bg-background",children:r.label},t))}),Object.entries(mUe).map(([t,r])=>e.jsx(fs,{value:t,className:"mt-6",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:r.sections.map(n=>e.jsxs(ke,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(n.path),children:[e.jsxs(Pt,{className:"pb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${n.color} mb-2 group-hover:scale-110 transition-transform`,children:e.jsx(n.icon,{className:"h-5 w-5"})}),e.jsx(Dt,{className:"text-base",children:n.title})]}),e.jsx(Pe,{className:"pt-0",children:e.jsx(Ur,{className:"text-sm",children:n.description})})]},n.path))})},t))]})]})})}const da=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:r,className:zt("w-full caption-bottom text-sm",s),...t})}));da.displayName="Table";const ua=k.forwardRef(({className:s,...t},r)=>e.jsx("thead",{ref:r,className:zt("[&_tr]:border-b",s),...t}));ua.displayName="TableHeader";const ha=k.forwardRef(({className:s,...t},r)=>e.jsx("tbody",{ref:r,className:zt("[&_tr:last-child]:border-0",s),...t}));ha.displayName="TableBody";const Bps=k.forwardRef(({className:s,...t},r)=>e.jsx("tfoot",{ref:r,className:zt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));Bps.displayName="TableFooter";const Ws=k.forwardRef(({className:s,...t},r)=>e.jsx("tr",{ref:r,className:zt("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));Ws.displayName="TableRow";const At=k.forwardRef(({className:s,...t},r)=>e.jsx("th",{ref:r,className:zt("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));At.displayName="TableHead";const xt=k.forwardRef(({className:s,...t},r)=>e.jsx("td",{ref:r,className:zt("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));xt.displayName="TableCell";const $ps=k.forwardRef(({className:s,...t},r)=>e.jsx("caption",{ref:r,className:zt("mt-4 text-sm text-muted-foreground",s),...t}));$ps.displayName="TableCaption";const Ups=()=>{const{isAdmin:s}=Cs(),t=qr(),[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState(null);k.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:_,error:b}=await U.from("app_tiles").select("*").order("name");if(b)throw b;n(_||[])}catch(_){console.error("Error loading apps:",_),he.error("Failed to load apps")}finally{i(!1)}},m=async _=>{_.preventDefault();const b=new FormData(_.currentTarget),j={name:b.get("name"),description:b.get("description"),icon:b.get("icon"),app_id:b.get("app_id"),target_url:b.get("target_url"),required_tags:b.get("required_tags").split(",").map(N=>N.trim()).filter(Boolean)};try{if(c){const{error:N}=await U.from("app_tiles").update(j).eq("id",c.id);if(N)throw N;he.success("App updated successfully")}else{const{error:N}=await U.from("app_tiles").insert([j]);if(N)throw N;he.success("App created successfully")}o(!1),d(null),u()}catch(N){console.error("Error saving app:",N),he.error("Failed to save app")}},f=async _=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:b}=await U.from("app_tiles").delete().eq("id",_);if(b)throw b;he.success("App deleted successfully"),u()}catch(b){console.error("Error deleting app:",b),he.error("Failed to delete app")}},x=_=>{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(q,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(Aa,{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(vs,{open:l,onOpenChange:o,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{onClick:y,children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:c?"Edit App":"Create New App"}),e.jsx(an,{children:"Configure the application tile settings"})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"name",children:"App Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"app_id",children:"App ID"}),e.jsx(Ne,{id:"app_id",name:"app_id",defaultValue:c==null?void 0:c.app_id,placeholder:"agent_connect",required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{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(ce,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(Ne,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"target_url",children:"Target URL"}),e.jsx(Ne,{id:"target_url",name:"target_url",type:"url",defaultValue:c==null?void 0:c.target_url,required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(Ne,{id:"required_tags",name:"required_tags",defaultValue:c==null?void 0:c.required_tags.join(", "),placeholder:"levelup-member, agent-connect"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(q,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Application Tiles"}),e.jsx(Ur,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Pe,{children:r.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs(q,{onClick:y,children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Icon"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"App ID"}),e.jsx(At,{children:"Target URL"}),e.jsx(At,{children:"Tags"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:r.map(_=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"text-2xl",children:_.icon}),e.jsx(xt,{className:"font-medium",children:_.name}),e.jsx(xt,{className:"font-mono text-sm",children:_.app_id}),e.jsx(xt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:_.target_url}),e.jsx(xt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:_.required_tags.map(b=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:b},b))})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>x(_),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>f(_.id),children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},_.id))})]})})]})})]})};function Uh({title:s,description:t,children:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vn,{to:"/admin",children:e.jsxs(q,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Admin Dashboard"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:s}),t&&e.jsx("p",{className:"text-muted-foreground",children:t})]}),r]})]})}const pUe=({expiresAt:s,className:t})=>{const r=new Date().getTime(),n=new Date(s).getTime(),a=Math.ceil((n-r)/(1e3*60*60*24));return a<=0?e.jsxs(Xe,{variant:"destructive",className:zt("gap-1",t),children:[e.jsx(du,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(Xe,{variant:"destructive",className:zt("gap-1",t),children:[e.jsx(jn,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(Xe,{className:zt("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(jn,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(Xe,{variant:"secondary",className:zt("gap-1",t),children:[e.jsx(jn,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},fft=({open:s,onOpenChange:t,brokerages:r,fixedBrokerageId:n,onSuccess:a})=>{const{toast:i}=Ba(),l=k.useRef(null),[o,c]=k.useState([]),[d,u]=k.useState(""),[m,f]=k.useState(!1),[x,y]=k.useState("upload"),[_,b]=k.useState(null),j=()=>{c([]),u(""),y("upload"),b(null),l.current&&(l.current.value="")},N=()=>{j(),t(!1)},C=F=>{const O=F.split(` `).map(W=>W.trim()).filter(W=>W);if(O.length===0)return[];const B=O[0].toLowerCase(),Z=B.includes("first")||B.includes("last")||B.includes("email")||B.includes("name")||B.includes("phone")||B.includes("sms")||B.includes("consent")?O.slice(1):O,Q=[];for(const W of Z){const ne=(W.includes(" ")?W.split(" "):W.split(",")).map(ae=>ae.trim().replace(/^["']|["']$/g,""));if(ne.length>=2){let ae="",ue="",me="",de="",fe;if(ne.length===2){const Ee=ne[0].split(" ");ae=Ee[0]||"",ue=Ee.slice(1).join(" ")||"",me=ne[1]}else if(ne.length===3)ae=ne[0],ue=ne[1],me=ne[2];else if(ne.length===4)ae=ne[0],ue=ne[1],me=ne[2],de=ne[3];else if(ne.length>=5){ae=ne[0],ue=ne[1],me=ne[2],de=ne[3];const Ee=ne[4].toLowerCase();fe=Ee==="true"||Ee==="yes"||Ee==="1"||Ee==="y"}const xe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(me);Q.push({firstName:ae.trim(),lastName:ue.trim(),email:me.trim().toLowerCase(),phone:de.trim()||void 0,smsConsent:fe,isValid:xe&&ae.trim().length>0,error:xe?ae.trim()?void 0:"Missing name":"Invalid email"})}}return Q},A=F=>{var K;const O=(K=F.target.files)==null?void 0:K[0];if(!O)return;const B=new FileReader;B.onload=Z=>{var te;const Q=(te=Z.target)==null?void 0:te.result,W=C(Q);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")},B.readAsText(O)},E=async()=>{const F=o.filter(B=>B.isValid);if(F.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const O=n||d||null;f(!0);try{const{data:{session:B}}=await U.auth.getSession(),K=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${B==null?void 0:B.access_token}`},body:JSON.stringify({users:F.map(Q=>({firstName:Q.firstName,lastName:Q.lastName,email:Q.email,phone:Q.phone,smsConsent:Q.smsConsent})),brokerageId:O})}),Z=await K.json();if(!K.ok)throw new Error(Z.error||"Failed to import users");b(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(B){console.error("Import error:",B),i({title:"Import Failed",description:B.message||"Failed to import users",variant:"destructive"})}finally{f(!1)}},D=o.filter(F=>F.isValid).length,R=o.filter(F=>!F.isValid).length;return e.jsx(vs,{open:s,onOpenChange:N,children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(s2,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(an,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),x==="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(ka,{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(q,{onClick:()=>{var F;return(F=l.current)==null?void 0:F.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."})]})]}),x==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!n&&r&&r.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Assign to Brokerage (optional)"}),e.jsxs(Ds,{value:d||"none",onValueChange:F=>u(F==="none"?"":F),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a brokerage..."})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No brokerage"}),r.map(F=>e.jsx(lt,{value:F.id,children:F.name},F.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(qn,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[D," valid"]})]}),R>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(go,{className:"h-4 w-4"}),e.jsxs("span",{children:[R," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/30",children:[e.jsx(At,{children:"First Name"}),e.jsx(At,{children:"Last Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Phone"}),e.jsx(At,{children:"SMS"}),e.jsx(At,{children:"Status"})]})}),e.jsx(ha,{children:o.slice(0,100).map((F,O)=>e.jsxs(Ws,{children:[e.jsx(xt,{children:F.firstName}),e.jsx(xt,{children:F.lastName}),e.jsx(xt,{children:F.email}),e.jsx(xt,{className:"text-muted-foreground",children:F.phone||"-"}),e.jsx(xt,{className:"text-muted-foreground",children:F.smsConsent===!0?"✓":F.smsConsent===!1?"✗":"-"}),e.jsx(xt,{children:F.isValid?e.jsx(Xe,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(Xe,{variant:"destructive",children:F.error||"Invalid"})})]},O))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),x==="result"&&_&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(qn,{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((F,O)=>e.jsxs("li",{children:["• ",F]},O)),_.errors.length>10&&e.jsxs("li",{children:["...and ",_.errors.length-10," more"]})]})]})]}),e.jsxs(fn,{children:[x==="upload"&&e.jsx(q,{variant:"outline",onClick:N,children:"Cancel"}),x==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"outline",onClick:j,children:"Back"}),e.jsx(q,{onClick:E,disabled:m||D===0,children:m?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${D} Agent${D!==1?"s":""}`})]}),x==="result"&&e.jsx(q,{onClick:N,children:"Done"})]})]})})};function mc({sortKey:s,currentSortKey:t,currentDirection:r,onSort:n,children:a,className:i,...l}){const o=t===s;return e.jsx(At,{className:zt("cursor-pointer select-none",i),...l,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 font-semibold hover:text-foreground transition-colors w-full text-left",onClick:()=>n(s),children:[a,o?r==="asc"?e.jsx(qu,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(gm,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Uu,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function zB(s=null,t=null){const[r,n]=k.useState(s),[a,i]=k.useState(t),l=k.useCallback(c=>{r===c?a==="asc"?i("desc"):a==="desc"?(n(null),i(null)):i("asc"):(n(c),i("asc"))},[r,a]),o=k.useCallback((c,d)=>{if(!r||!a||!d[r])return c;const u=d[r];return[...c].sort((m,f)=>{const x=u(m),y=u(f);if(x==null&&y==null)return 0;if(x==null)return 1;if(y==null)return-1;let _;return typeof x=="string"&&typeof y=="string"?_=x.localeCompare(y,void 0,{sensitivity:"base"}):_=x-y,a==="asc"?_:-_})},[r,a]);return{sortKey:r,sortDirection:a,handleSort:l,sortData:o}}const qps=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:fa},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:wo},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:ph}];function pft({open:s,onOpenChange:t,userId:r,userName:n}){const[a,i]=k.useState("custom"),[l,o]=k.useState(""),[c,d]=k.useState(""),u=n8t(),m=x=>{i(x.type),o(x.title),d(x.message)},f=async x=>{if(x.preventDefault(),!l.trim()){Dn({title:"Title required",description:"Please enter a celebration title",variant:"destructive"});return}try{await u.mutateAsync({user_id:r,celebration_type:a,title:l.trim(),message:c.trim()||void 0}),Dn({title:"Celebration sent! 🎉",description:`${n} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{Dn({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",n]}),e.jsx(an,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(ce,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:qps.map((x,y)=>e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>m(x),className:"text-xs",children:[e.jsx(x.icon,{className:"h-3 w-3 mr-1"}),x.title]},y))})]}),e.jsxs("form",{onSubmit:f,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(Ds,{value:a,onValueChange:x=>i(x),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-4 w-4"})," Custom"]})}),e.jsx(lt,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wo,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(lt,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(lt,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xl,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:l,onChange:x=>o(x.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"message",children:"Message (optional)"}),e.jsx(pr,{id:"message",value:c,onChange:x=>d(x.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:u.isPending,children:[e.jsx(ph,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const xwe={points_earned:{label:"Points Earned",icon:wo,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:Pn,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:Xl,color:"bg-green-500"},custom:{label:"Custom",icon:Ir,color:"bg-purple-500"}};function Vps(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("all"),{data:l=[],isLoading:o}=pt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:m}=await U.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(m)throw m;const f=[...new Set([...u.map(_=>_.user_id),...u.map(_=>_.created_by).filter(Boolean)])],{data:x}=await U.from("profiles").select("id, name, email").in("id",f),y=new Map((x==null?void 0:x.map(_=>[_.id,_]))||[]);return u.map(_=>{var b,j,N;return{..._,user_name:((b=y.get(_.user_id))==null?void 0:b.name)||"Unknown",user_email:((j=y.get(_.user_id))==null?void 0:j.email)||"",creator_name:_.created_by?((N=y.get(_.created_by))==null?void 0:N.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var y,_;const m=((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()),f=r==="all"||u.celebration_type===r,x=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return m&&f&&x}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(xwe).reduce((u,m)=>(u[m]=l.filter(f=>f.celebration_type===m).length,u),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Ur,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:r,onValueChange:n,children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{placeholder:"Filter by type"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),Object.entries(xwe).map(([u,m])=>e.jsx(lt,{value:u,children:m.label},u))]})]}),e.jsxs(Ds,{value:a,onValueChange:i,children:[e.jsx(Ps,{className:"w-[140px]",children:e.jsx(Fs,{placeholder:"Status"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Status"}),e.jsx(lt,{value:"seen",children:"Seen"}),e.jsx(lt,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Points"}),e.jsx(At,{children:"Created By"}),e.jsx(At,{children:"Created"}),e.jsx(At,{children:"Status"})]})}),e.jsx(ha,{children:c.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const m=xwe[u.celebration_type],f=m.icon;return e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(f,{className:"h-3 w-3"}),m.label]})}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:u.user_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.user_email})]})}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:u.title}),u.message&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:u.message})]})}),e.jsx(xt,{children:u.points_amount?e.jsxs(Xe,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:As(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(xt,{children:u.seen_at?e.jsx(Xe,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(Xe,{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 Hps=()=>{const{user:s}=Cs(),{toast:t}=Ba(),[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState("all"),[u,m]=k.useState("all"),[f,x]=k.useState("new"),[y,_]=k.useState(new Set),b=k.useCallback(async()=>{try{i(!0);const{data:Q,error:W}=await U.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(W)throw W;const{data:te,error:ne}=await U.from("trial_email_exports").select("user_id");if(ne)throw ne;const ae=new Set((te||[]).map(me=>me.user_id)),ue=(Q||[]).map(me=>({...me,converted_from_trial_at:me.converted_from_trial_at??null,already_exported:ae.has(me.id)}));ue.sort((me,de)=>new Date(de.created_at).getTime()-new Date(me.created_at).getTime()),n(ue)}catch(Q){console.error("Error loading trial users:",Q),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);k.useEffect(()=>{b()},[b]);const j=Q=>Q.trial_started_at?"ghl":"stripe",N=Q=>Q.trial_expires_at?Q.trial_expires_at:Q.subscription_end_date?Q.subscription_end_date:null,C=Q=>Q.converted_from_trial_at!==null,A=Q=>{if(C(Q))return!1;const W=N(Q);return W?new Date(W).getTime()<=Date.now():!1},E=r.filter(Q=>!(c!=="all"&&j(Q)!==c||u==="active"&&(A(Q)||C(Q))||u==="expired"&&!A(Q)||u==="converted"&&!C(Q)||f==="new"&&Q.already_exported||f==="exported"&&!Q.already_exported)),D=()=>{y.size===E.length?_(new Set):_(new Set(E.map(Q=>Q.id)))},R=Q=>{const W=new Set(y);W.has(Q)?W.delete(Q):W.add(Q),_(W)},F=async()=>{if(y.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const Q=r.filter(fe=>y.has(fe.id)),W="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",te=Q.map(fe=>{const je=(fe.name||"").split(" "),xe=je[0]||"",Ee=je.slice(1).join(" ")||"",Me=j(fe)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",Oe=C(fe)?"Converted":A(fe)?"Expired":"Active",Ie=fe.created_at?new Date(fe.created_at).toLocaleDateString():"",ze=N(fe)?new Date(N(fe)).toLocaleDateString():"";return`"${xe}","${Ee}","${fe.email}","${fe.phone||""}","${Me}","${Oe}","${Ie}","${ze}"`}),ne=[W,...te].join(` `),ae=new Blob([ne],{type:"text/csv"}),ue=URL.createObjectURL(ae),me=document.createElement("a");me.href=ue,me.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,me.click(),URL.revokeObjectURL(ue);const de=Q.filter(fe=>!fe.already_exported).map(fe=>({user_id:fe.id,exported_by:s.id}));if(de.length>0){const{error:fe}=await U.from("trial_email_exports").upsert(de,{onConflict:"user_id"});fe&&console.error("Error marking exports:",fe)}t({title:"Export complete",description:`Downloaded ${Q.length} trial user(s). ${de.length} newly marked as exported.`}),_(new Set),b()}catch(Q){console.error("Export error:",Q),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},O=r.filter(Q=>!Q.already_exported).length,B=r.filter(Q=>Q.already_exported).length,K=r.filter(Q=>C(Q)).length,Z=r.filter(Q=>!A(Q)&&!C(Q)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"Total"}),e.jsx(Dt,{className:"text-2xl",children:r.length})]})}),e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"New (Not Exported)"}),e.jsx(Dt,{className:"text-2xl text-green-600",children:O})]})}),e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"Active Trials"}),e.jsx(Dt,{className:"text-2xl",children:Z})]})}),e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"Converted 🎉"}),e.jsx(Dt,{className:"text-2xl text-primary",children:K})]})}),e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"Already Exported"}),e.jsx(Dt,{className:"text-2xl text-muted-foreground",children:B})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Ds,{value:f,onValueChange:Q=>x(Q),children:[e.jsx(Ps,{className:"w-[160px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Users"}),e.jsx(lt,{value:"new",children:"New Only"}),e.jsx(lt,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(Ds,{value:c,onValueChange:Q=>d(Q),children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Trial Types"}),e.jsx(lt,{value:"stripe",children:"Credit Card Trial"}),e.jsx(lt,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(Ds,{value:u,onValueChange:Q=>m(Q),children:[e.jsx(Ps,{className:"w-[160px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Statuses"}),e.jsx(lt,{value:"active",children:"Active Trial"}),e.jsx(lt,{value:"expired",children:"Expired"}),e.jsx(lt,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(q,{onClick:F,disabled:l||y.size===0,children:[l?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(li,{className:"h-4 w-4 mr-2"}),"Export Selected (",y.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"w-[40px]",children:e.jsx(Ri,{checked:E.length>0&&y.size===E.length,onCheckedChange:D})}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Trial Type"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Signup Date"}),e.jsx(At,{children:"Last Login"}),e.jsx(At,{children:"Expires / Renews"}),e.jsx(At,{children:"Exported"})]})}),e.jsx(ha,{children:E.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):E.map(Q=>{const W=j(Q),te=C(Q),ne=A(Q),ae=N(Q);return e.jsxs(Ws,{className:`hover:bg-muted/30 ${te?"bg-primary/5":""}`,children:[e.jsx(xt,{children:e.jsx(Ri,{checked:y.has(Q.id),onCheckedChange:()=>R(Q.id)})}),e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Q.name,te&&e.jsx(Wo,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(xt,{className:"text-muted-foreground",children:Q.email}),e.jsx(xt,{children:W==="stripe"?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(S0,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ks,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(xt,{children:te?e.jsxs(Xe,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(Wo,{className:"h-3 w-3"}),"Converted"]}):ne?e.jsx(Xe,{variant:"destructive",children:"Expired"}):e.jsx(Xe,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(xt,{className:"text-sm",children:Q.created_at?new Date(Q.created_at).toLocaleDateString():"—"}),e.jsx(xt,{className:"text-sm",children:Q.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(Q.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(Q.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(xt,{className:"text-sm",children:te&&ae?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(ae).toLocaleDateString()]}):ae?new Date(ae).toLocaleDateString():"—"}),e.jsx(xt,{children:Q.already_exported?e.jsx(qn,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Xe,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},Q.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",E.length," of ",r.length," trial users · ",K," converted to paid"]})]})},Gps=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,Wps=()=>{const[s,t]=k.useState([]),[r,n]=k.useState(!0);k.useEffect(()=>{(async()=>{const{data:l,error:o}=await U.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),n(!1)})()},[]);const a=()=>{if(s.length===0){he.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(m=>[As(new Date(m.created_at),"MMM d, yyyy h:mm a"),m.deleted_user_name||"—",m.deleted_user_email||"—",m.brokerage_name||"—",m.deletion_type==="deleted"?"Account Deleted":"Removed",m.deleted_by_name||m.deleted_by_email||"—"]),o=[i.join(","),...l.map(m=>m.map(Gps).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),he.success(`Exported ${s.length} deletion record(s)`)};return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(zr,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{className:"text-lg",children:"User Deletion History"}),e.jsxs(q,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Pe,{children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Date"}),e.jsx(At,{children:"User"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Brokerage"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Deleted By"})]})}),e.jsx(ha,{children:s.map(i=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"whitespace-nowrap text-sm",children:As(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(xt,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(xt,{children:i.brokerage_name||"—"}),e.jsx(xt,{children:e.jsx(Xe,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(xt,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},aM=s=>{const{user:t}=Cs(),r=is(),n=pt({queryKey:["teams",s],queryFn:async()=>{let m=U.from("teams").select("*").order("created_at",{ascending:!1});s&&(m=m.eq("brokerage_id",s));const{data:f,error:x}=await m;if(x)throw x;return f||[]},enabled:!!t}),a=m=>pt({queryKey:["team-members",m],queryFn:async()=>{const{data:f,error:x}=await U.from("team_members").select("*").eq("team_id",m).order("role",{ascending:!0});if(x)throw x;const y=(f||[]).map(j=>j.user_id),{data:_}=await U.from("profiles").select("id, name, email, avatar_url").in("id",y),b=new Map((_||[]).map(j=>[j.id,j]));return(f||[]).map(j=>({...j,profile:b.get(j.user_id)||null}))},enabled:!!m}),i=Mt({mutationFn:async m=>{const f={name:m.name,created_by:t.id,description:m.description,contact_visibility:m.contact_visibility,lead_pond_enabled:m.lead_pond_enabled,shared_assets_enabled:m.shared_assets_enabled};m.brokerage_id&&(f.brokerage_id=m.brokerage_id);const{data:x,error:y}=await U.from("teams").insert(f).select().single();if(y)throw y;return x},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),he.success("Team created!")},onError:m=>{he.error("Failed to create team: "+m.message)}}),l=Mt({mutationFn:async({id:m,...f})=>{const{data:x,error:y}=await U.from("teams").update(f).eq("id",m).select().single();if(y)throw y;return x},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),he.success("Team updated")},onError:m=>{he.error("Failed to update team: "+m.message)}}),o=Mt({mutationFn:async m=>{const{error:f}=await U.from("teams").delete().eq("id",m);if(f)throw f},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),he.success("Team deleted")},onError:m=>{he.error("Failed to delete team: "+m.message)}}),c=Mt({mutationFn:async m=>{const{data:f,error:x}=await U.from("team_members").insert({team_id:m.team_id,user_id:m.user_id,role:m.role||"team_member"}).select().single();if(x)throw x.message.includes("duplicate")||x.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):x;return f},onSuccess:(m,f)=>{r.invalidateQueries({queryKey:["team-members",f.team_id]}),he.success("Member added to team")},onError:m=>{he.error(m.message)}}),d=Mt({mutationFn:async m=>{const{error:f}=await U.from("team_members").delete().eq("id",m.member_id);if(f)throw f},onSuccess:(m,f)=>{r.invalidateQueries({queryKey:["team-members",f.team_id]}),he.success("Member removed from team")},onError:m=>{he.error("Failed to remove member: "+m.message)}}),u=Mt({mutationFn:async m=>{const{error:f}=await U.from("team_members").update({role:m.role}).eq("id",m.member_id);if(f)throw f},onSuccess:(m,f)=>{r.invalidateQueries({queryKey:["team-members",f.team_id]}),he.success("Member role updated")},onError:m=>{he.error("Failed to update role: "+m.message)}});return{teams:n.data||[],isLoading:n.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:u,useTeamMembers:a}},Kps=()=>{const{user:s}=Cs();return pt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.rpc("get_team_contacts",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})},xft=s=>{const{user:t}=Cs(),r=is(),n=pt({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await U.from("team_lead_pond").select("*").eq("team_id",s).order("created_at",{ascending:!1});if(c)throw c;if(!o||o.length===0)return[];const d=o.map(j=>j.contact_id),u=[...new Set(o.map(j=>j.added_by))],m=o.filter(j=>j.claimed_by).map(j=>j.claimed_by),f=[...new Set([...u,...m])],[x,y]=await Promise.all([U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),U.from("profiles").select("id, name, avatar_url").in("id",f)]),_=new Map((x.data||[]).map(j=>[j.id,j])),b=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:b.get(j.added_by)||null,claimer:j.claimed_by&&b.get(j.claimed_by)||null}))},enabled:!!s&&!!t}),a=Mt({mutationFn:async o=>{const{data:c,error:d}=await U.rpc("add_to_lead_pond",{_contact_id:o.contact_id,_team_id:o.team_id,_notes:o.notes||null});if(d)throw d;return c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),he.success("Contact added to Lead Pond")},onError:o=>{he.error(o.message)}}),i=Mt({mutationFn:async o=>{const{error:c}=await U.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),he.success("Lead claimed!")},onError:o=>{he.error(o.message)}}),l=Mt({mutationFn:async o=>{const{error:c}=await U.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),he.success("Lead returned to pond")},onError:o=>{he.error(o.message)}});return{leadPondItems:n.data||[],isLoading:n.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},Yps=()=>{const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(n)throw n;const a=r;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),he.success("Contact transferred successfully")},onError:t=>{he.error(t.message||"Failed to transfer contact")}})};function gft({open:s,onOpenChange:t,contactIds:r,contactNames:n=[],onComplete:a}){var E;const{user:i}=Cs(),{data:l}=uv(),{useTeamMembers:o}=aM(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=Yps(),[u,m]=k.useState(null),[f,x]=k.useState(""),[y,_]=k.useState(!1),b=c.filter(D=>D.user_id!==(i==null?void 0:i.id)),j=async()=>{if(u){_(!0);try{for(const D of r)await d.mutateAsync({contactId:D,toUserId:u,notes:f||void 0});t(!1),m(null),x(""),a==null||a()}catch{}finally{_(!1)}}},N=b.find(D=>D.user_id===u),C=r.length>1,A=n.length>0?C?`${n.length} contacts`:n[0]:C?`${r.length} contacts`:"this contact";return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Jj,{className:"h-5 w-5"}),"Transfer ",A]}),e.jsxs(an,{children:["Select a team member to transfer ",C?"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(ce,{className:"text-sm font-medium mb-2 block",children:"Transfer to:"}),e.jsx("div",{className:"space-y-1 max-h-[240px] overflow-y-auto",children:b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):b.map(D=>{var R,F,O;return e.jsxs("button",{onClick:()=>m(D.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===D.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:((R=D.profile)==null?void 0:R.avatar_url)||""}),e.jsx(Kn,{className:"text-xs",children:(((F=D.profile)==null?void 0:F.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((O=D.profile)==null?void 0:O.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:D.role.replace("_"," ")})]})]},D.user_id)})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(pr,{id:"transfer-notes",value:f,onChange:D=>x(D.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:j,disabled:!u||y,children:[y?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jj,{className:"h-4 w-4 mr-2"}),"Transfer",N?` to ${(E=N.profile)==null?void 0:E.name}`:""]})]})]})})}const VAe=()=>{const s=qr(),{data:t,isLoading:r}=Kps(),{data:n}=uv(),[a,i]=k.useState(""),[l,o]=k.useState("all"),[c,d]=k.useState(null),[u,m]=k.useState(""),f=(n==null?void 0:n.role)==="team_leader",x=k.useMemo(()=>{if(!t)return[];const _=new Map;return t.forEach(b=>{_.has(b.owner_user_id)||_.set(b.owner_user_id,{id:b.owner_user_id,name:b.owner_name||"Unknown",avatar:b.owner_avatar_url})}),Array.from(_.values())},[t]),y=k.useMemo(()=>{if(!t)return[];let _=t;if(l!=="all"&&(_=_.filter(b=>b.owner_user_id===l)),a.trim()){const b=a.toLowerCase();_=_.filter(j=>{var N,C,A;return(j.first_name+" "+(j.last_name||"")).toLowerCase().includes(b)||((N=j.email)==null?void 0:N.toLowerCase().includes(b))||((C=j.phone)==null?void 0:C.includes(b))||((A=j.owner_name)==null?void 0:A.toLowerCase().includes(b))})}return _},[t,a,l]);return r?e.jsxs("div",{className:"space-y-4",children:[e.jsx(dr,{className:"h-10 w-full"}),e.jsx(dr,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Dr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Team Contacts"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team contact sharing is not enabled, or you're not on a team. Ask your manager about contact visibility settings."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:_=>i(_.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:l,onValueChange:o,children:[e.jsx(Ps,{className:"w-[200px]",children:e.jsx(Fs,{placeholder:"Filter by agent"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Team Members"}),x.map(_=>e.jsx(lt,{value:_.id,children:_.name},_.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[y.length," contact",y.length!==1?"s":""," from ",x.length," teammate",x.length!==1?"s":""]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0 overflow-x-auto",children:e.jsxs(da,{className:"min-w-[800px]",children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Contact Info"}),e.jsx(At,{children:"Address"}),e.jsx(At,{children:"Lead Source"}),e.jsx(At,{children:"Date Added"}),f&&e.jsx(At,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(ha,{children:y.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:f?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(Ws,{className:`hover:bg-accent/50 ${f?"cursor-pointer":""}`,onClick:f?()=>s(`/mission-control/contacts/${_.id}`):void 0,children:[e.jsx(xt,{className:"font-medium",children:e.jsxs("span",{className:f?"hover:text-primary hover:underline transition-colors":"",children:[_.first_name," ",_.last_name||""]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Wn,{className:"h-6 w-6",children:[e.jsx(Xa,{src:_.owner_avatar_url||""}),e.jsx(Kn,{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(xt,{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(Ks,{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(Mn,{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(xt,{children:_.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Ma,{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(xt,{children:_.lead_source?e.jsx(Xe,{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(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:As(new Date(_.created_at),"MMM d, yyyy")})}),f&&e.jsx(xt,{children:e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:b=>{b.stopPropagation(),d(_.id),m(`${_.first_name} ${_.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(Jj,{className:"h-4 w-4"})})})]},_.id))})]})})}),e.jsx(gft,{open:!!c,onOpenChange:_=>{_||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},HAe=({teamId:s})=>{const{user:t}=Cs(),{leadPondItems:r,isLoading:n,claimLead:a,returnLead:i}=xft(s);if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",r.length,"loading:",n),n)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(c=>e.jsx(dr,{className:"h-20 w-full"},c))});if(r.length===0)return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(S1,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Lead Pond is Empty"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team members can contribute contacts here for others to claim and follow up with."})]})});const l=r.filter(c=>c.status==="available"),o=r.filter(c=>c.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",l.length,")"]}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads available right now."}):e.jsx("div",{className:"space-y-2",children:l.map(c=>{var d,u,m,f,x,y,_;return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((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:[((m=c.contact)==null?void 0:m.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ks,{className:"h-3 w-3"})," ",c.contact.email]}),((f=c.contact)==null?void 0:f.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"})," ",c.contact.phone]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(Wn,{className:"h-4 w-4",children:[e.jsx(Xa,{src:((x=c.contributor)==null?void 0:x.avatar_url)||""}),e.jsx(Kn,{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(q,{size:"sm",onClick:()=>a.mutate(c.id),disabled:a.isPending,children:[e.jsx(CF,{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,m;return e.jsx(ke,{className:"opacity-75",children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((u=c.contact)==null?void 0:u.last_name)||""]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:["Claimed by ",((m=c.claimer)==null?void 0:m.name)||"Unknown"]})})]}),c.claimed_by===(t==null?void 0:t.id)&&e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>i.mutate(c.id),disabled:i.isPending,children:[e.jsx(ev,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},yft=({teamId:s})=>{const{useTeamMembers:t}=aM(),{data:r=[]}=t(s),n=r.map(x=>x.user_id),a=new Map(r.map(x=>[x.user_id,x.profile])),{data:i=[],isLoading:l}=pt({queryKey:["team-shared-presentations",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:x,error:y}=await U.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",n).neq("status","archived").order("created_at",{ascending:!1});if(y)throw y;return x||[]},enabled:n.length>0}),{data:o=[],isLoading:c}=pt({queryKey:["team-shared-open-houses",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:x,error:y}=await U.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",n).order("event_date",{ascending:!1});if(y)throw y;return x||[]},enabled:n.length>0}),{data:d=[],isLoading:u}=pt({queryKey:["team-shared-videos",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:x,error:y}=await U.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",n).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(y)throw y;return x||[]},enabled:n.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(x=>e.jsx(dr,{className:"h-20 w-full"},x))});const f=x=>{const y=a.get(x);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(ke,{children:e.jsxs(Pe,{className:"flex items-center gap-3 p-4",children:[e.jsx(Jy,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:i.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Presentations"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center gap-3 p-4",children:[e.jsx(Pn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:o.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Guest Books"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center gap-3 p-4",children:[e.jsx(bn,{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(ta,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(rs,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(rs,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(fs,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(gwe,{icon:e.jsx(Jy,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(x=>{const y=f(x.owner_user_id);return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Wn,{className:"h-8 w-8 shrink-0",children:[e.jsx(Xa,{src:y.avatar}),e.jsx(Kn,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:x.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",As(new Date(x.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Xe,{variant:x.status==="published"?"default":"secondary",className:"text-xs capitalize",children:x.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),x.view_count||0]})]})]})},x.id)})}),e.jsx(fs,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(gwe,{icon:e.jsx(Pn,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(x=>{const y=f(x.agent_id);return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Wn,{className:"h-8 w-8 shrink-0",children:[e.jsx(Xa,{src:y.avatar}),e.jsx(Kn,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:x.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",As(new Date(x.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[x.is_active?e.jsx(Xe,{className:"text-xs",children:"Active"}):e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Dr,{className:"h-3 w-3"}),x.visitor_count||0]})]})]})},x.id)})}),e.jsx(fs,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(gwe,{icon:e.jsx(bn,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(x=>{const y=f(x.owner_user_id);return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Wn,{className:"h-8 w-8 shrink-0",children:[e.jsx(Xa,{src:y.avatar}),e.jsx(Kn,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:x.title||x.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",As(new Date(x.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Xe,{variant:"secondary",className:"text-xs capitalize",children:x.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),x.view_count||0]})]})]})},x.id)})})]})]})},gwe=({icon:s,label:t})=>e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-8 text-center text-muted-foreground",children:[s,e.jsx("p",{className:"mt-2 text-sm",children:t})]})}),vft=({team:s,brokerageAgents:t,onBack:r,onUpdate:n,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var R,F;const{useTeamMembers:u}=aM(),{data:m=[],isLoading:f}=u(s.id),[x,y]=k.useState(!1),[_,b]=k.useState(""),[j,N]=k.useState("team_member"),{data:C}=pt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:O}=await U.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),B=new Map;return(O||[]).forEach(K=>{var Z;B.set(K.user_id,((Z=K.teams)==null?void 0:Z.name)||"another team")}),B}}),A=new Set(m.map(O=>O.user_id)),E=t.filter(O=>!A.has(O.id)),D=async()=>{_&&(await a(_,j),b(""),N("team_member"),y(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(q,{variant:"ghost",onClick:r,className:"mb-2",children:"← Back to Teams"}),e.jsxs(ta,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"members",children:"Members"}),e.jsxs(rs,{value:"contacts",children:[e.jsx(AE,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(rs,{value:"lead-pond",children:[e.jsx(S1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(rs,{value:"shared-assets",children:[e.jsx(Kf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(rs,{value:"settings",children:"Settings"})]}),e.jsxs(fs,{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(vs,{open:x,onOpenChange:y,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{size:"sm",children:[e.jsx(xl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Add Team Member"}),e.jsxs(an,{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(ce,{children:"Agent"}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[_&&(((R=E.find(O=>O.id===_))==null?void 0:R.name)||((F=E.find(O=>O.id===_))==null?void 0:F.email))||"Select an agent",e.jsx(xg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search agents..."}),e.jsxs(kg,{children:[e.jsx(Sg,{children:"No agents found."}),e.jsx(Cg,{children:E.map(O=>{const B=C==null?void 0:C.get(O.id);return e.jsxs(Sp,{value:O.name||O.email||O.id,disabled:!!B,onSelect:()=>b(O.id),children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",_===O.id?"opacity-100":"opacity-0")}),O.name||O.email,B&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(on ",B,")"]})]},O.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Role"}),e.jsxs(Ds,{value:j,onValueChange:N,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"team_leader",children:"Team Leader"}),e.jsx(lt,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(q,{onClick:D,disabled:!_||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),f?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(O=>e.jsx(dr,{className:"h-16 w-full"},O))}):m.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Dr,{className:"h-10 w-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No members yet. Add agents to this team."})]})}):e.jsx("div",{className:"space-y-2",children:m.map(O=>{var B,K,Z,Q,W;return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:((B=O.profile)==null?void 0:B.avatar_url)||""}),e.jsx(Kn,{children:(((K=O.profile)==null?void 0:K.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Z=O.profile)==null?void 0:Z.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(Q=O.profile)==null?void 0:Q.email})]}),O.role==="team_leader"?e.jsxs(Xe,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(Gf,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Xe,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ds,{value:O.role,onValueChange:te=>l(O.id,te),children:[e.jsx(Ps,{className:"w-[140px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"team_leader",children:"Team Leader"}),e.jsx(lt,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(r7,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Remove Member?"}),e.jsxs(Ho,{children:["Remove ",((W=O.profile)==null?void 0:W.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>i(O.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},O.id)})})]}),e.jsx(fs,{value:"contacts",className:"space-y-4",children:e.jsx(VAe,{})}),s.lead_pond_enabled&&e.jsx(fs,{value:"lead-pond",className:"space-y-4",children:e.jsx(HAe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(fs,{value:"shared-assets",className:"space-y-4",children:e.jsx(yft,{teamId:s.id})}),e.jsxs(fs,{value:"settings",className:"space-y-4",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{className:"text-lg",children:"Team Settings"}),e.jsx(Ur,{children:"Configure how this team operates."})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Team Name"}),e.jsx(Ne,{defaultValue:s.name,onBlur:O=>{O.target.value!==s.name&&n({name:O.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{defaultValue:s.description||"",onBlur:O=>{O.target.value!==(s.description||"")&&n({description:O.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Contact Visibility"}),e.jsxs(Ds,{defaultValue:s.contact_visibility,onValueChange:O=>n({contact_visibility:O}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(lt,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(lt,{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(ce,{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(Rr,{checked:s.lead_pond_enabled,onCheckedChange:O=>n({lead_pond_enabled:O})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{checked:s.shared_assets_enabled,onCheckedChange:O=>n({shared_assets_enabled:O})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{checked:s.shared_videos_enabled??!1,onCheckedChange:O=>n({shared_videos_enabled:O})})]})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsxs(q,{variant:"destructive",size:"sm",children:[e.jsx(zr,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete Team?"}),e.jsxs(Ho,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>{o(),r()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},bft=({open:s,onOpenChange:t,onCreateTeam:r,isCreating:n,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=k.useState(1),[u,m]=k.useState(""),[f,x]=k.useState(""),[y,_]=k.useState(""),[b,j]=k.useState(""),[N,C]=k.useState([]),A=()=>{d(1),m(""),x(""),_(""),j(""),C([])},E=O=>{O||A(),t(O)},D=async()=>{const O=y&&y!=="none"?y:o||null;await r({name:u.trim(),description:f.trim()||void 0,brokerage_id:O,leaderId:b||void 0,memberIds:N.length>0?N:void 0}),A()},R=O=>{O!==b&&C(B=>B.includes(O)?B.filter(K=>K!==O):[...B,O])},F=a.filter(O=>O.id!==b);return e.jsx(vs,{open:s,onOpenChange:E,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(an,{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:zt("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:zt("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(ce,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(Ne,{id:"team-name",value:u,onChange:O=>m(O.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"team-desc",children:"Description"}),e.jsx(pr,{id:"team-desc",value:f,onChange:O=>x(O.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(ce,{children:"Brokerage"}),e.jsxs(Ds,{value:y,onValueChange:_,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"No brokerage (independent team)"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No brokerage (independent)"}),l.map(O=>e.jsx(lt,{value:O.id,children:O.name},O.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{className:"flex items-center gap-1.5",children:[e.jsx(Gf,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(Ds,{value:b,onValueChange:O=>{j(O),C(B=>B.filter(K=>K!==O))},children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a team leader (optional)"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No leader for now"}),a.map(O=>e.jsx(lt,{value:O.id,children:O.name||O.email||"Unknown"},O.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{className:"flex items-center gap-1.5",children:[e.jsx(xl,{className:"h-3.5 w-3.5"}),"Initial Members",N.length>0&&e.jsxs(Xe,{variant:"secondary",className:"ml-1 text-xs",children:[N.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:F.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(Dr,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):F.map(O=>{const B=N.includes(O.id);return e.jsxs("button",{type:"button",className:zt("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",B&&"bg-primary/5"),onClick:()=>R(O.id),children:[e.jsxs(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:O.avatar_url||""}),e.jsx(Kn,{className:"text-xs",children:(O.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:O.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:O.email})]}),e.jsx("div",{className:zt("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",B?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:B&&e.jsx(la,{className:"h-3 w-3"})})]},O.id)})})]})]})}),e.jsx(fn,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsxs(q,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(ci,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"outline",onClick:()=>d(1),children:[e.jsx(Aa,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(q,{onClick:D,disabled:n,children:n?"Creating…":"Create Team"})]})})]})})},Zps=()=>{const{teams:s,isLoading:t,createTeam:r,updateTeam:n,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=aM(),[c,d]=k.useState(!1),[u,m]=k.useState(null),[f,x]=k.useState(""),{data:y}=pt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:E,error:D}=await U.from("brokerages").select("id, name").order("name");if(D)throw D;return E||[]}}),{data:_}=pt({queryKey:["admin-team-member-info",s.map(E=>E.id).join(",")],queryFn:async()=>{var O;if(s.length===0)return{};const{data:E}=await U.from("team_members").select("team_id, user_id, role").in("team_id",s.map(B=>B.id));if(!E)return{};const D=E.filter(B=>B.role==="team_leader").map(B=>B.user_id);let R={};if(D.length>0){const{data:B}=await U.from("profiles").select("id, name").in("id",D);B&&(R=Object.fromEntries(B.map(K=>[K.id,{name:K.name}])))}const F={};for(const B of s){const K=E.filter(Q=>Q.team_id===B.id),Z=K.find(Q=>Q.role==="team_leader");F[B.id]={count:K.length,leaderName:Z&&((O=R[Z.user_id])==null?void 0:O.name)||null}}return F},enabled:s.length>0}),b=(u==null?void 0:u.brokerage_id)||null,{data:j}=pt({queryKey:["brokerage-agents-for-teams",b],queryFn:async()=>{let E=U.from("profiles").select("id, name, email, avatar_url").order("name");b&&(E=E.eq("brokerage_id",b));const{data:D,error:R}=await E;if(R)throw R;return D||[]},enabled:!!u}),N=Object.fromEntries((y||[]).map(E=>[E.id,E.name])),C=async E=>{const D=await r.mutateAsync({name:E.name,brokerage_id:E.brokerage_id||null,description:E.description});if(E.leaderId&&E.leaderId!=="none"&&await i.mutateAsync({team_id:D.id,user_id:E.leaderId,role:"team_leader"}),E.memberIds)for(const R of E.memberIds)await i.mutateAsync({team_id:D.id,user_id:R,role:"team_member"});d(!1)};if(u)return e.jsx(vft,{team:u,brokerageAgents:j||[],onBack:()=>m(null),onUpdate:E=>n.mutateAsync({id:u.id,...E}).then(D=>m(D)),onAddMember:(E,D)=>i.mutateAsync({team_id:u.id,user_id:E,role:D}),onRemoveMember:E=>l.mutateAsync({team_id:u.id,member_id:E}),onUpdateRole:(E,D)=>o.mutateAsync({team_id:u.id,member_id:E,role:D}),onDeleteTeam:()=>{a.mutate(u.id),m(null)},isUpdating:n.isPending,isAddingMember:i.isPending});const A=s.filter(E=>E.name.toLowerCase().includes(f.toLowerCase())||(E.description||"").toLowerCase().includes(f.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(_n,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search teams...",value:f,onChange:E=>x(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(q,{size:"sm",onClick:()=>d(!0),children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(bft,{open:c,onOpenChange:d,onCreateTeam:C,isCreating:r.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:y,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"font-semibold",children:"Team Name"}),e.jsx(At,{className:"font-semibold",children:"Brokerage"}),e.jsx(At,{className:"font-semibold",children:"Leader"}),e.jsx(At,{className:"font-semibold",children:"Members"}),e.jsx(At,{className:"font-semibold",children:"Visibility"}),e.jsx(At,{className:"w-[100px]"})]})}),e.jsx(ha,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(E=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsx(dr,{className:"h-4 w-32"})}),e.jsx(xt,{children:e.jsx(dr,{className:"h-4 w-24"})}),e.jsx(xt,{children:e.jsx(dr,{className:"h-4 w-28"})}),e.jsx(xt,{children:e.jsx(dr,{className:"h-4 w-12"})}),e.jsx(xt,{children:e.jsx(dr,{className:"h-4 w-20"})}),e.jsx(xt,{children:e.jsx(dr,{className:"h-4 w-16"})})]},E))}):A.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:f?"No teams match your search":"No teams found. Create one to get started."})}):A.map(E=>{const D=_==null?void 0:_[E.id];return e.jsxs(Ws,{className:"hover:bg-muted/30",children:[e.jsxs(xt,{children:[e.jsx("button",{onClick:()=>m(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(xt,{children:E.brokerage_id?e.jsx("span",{className:"text-sm",children:N[E.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(xt,{children:D!=null&&D.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Gf,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),D.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(xt,{children:e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[e.jsx(Dr,{className:"h-3 w-3 mr-1"}),(D==null?void 0:D.count)??0]})}),e.jsx(xt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Oh,{className:"h-3 w-3"}),E.contact_visibility.replace("_"," ")]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>m(E),title:"Edit team",children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{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(zr,{className:"h-3.5 w-3.5"})})]})})]},E.id)})})]})})]})};function xUe(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 Xps({open:s,onOpenChange:t,recipients:r}){const{toast:n}=Ba(),[a,i]=k.useState([]),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,m]=k.useState(""),[f,x]=k.useState(""),[y,_]=k.useState(!1),[b,j]=k.useState(!1),N=k.useMemo(()=>a.find(D=>D.id===c)||null,[a,c]);k.useEffect(()=>{s&&(o(!0),(async()=>{const D=new Date().toISOString(),{data:R,error:F}=await U.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",D).order("event_date",{ascending:!0}).limit(50);F?n({title:"Could not load events",description:F.message,variant:"destructive"}):i(R||[]),o(!1)})())},[s,n]);const C=k.useMemo(()=>r.filter(D=>D.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(D.email)),[r]),A=()=>{if(!N){n({title:"Pick an event first",variant:"destructive"});return}if(C.length===0){n({title:"No valid recipient emails",variant:"destructive"});return}j(!0)},E=async()=>{if(N){j(!1),_(!0);try{const{data:{session:D}}=await U.auth.getSession(),R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({event_id:N.id,recipients:C.map(K=>({email:K.email,name:K.name,user_id:K.id})),custom_subject:u.trim()||void 0,custom_intro:f.trim()||void 0})}),F=await R.json().catch(()=>({}));if(!R.ok)throw new Error((F==null?void 0:F.error)||"Failed to send event invite");const O=(F==null?void 0:F.sent)??0,B=(F==null?void 0:F.failed)??0;n({title:"Invites sent",description:`Sent: ${O}${B?` · Failed: ${B}`:""}`}),t(!1),x(""),m(""),d("")}catch(D){const R=D instanceof Error?D.message:"Send failed";n({title:"Send failed",description:R,variant:"destructive"})}finally{_(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(an,{children:["Send a beautiful event invitation to ",C.length," selected member",C.length===1?"":"s",".",r.length!==C.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[r.length-C.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{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(ls,{className:"h-4 w-4 animate-spin"})," Loading upcoming events..."]}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No upcoming events found. Create an event first."}):e.jsxs(Ds,{value:c,onValueChange:d,children:[e.jsx(Ps,{id:"event-select",children:e.jsx(Fs,{placeholder:"Pick an upcoming event..."})}),e.jsx(Ls,{children:a.map(D=>e.jsx(lt,{value:D.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:D.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[xUe(D.event_date),!D.is_published&&" · (Draft)"]})]})},D.id))})]})]}),N&&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(vn,{className:"h-4 w-4 text-primary"}),N.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:xUe(N.event_date)}),N.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:N.description})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(Ne,{id:"subject",placeholder:N?`You're invited: ${N.title}`:"You're invited to...",value:u,onChange:D=>m(D.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the default."})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(pr,{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:f,onChange:D=>x(D.target.value),rows:4}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This appears at the top of the email. Leave blank for a friendly default."})]}),e.jsxs("div",{className:"rounded-lg border p-3 bg-muted/20",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["RECIPIENTS (",C.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[C.slice(0,30).map(D=>e.jsx(Xe,{variant:"secondary",className:"text-xs font-normal",children:D.name||D.email},D.id)),C.length>30&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:["+",C.length-30," more"]})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsx(q,{onClick:A,disabled:y||!c||C.length===0,children:y?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4 mr-2"})," Send to ",C.length]})})]})]})}),e.jsx(el,{open:b,onOpenChange:j,children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Send event invite?"}),e.jsx(Ho,{children:N?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',N.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[C.length," member",C.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsxs(Oo,{onClick:E,children:[e.jsx(hn,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const Qps=()=>{const s=qr(),{user:t,isAdmin:r}=Cs(),{startImpersonation:n,isLoading:a}=Rxe(),{toast:i}=Ba(),[l,o]=k.useState([]),[c,d]=k.useState([]),[u,m]=k.useState([]),[f,x]=k.useState({}),[y,_]=k.useState(!0);k.useState({});const[b,j]=k.useState(!1),[N,C]=k.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[A,E]=k.useState(!1),[D,R]=k.useState(""),[F,O]=k.useState(1),[B,K]=k.useState(50),[Z,Q]=k.useState("all"),[W,te]=k.useState("all"),[ne,ae]=k.useState("all"),[ue,me]=k.useState("all"),[de,fe]=k.useState("all"),[je,xe]=k.useState(!1),[Ee,Me]=k.useState(!1),[Oe,Ie]=k.useState(!1),[ze,Ve]=k.useState(null),[Le,$e]=k.useState(null),[ve,Qe]=k.useState(!1),[we,nt]=k.useState({name:"",email:"",brokerage_id:"",phone:""}),[Se,Ge]=k.useState(null),[We,Ce]=k.useState(!1),[qe,et]=k.useState(""),[Ze,rt]=k.useState(!1),[ct,vt]=k.useState(!1),[kt,St]=k.useState(null),[Yt,es]=k.useState(""),[zs,sr]=k.useState(!1),[ms,gt]=k.useState(!1),[Ut,ht]=k.useState(null),[Jt,Ms]=k.useState(!1),[ts,Xs]=k.useState(!1),[js,$s]=k.useState(null),[Js,or]=k.useState(""),[Er,Sr]=k.useState(!1),[Gr,Yr]=k.useState({email:"",name:"",password:"",phone:""}),[Fn,sa]=k.useState(!1),[gs,mi]=k.useState(!1),[In,Br]=k.useState(""),[ps,Or]=k.useState(!1),[Qr,Tn]=k.useState(!1),[Qt,Re]=k.useState(""),[Ke,at]=k.useState(new Set),[Nt,Ft]=k.useState(!1),[qt,cs]=k.useState(!1),[it,Xt]=k.useState(null),[Bs,us]=k.useState(!1),[cr,Ar]=k.useState(null),[xr,Kr]=k.useState([]),[mn,pn]=k.useState([]),[wn,ca]=k.useState(!1),[Vi,so]=k.useState({});k.useEffect(()=>{!t||!r||(kn(),Fi())},[t,r]);const Ka=async()=>{try{const{data:It,error:ar}=await U.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(ar)throw ar;const Pr={};for(const Sn of It??[])Pr[Sn.brokerage_id]||(Pr[Sn.brokerage_id]=[]),Pr[Sn.brokerage_id].push(Sn.user_id);x(Pr)}catch(It){console.error("Error loading brokerage manager assignments:",It)}},kn=async()=>{try{_(!0);const{data:It,error:ar}=await U.functions.invoke("get-user-details");if(ar)throw ar;const Pr=It.users||[];o(Pr),m(It.brokerages||[]),await Ka();const Sn=Pr.filter(Vr=>Vr.roles.includes("assistant"));if(Sn.length>0){const Vr=Sn.map(Va=>Va.id),{data:na}=await U.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Vr);if(na&&na.length>0){const Va=[...new Set(na.map(fd=>fd.agent_id))],{data:ri}=await U.from("profiles").select("id, name, email").in("id",Va),An={};for(const fd of na){const Gh=ri==null?void 0:ri.find(Cu=>Cu.id===fd.agent_id);Gh&&(An[fd.assistant_id]={agent_name:Gh.name||"",agent_email:Gh.email||""})}so(An)}}}catch(It){console.error("Error loading members:",It),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{_(!1)}},Fi=async()=>{try{const{data:It,error:ar}=await U.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(ar)throw ar;d(It||[])}catch(It){console.error("Error loading apps:",It),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},zi=async It=>{if(!we.name.trim()||!we.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(we.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:Pr}=await U.from("profiles").update({name:we.name.trim(),email:we.email.trim(),brokerage_id:we.brokerage_id||null,phone:we.phone.trim()||null}).eq("id",It);if(Pr)throw Pr;i({title:"Success",description:"Member details updated successfully"}),Ve(null),kn()}catch(Pr){console.error("Error updating member:",Pr),i({title:"Error",description:Pr.message||"Failed to update member",variant:"destructive"})}},Qa=async It=>{try{const{data:{session:ar}}=await U.auth.getSession(),Pr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ar==null?void 0:ar.access_token}`},body:JSON.stringify({userId:It})}),Sn=await Pr.json();if(!Pr.ok)throw new Error(Sn.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(ar){console.error("Error resending welcome email:",ar),i({title:"Error",description:ar.message||"Failed to resend welcome email",variant:"destructive"})}},Hi=async(It,ar)=>{try{const{error:Pr}=await U.functions.invoke("send-password-reset",{body:{email:It,redirectTo:window.location.origin}});if(Pr)throw Pr;i({title:"Password Reset Sent",description:`Password reset email sent to ${ar}`})}catch(Pr){console.error("Error sending password reset:",Pr),i({title:"Error",description:Pr.message||"Failed to send password reset email",variant:"destructive"})}},Gi=async(It,ar)=>{if(confirm(`Are you sure you want to delete ${ar}? This action cannot be undone.`))try{const{data:{session:Pr}}=await U.auth.getSession(),Sn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pr==null?void 0:Pr.access_token}`},body:JSON.stringify({userId:It})}),Vr=await Sn.json();if(!Sn.ok)throw new Error(Vr.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),kn()}catch(Pr){console.error("Error deleting user:",Pr),i({title:"Error",description:Pr.message||"Failed to delete user",variant:"destructive"})}},Qn=async()=>{if(!N.email||!N.name||!N.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(N.role==="brokerage_manager"&&!N.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}j(!0);try{const{data:{session:It}}=await U.auth.getSession(),ar=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${It==null?void 0:It.access_token}`},body:JSON.stringify(N)}),Pr=await ar.json();if(!ar.ok)throw new Error(Pr.error||"Failed to create user");if(N.role&&N.role!=="user"&&Pr.userId){const Sn=N.role==="brokerage_manager"?N.brokerage_id:void 0;await vr(Pr.userId,N.role,"add",Sn)}i({title:"Success",description:`User ${N.email} created successfully`}),C({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),E(!1),kn()}catch(It){console.error("Error creating user:",It),i({title:"Error",description:It.message||"Failed to create user",variant:"destructive"})}finally{j(!1)}},vr=async(It,ar,Pr,Sn)=>{try{const{data:{session:Vr}}=await U.auth.getSession(),na={userId:It,role:ar,action:Pr};if(ar==="brokerage_manager"){if(!Sn){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}na.brokerageId=Sn}const Va=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vr==null?void 0:Vr.access_token}`},body:JSON.stringify(na)}),ri=await Va.json();if(!Va.ok)throw new Error(ri.error||"Failed to manage user role");i({title:"Success",description:`Role ${Pr==="add"?"added":"removed"} successfully`}),kn()}catch(Vr){console.error("Error managing user role:",Vr),i({title:"Error",description:Vr.message||"Failed to manage user role",variant:"destructive"})}},Ca=(It,ar)=>ar.length===0?!0:ar.some(Pr=>It.includes(Pr)),Ji=async(It,ar,Pr)=>{const Sn=`${It}-${ar.id}`;Ge(Sn);try{if(Pr){const Vr=l.find(Va=>Va.id===It),na=ar.required_tags.filter(Va=>Vr==null?void 0:Vr.tags.includes(Va));for(const Va of na){const{error:ri}=await U.from("user_tags").delete().eq("user_id",It).eq("tag",Va);if(ri)throw ri}i({title:"Access Removed",description:`Removed access to ${ar.name}`})}else if(ar.required_tags.length>0){const{error:Vr}=await U.from("user_tags").insert({user_id:It,tag:ar.required_tags[0]});if(Vr)throw Vr;i({title:"Access Granted",description:`Granted access to ${ar.name}`})}await kn()}catch(Vr){console.error("Error toggling access:",Vr),i({title:"Error",description:Vr.message||"Failed to update access",variant:"destructive"})}finally{Ge(null)}},Zo=async()=>{const It=qe.trim();if(!It){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(It.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(Pr=>Pr.name.toLowerCase()===It.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}rt(!0);try{const{error:Pr}=await U.from("brokerages").insert({name:It});if(Pr)throw Pr;i({title:"Success",description:`Brokerage "${It}" created successfully`}),et(""),Ce(!1),kn()}catch(Pr){console.error("Error creating brokerage:",Pr),i({title:"Error",description:Pr.message||"Failed to create brokerage",variant:"destructive"})}finally{rt(!1)}},vl=It=>{St(It),es(It.name),vt(!0)},vo=()=>{St(null),es(""),vt(!1)},hd=async()=>{if(!kt)return;const It=Yt.trim();if(!It){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(It.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}sr(!0);try{const{error:ar}=await U.from("brokerages").update({name:It}).eq("id",kt.id);if(ar)throw ar;i({title:"Success",description:"Brokerage updated successfully"}),vo(),kn()}catch(ar){console.error("Error updating brokerage:",ar),i({title:"Error",description:ar.message||"Failed to update brokerage",variant:"destructive"})}finally{sr(!1)}},ju=async(It,ar)=>{var Pr;if(!ar||typeof ar!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const Sn={userId:It,role:"brokerage_manager",action:"add",brokerageId:ar};console.debug("[assignManagerToBrokerage] payload",Sn);const{data:{session:Vr}}=await U.auth.getSession(),na=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vr==null?void 0:Vr.access_token}`},body:JSON.stringify(Sn)}),Va=await na.json();if(!na.ok&&!((Pr=Va.error)!=null&&Pr.includes("duplicate")))throw new Error(Va.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await kn()}catch(Sn){console.error("Error assigning manager:",Sn),i({title:"Error",description:Sn.message||"Failed to assign manager",variant:"destructive"})}},sp=It=>{ht(It),gt(!0)},Nu=async()=>{if(Ut){Ms(!0);try{const It=l.filter(Sn=>Sn.brokerage_id===Ut.id),{data:{session:ar}}=await U.auth.getSession();for(const Sn of It){const Vr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ar==null?void 0:ar.access_token}`},body:JSON.stringify({userId:Sn.id})});if(!Vr.ok){const na=await Vr.json();console.error(`Failed to delete user ${Sn.email}:`,na.error)}}const{error:Pr}=await U.from("brokerages").delete().eq("id",Ut.id);if(Pr)throw Pr;i({title:"Success",description:`Brokerage "${Ut.name}" and ${It.length} member(s) deleted`}),gt(!1),ht(null),kn()}catch(It){console.error("Error deleting brokerage:",It),i({title:"Error",description:It.message||"Failed to delete brokerage",variant:"destructive"})}finally{Ms(!1)}}},qh=It=>{$s(It),or(""),Xs(!0)},ku=()=>{$s(null),or(""),Xs(!1)},Cd=async It=>{try{const{error:ar}=await U.from("profiles").update({brokerage_id:null}).eq("id",It);if(ar)throw ar;i({title:"Success",description:"User removed from brokerage"}),kn()}catch(ar){console.error("Error removing user from brokerage:",ar),i({title:"Error",description:ar.message||"Failed to remove user",variant:"destructive"})}},vv=async(It,ar)=>{try{const{error:Pr}=await U.from("profiles").update({brokerage_id:ar}).eq("id",It);if(Pr)throw Pr;i({title:"Success",description:"User added to brokerage"}),kn()}catch(Pr){console.error("Error adding user to brokerage:",Pr),i({title:"Error",description:Pr.message||"Failed to add user",variant:"destructive"})}},gw=async()=>{if(!js||!Gr.email||!Gr.name||!Gr.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}sa(!0);try{const{data:{session:It}}=await U.auth.getSession(),ar=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${It==null?void 0:It.access_token}`},body:JSON.stringify({...Gr,brokerage_id:js.id,role:"user"})}),Pr=await ar.json();if(!ar.ok)throw new Error(Pr.error||"Failed to create agent");i({title:"Success",description:`Agent ${Gr.email} created successfully`}),Yr({email:"",name:"",password:"",phone:""}),Sr(!1),kn()}catch(It){console.error("Error creating agent:",It),i({title:"Error",description:It.message||"Failed to create agent",variant:"destructive"})}finally{sa(!1)}},Vh=It=>l.filter(ar=>ar.brokerage_id===It),K0=It=>{const ar=Vh(It);if(!Js)return ar;const Pr=Js.toLowerCase();return ar.filter(Sn=>Sn.name.toLowerCase().includes(Pr)||Sn.email.toLowerCase().includes(Pr))},Y0=It=>l.filter(ar=>ar.brokerage_id!==It),rp=l.filter(It=>{var Pr;if(D){const Sn=D.toLowerCase();if(!(It.name.toLowerCase().includes(Sn)||It.email.toLowerCase().includes(Sn)||((Pr=It.brokerage_name)==null?void 0:Pr.toLowerCase().includes(Sn))))return!1}if(Z==="claimed"&&!It.claimed||Z==="unclaimed"&&It.claimed||W!=="all"&&!It.roles.includes(W))return!1;const ar=It.is_trial||It.subscription_status==="trialing";if(ne==="trial"&&!ar||ne==="non-trial"&&ar||ue==="none"&&It.brokerage_id||ue!=="all"&&ue!=="none"&&It.brokerage_id!==ue)return!1;if(de!=="all"){if(!It.created_at)return!1;const Sn=parseInt(de,10),Vr=Date.now()-Sn*24*60*60*1e3;if(new Date(It.created_at).getTime(){var ar;return((ar=It.name)==null?void 0:ar.toLowerCase())||""},brokerage:It=>{var ar;return((ar=It.brokerage_name)==null?void 0:ar.toLowerCase())||""},status:It=>It.claimed?"active":"pending",role:It=>It.roles[0]||"",last_login:It=>It.last_sign_in_at?new Date(It.last_sign_in_at).getTime():null,created_at:It=>It.created_at?new Date(It.created_at).getTime():null}),vh=Hh.length,$p=B===0,Su=$p?1:Math.ceil(vh/B),Xo=$p?0:(F-1)*B,Pg=$p?vh:Xo+B,Xd=Hh.slice(Xo,Pg),Lg=It=>{R(It),O(1)},yw=It=>{K(It),O(1)},np=(It,ar)=>{It(ar),O(1)},qa=async(It,ar)=>{Me(!0);try{const Pr=l.find(Va=>Va.id===It);if(!Pr)return;const Sn=Pr.trial_expires_at?new Date(Pr.trial_expires_at):new Date,Vr=new Date(Sn.getTime()+ar*24*60*60*1e3),{error:na}=await U.from("profiles").update({trial_expires_at:Vr.toISOString()}).eq("id",It);if(na)throw na;i({title:"Trial Extended",description:`Trial extended by ${ar} days`}),kn()}catch(Pr){console.error("Error extending trial:",Pr),i({title:"Error",description:Pr.message||"Failed to extend trial",variant:"destructive"})}finally{Me(!1)}},Z0=async It=>{Ie(!0);try{const{error:ar}=await U.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",It);if(ar)throw ar;i({title:"Account Converted",description:"User has been converted to a full account"}),kn(),Rx()}catch(ar){console.error("Error converting trial:",ar),i({title:"Error",description:ar.message||"Failed to convert account",variant:"destructive"})}finally{Ie(!1)}},[X0,Mm]=k.useState(!1),Im=async(It,ar)=>{if(confirm(`Revert this user to a ${ar}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){Mm(!0);try{const Pr=new Date,Sn=new Date(Pr.getTime()+ar*24*60*60*1e3),{error:Vr}=await U.from("profiles").update({is_trial:!0,trial_started_at:Pr.toISOString(),trial_expires_at:Sn.toISOString(),trial_claimed_at:Pr.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",It);if(Vr)throw Vr;i({title:"Reverted to Trial",description:`User is now on a ${ar}-day free trial.`}),kn()}catch(Pr){console.error("Error reverting to trial:",Pr),i({title:"Error",description:Pr.message||"Failed to revert to trial",variant:"destructive"})}finally{Mm(!1)}}},ff=async It=>{ca(!0);try{const{data:ar}=await U.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",It);if(ar&&ar.length>0){const Sn=ar.map(na=>na.assistant_id),{data:Vr}=await U.from("profiles").select("id, name, email").in("id",Sn);Kr(ar.map(na=>{const Va=Vr==null?void 0:Vr.find(ri=>ri.id===na.assistant_id);return{id:na.id,assistant_id:na.assistant_id,assistant_name:(Va==null?void 0:Va.name)||"Unknown",assistant_email:(Va==null?void 0:Va.email)||"",permissions:na.permissions||{}}}))}else Kr([]);const{data:Pr}=await U.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",It);if(Pr&&Pr.length>0){const Sn=Pr.map(na=>na.agent_id),{data:Vr}=await U.from("profiles").select("id, name, email").in("id",Sn);pn(Pr.map(na=>{const Va=Vr==null?void 0:Vr.find(ri=>ri.id===na.agent_id);return{id:na.id,agent_id:na.agent_id,agent_name:(Va==null?void 0:Va.name)||"Unknown",agent_email:(Va==null?void 0:Va.email)||"",permissions:na.permissions||{}}}))}else pn([])}catch(ar){console.error("Error loading assistant data:",ar)}finally{ca(!1)}},Up=It=>{$e(It),nt({name:It.name,email:It.email,brokerage_id:It.brokerage_id||"",phone:It.phone||""}),Qe(!0),ff(It.id)},Rx=()=>{$e(null),Qe(!1),nt({name:"",email:"",brokerage_id:"",phone:""})},Q1=async()=>{Le&&(await zi(Le.id),Rx())},pf=It=>{at(ar=>{const Pr=new Set(ar);return Pr.has(It)?Pr.delete(It):Pr.add(It),Pr})},Pm=()=>{if(Ke.size===Xd.length&&Xd.every(It=>Ke.has(It.id))){const It=new Set(Ke);Xd.forEach(ar=>It.delete(ar.id)),at(It)}else{const It=new Set(Ke);Xd.forEach(ar=>It.add(ar.id)),at(It)}},ap=()=>{at(new Set)},Q0=async()=>{if(Ke.size===0)return;Ft(!0);let It=0,ar=0;try{const{data:{session:Pr}}=await U.auth.getSession();for(const Sn of Ke)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pr==null?void 0:Pr.access_token}`},body:JSON.stringify({userId:Sn})})).ok?It++:ar++}catch{ar++}i({title:"Bulk Email Complete",description:`Sent ${It} emails${ar>0?`, ${ar} failed`:""}`}),ap()}catch(Pr){i({title:"Error",description:Pr.message||"Failed to send emails",variant:"destructive"})}finally{Ft(!1)}},J1=async()=>{if(Ke.size===0)return;Ft(!0);let It=0,ar=0;try{const{data:{session:Pr}}=await U.auth.getSession();for(const Sn of Ke)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pr==null?void 0:Pr.access_token}`},body:JSON.stringify({userId:Sn})})).ok?It++:ar++}catch{ar++}i({title:"Bulk Password Reset Complete",description:`Sent ${It} reset emails${ar>0?`, ${ar} failed`:""}`}),ap()}catch(Pr){i({title:"Error",description:Pr.message||"Failed to send password reset emails",variant:"destructive"})}finally{Ft(!1)}},md=async()=>{if(Ke.size===0)return;const It=l.filter(Vr=>Ke.has(Vr.id)).map(Vr=>Vr.name).slice(0,5).join(", "),ar=Ke.size>5?` and ${Ke.size-5} more`:"";if(!confirm(`Are you sure you want to delete ${Ke.size} users (${It}${ar})? This action cannot be undone.`))return;Ft(!0);let Pr=0,Sn=0;try{const{data:{session:Vr}}=await U.auth.getSession();for(const na of Ke)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vr==null?void 0:Vr.access_token}`},body:JSON.stringify({userId:na})})).ok?Pr++:Sn++}catch{Sn++}i({title:"Bulk Delete Complete",description:`Deleted ${Pr} users${Sn>0?`, ${Sn} failed`:""}`}),ap(),kn()}catch(Vr){i({title:"Error",description:Vr.message||"Failed to delete users",variant:"destructive"})}finally{Ft(!1)}},_c=async()=>{cs(!0);try{const{data:{session:It}}=await U.auth.getSession(),ar=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${It==null?void 0:It.access_token}`}});if(!ar.ok){const Sn=await ar.json();throw new Error(Sn.error||"Failed to sync phones")}const Pr=await ar.json();i({title:"Phone Sync Complete",description:`Pulled ${Pr.summary.pulledFromGHL} from GHL, pushed ${Pr.summary.pushedToGHL} to GHL, ${Pr.summary.alreadySynced} already synced`}),kn()}catch(It){i({title:"Error",description:It.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{cs(!1)}},Lm=async(It,ar)=>{Xt(It);try{const{data:{session:Pr}}=await U.auth.getSession(),{data:Sn}=await U.from("profiles").select("phone").eq("id",It).single(),Vr=(Sn==null?void 0:Sn.phone)||"",na=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pr==null?void 0:Pr.access_token}`},body:JSON.stringify({email:ar,action:"update",phone:Vr||void 0})});if(!na.ok){const ri=await na.json();throw new Error(ri.error||"Failed to sync with GHL")}const Va=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(ar)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Vr?`Phone ${Vr} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),kn()}catch(Pr){i({title:"Error",description:Pr.message||"Failed to sync phone",variant:"destructive"})}finally{Xt(null)}},Mc=async It=>{await n(It)},Dm=()=>{if(Ke.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const It=l.filter(ri=>Ke.has(ri.id)),ar=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],Pr=It.map(ri=>[ri.name,ri.email,ri.phone||"",ri.brokerage_name||"",ri.roles.join("; "),ri.claimed?"Claimed":"Unclaimed",new Date(ri.created_at).toLocaleDateString()]),Sn=[ar.join(","),...Pr.map(ri=>ri.map(An=>`"${(An||"").replace(/"/g,'""')}"`).join(","))].join(` `),Vr=new Blob([Sn],{type:"text/csv"}),na=URL.createObjectURL(Vr),Va=document.createElement("a");Va.href=na,Va.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Va.click(),URL.revokeObjectURL(na),i({title:"Export complete",description:`Exported ${It.length} member(s)`})},xf=()=>{if(rp.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const It=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],ar=rp.map(ri=>[ri.name,ri.email,ri.phone||"",ri.brokerage_name||"",ri.roles.join("; "),ri.claimed?"Claimed":"Unclaimed",ri.created_at?new Date(ri.created_at).toLocaleDateString():""]),Pr=[It.join(","),...ar.map(ri=>ri.map(An=>`"${(An||"").replace(/"/g,'""')}"`).join(","))].join(` `),Sn=new Blob([Pr],{type:"text/csv"}),Vr=URL.createObjectURL(Sn),na=document.createElement("a"),Va=de!=="all"?`-last-${de}days`:"";na.href=Vr,na.download=`members-export${Va}-${new Date().toISOString().split("T")[0]}.csv`,na.click(),URL.revokeObjectURL(Vr),i({title:"Export complete",description:`Exported ${rp.length} member(s)`})};return y?e.jsx(ws,{title:"Members",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(ws,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Member Management",description:"Manage users, roles, and permissions"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(q,{size:"sm",variant:"outline",onClick:_c,disabled:qt,children:[qt?e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Mn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:qt?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:qt?"Syncing...":"Sync GHL"})]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>mi(!0),children:[e.jsx(s2,{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(vs,{open:A,onOpenChange:E,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{size:"sm",children:[e.jsx(xl,{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(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create New User"}),e.jsx(an,{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(ce,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",placeholder:"John Doe",value:N.name,onChange:It=>C({...N,name:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",placeholder:"john@example.com",value:N.email,onChange:It=>C({...N,email:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"password",children:"Password"}),e.jsx(Ne,{id:"password",type:"password",placeholder:"Min 6 characters",value:N.password,onChange:It=>C({...N,password:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(Ne,{id:"phone",type:"tel",placeholder:"555-123-4567",value:N.phone,onChange:It=>C({...N,phone:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{htmlFor:"brokerage",children:["Brokerage",N.role==="brokerage_manager"?" (required)":""]}),e.jsxs(Ds,{value:N.brokerage_id||"none",onValueChange:It=>C({...N,brokerage_id:It==="none"?"":It}),children:[e.jsx(Ps,{id:"brokerage",children:e.jsx(Fs,{placeholder:N.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"None"}),u.map(It=>e.jsx(lt,{value:It.id,children:It.name},It.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"role",children:"Role"}),e.jsxs(Ds,{value:N.role,onValueChange:It=>C({...N,role:It}),children:[e.jsx(Ps,{id:"role",children:e.jsx(Fs,{placeholder:"Select role"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"user",children:"User"}),e.jsx(lt,{value:"moderator",children:"Moderator"}),e.jsx(lt,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(lt,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(Ds,{value:N.trial_days||"none",onValueChange:It=>C({...N,trial_days:It==="none"?"":It}),children:[e.jsx(Ps,{id:"trial_days",children:e.jsx(Fs,{placeholder:"No trial (full access)"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No trial (full access)"}),e.jsx(lt,{value:"7",children:"7-day trial"}),e.jsx(lt,{value:"30",children:"30-day trial"}),e.jsx(lt,{value:"60",children:"60-day trial"}),e.jsx(lt,{value:"90",children:"90-day trial"}),e.jsx(lt,{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(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(q,{onClick:Qn,disabled:b,children:b?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(ta,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"members",children:"Members"}),e.jsx(rs,{value:"brokerages",children:"Brokerages"}),e.jsx(rs,{value:"teams",children:"Teams"}),e.jsx(rs,{value:"trials",children:"Trial Users"}),e.jsx(rs,{value:"access",children:"Access Matrix"}),e.jsx(rs,{value:"celebrations",children:"Celebrations"}),e.jsx(rs,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(fs,{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(_n,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search members...",value:D,onChange:It=>Lg(It.target.value),className:"pl-10 h-9"})]}),e.jsxs(Ds,{value:Z,onValueChange:It=>np(Q,It),children:[e.jsx(Ps,{className:"w-[130px] h-9",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Status"}),e.jsx(lt,{value:"claimed",children:"Active"}),e.jsx(lt,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(Ds,{value:W,onValueChange:It=>np(te,It),children:[e.jsx(Ps,{className:"w-[130px] h-9",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Roles"}),e.jsx(lt,{value:"admin",children:"Admin"}),e.jsx(lt,{value:"brokerage_manager",children:"Manager"}),e.jsx(lt,{value:"assistant",children:"Assistant"}),e.jsx(lt,{value:"user",children:"User"})]})]}),e.jsxs(Ds,{value:ne,onValueChange:It=>np(ae,It),children:[e.jsx(Ps,{className:"w-[130px] h-9",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Users"}),e.jsx(lt,{value:"trial",children:"Trial Only"}),e.jsx(lt,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(Ds,{value:ue,onValueChange:It=>np(me,It),children:[e.jsx(Ps,{className:"w-[150px] h-9",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Brokerages"}),e.jsx(lt,{value:"none",children:"No Brokerage"}),u.map(It=>e.jsx(lt,{value:It.id,children:It.name},It.id))]})]}),e.jsxs(Ds,{value:de,onValueChange:It=>np(fe,It),children:[e.jsx(Ps,{className:"w-[150px] h-9",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"Any Join Date"}),e.jsx(lt,{value:"30",children:"Joined Last 30 Days"}),e.jsx(lt,{value:"60",children:"Joined Last 60 Days"}),e.jsx(lt,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(q,{size:"sm",variant:"outline",className:"h-9",onClick:xf,title:"Export currently filtered members to CSV",children:[e.jsx(li,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(D||Z!=="all"||W!=="all"||ne!=="all"||ue!=="all"||de!=="all")&&e.jsxs(q,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{R(""),Q("all"),te("all"),ae("all"),me("all"),fe("all"),O(1)},children:[e.jsx($r,{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:$p?`Showing all ${vh} members`:`Showing ${Xo+1}-${Math.min(Pg,vh)} of ${vh} members`}),e.jsxs(Ds,{value:B.toString(),onValueChange:It=>yw(Number(It)),children:[e.jsx(Ps,{className:"h-9 w-[110px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"50",children:"50 / page"}),e.jsx(lt,{value:"100",children:"100 / page"}),e.jsx(lt,{value:"250",children:"250 / page"}),e.jsx(lt,{value:"0",children:"All"})]})]})]})]}),Ke.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[Xd.length>0&&Xd.every(It=>Ke.has(It.id))&&Hh.length>Ke.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 ",Ke.size," on this page are selected."]}),e.jsxs(q,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>at(new Set(Hh.map(It=>It.id))),children:["Select all ",Hh.length," filtered members"]})]}),Hh.length>0&&Ke.size===Hh.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Hh.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(zj,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[Ke.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(q,{size:"sm",variant:"outline",onClick:Q0,disabled:Nt,children:[Nt?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Ks,{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(q,{size:"sm",variant:"outline",onClick:J1,disabled:Nt,children:[Nt?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(gg,{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(q,{size:"sm",variant:"outline",onClick:()=>xe(!0),disabled:Nt,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(gF,{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(q,{size:"sm",variant:"outline",onClick:Dm,children:[e.jsx(li,{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(q,{size:"sm",variant:"destructive",onClick:md,disabled:Nt,children:[Nt?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(zr,{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(q,{size:"sm",variant:"ghost",onClick:ap,disabled:Nt,children:e.jsx($r,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"w-[50px]",children:e.jsx(Ri,{checked:Xd.length>0&&Xd.every(It=>Ke.has(It.id)),onCheckedChange:Pm,"aria-label":"Select all on page"})}),e.jsx(mc,{sortKey:"name",currentSortKey:Xu,currentDirection:Bp,onSort:co,children:"Name"}),e.jsx(mc,{sortKey:"brokerage",currentSortKey:Xu,currentDirection:Bp,onSort:co,children:"Brokerage"}),e.jsx(mc,{sortKey:"status",currentSortKey:Xu,currentDirection:Bp,onSort:co,children:"Status"}),e.jsx(mc,{sortKey:"role",currentSortKey:Xu,currentDirection:Bp,onSort:co,children:"Role"}),e.jsx(mc,{sortKey:"last_login",currentSortKey:Xu,currentDirection:Bp,onSort:co,children:"Last Login"}),e.jsx(mc,{sortKey:"created_at",currentSortKey:Xu,currentDirection:Bp,onSort:co,children:"Member Since"}),e.jsx(At,{className:"w-[100px]"})]})}),e.jsx(ha,{children:Xd.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):Xd.map(It=>e.jsxs(Ws,{className:`hover:bg-muted/30 ${Ke.has(It.id)?"bg-primary/5":""}`,children:[e.jsx(xt,{children:e.jsx(Ri,{checked:Ke.has(It.id),onCheckedChange:()=>pf(It.id),"aria-label":`Select ${It.name}`})}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>Up(It),className:"text-primary hover:underline font-medium text-left",children:It.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:It.email})]})}),e.jsx(xt,{className:"text-muted-foreground",children:It.brokerage_name||"—"}),e.jsx(xt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const ar=It.trial_expires_at||It.subscription_end_date;if((It.is_trial||It.subscription_status==="trialing")&&ar){const Sn=Math.ceil((new Date(ar).getTime()-Date.now())/864e5),Vr=Sn<=0,na=Sn<=3;return e.jsx(Xe,{variant:"outline",className:zt("w-fit",Vr?"border-destructive text-destructive":na?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Vr?"Trial Expired":`Trial · ${Sn}d left`})}return e.jsx(Xe,{variant:It.claimed?"default":"secondary",className:It.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:It.claimed?"Active":"Pending"})})()})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col",children:[It.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:It.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),It.roles.includes("assistant")&&Vi[It.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Vi[It.id].agent_name||Vi[It.id].agent_email]})]})}),e.jsx(xt,{className:"text-muted-foreground",children:It.last_sign_in_at?new Date(It.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(xt,{className:"text-muted-foreground",children:It.created_at?new Date(It.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{Ar(It),us(!0)},title:"Send celebration",children:e.jsx(ph,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Up(It),title:"Edit member",children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Lm(It.id,It.email),disabled:it===It.id,title:"Sync phone with GHL",children:it===It.id?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Mn,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Qa(It.id),title:"Resend welcome email",children:e.jsx(Ks,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Hi(It.email,It.name),title:"Send password reset",children:e.jsx(PE,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Mc(It.id),disabled:a||It.id===(t==null?void 0:t.id),title:It.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${It.name}`,children:a?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(RE,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Gi(It.id,It.name),title:"Delete user",children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},It.id))})]})}),Su>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 ",F," of ",Su]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"outline",size:"sm",onClick:()=>O(1),disabled:F===1,children:"First"}),e.jsx(q,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(It=>Math.max(1,It-1)),disabled:F===1,children:e.jsx(jl,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,Su)},(It,ar)=>{let Pr;return Su<=5||F<=3?Pr=ar+1:F>=Su-2?Pr=Su-4+ar:Pr=F-2+ar,e.jsx(q,{variant:F===Pr?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>O(Pr),children:Pr},Pr)})}),e.jsx(q,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(It=>Math.min(Su,It+1)),disabled:F===Su,children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>O(Su),disabled:F===Su,children:"Last"})]})]})]}),e.jsx(vs,{open:ve,onOpenChange:Qe,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Edit Member"}),e.jsx(an,{children:"Update member details, roles, and app access"})]}),Le&&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(ce,{htmlFor:"edit-name",children:"Name"}),e.jsx(Ne,{id:"edit-name",value:we.name,onChange:It=>nt({...we,name:It.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"edit-email",children:"Email"}),e.jsx(Ne,{id:"edit-email",type:"email",value:we.email,onChange:It=>nt({...we,email:It.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(ce,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(Ne,{id:"edit-phone",type:"tel",value:we.phone,onChange:It=>nt({...we,phone:It.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(Ds,{value:we.brokerage_id||"none",onValueChange:It=>nt({...we,brokerage_id:It==="none"?"":It}),children:[e.jsx(Ps,{id:"edit-brokerage",children:e.jsx(Fs,{placeholder:"Select brokerage"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"None"}),u.map(It=>e.jsx(lt,{value:It.id,children:It.name},It.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:[Le.roles.map(It=>e.jsxs(Xe,{variant:"default",className:"gap-1",children:[e.jsx(Oh,{className:"h-3 w-3"}),It,It==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>vr(Le.id,It,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx($r,{className:"h-3 w-3"})})]},It)),Le.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(Ds,{onValueChange:It=>vr(Le.id,It,"add"),children:[e.jsx(Ps,{className:"w-[200px]",children:e.jsx(Fs,{placeholder:"Add role..."})}),e.jsxs(Ls,{children:[!Le.roles.includes("admin")&&e.jsx(lt,{value:"admin",children:"Admin"}),!Le.roles.includes("user")&&e.jsx(lt,{value:"user",children:"User"})]})]}),!Le.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"})]}),(xr.length>0||mn.length>0||Le.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(Dr,{className:"h-4 w-4"}),"Assistant Relationships"]}),wn?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[xr.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Has assistants:"}),xr.map(It=>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:It.assistant_name}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:It.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(It.permissions).filter(([,ar])=>ar).map(([ar])=>e.jsx(Xe,{variant:"secondary",className:"text-[10px] capitalize",children:ar},ar))})]},It.id))]}),mn.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:"}),mn.map(It=>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:It.agent_name}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:It.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(It.permissions).filter(([,ar])=>ar).map(([ar])=>e.jsx(Xe,{variant:"secondary",className:"text-[10px] capitalize",children:ar},ar))})]},It.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(It=>{const ar=Ca(Le.tags,It.required_tags),Pr=`${Le.id}-${It.id}`,Sn=Se===Pr,Vr=It.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:It.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:It.name}),Vr&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:Sn?e.jsx(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Vr?e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(Rr,{checked:ar,onCheckedChange:()=>Ji(Le.id,It,ar)})})]},It.id)})})]}),(Le.is_trial||Le.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(jn,{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:[Le.trial_expires_at&&e.jsx(pUe,{expiresAt:Le.trial_expires_at}),!Le.trial_expires_at&&Le.subscription_status==="trialing"&&Le.subscription_end_date&&e.jsx(pUe,{expiresAt:Le.subscription_end_date})]}),(Le.trial_expires_at||Le.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Le.trial_expires_at||Le.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>qa(Le.id,7),disabled:Ee,children:[e.jsx(Gj,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>qa(Le.id,14),disabled:Ee,children:[e.jsx(Gj,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>qa(Le.id,30),disabled:Ee,children:[e.jsx(Gj,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(q,{size:"sm",variant:"default",onClick:()=>Z0(Le.id),disabled:Oe,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(M1,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Le.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Le.trial_started_at).toLocaleDateString(),Le.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Le.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Le.is_trial||Le.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(jn,{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(It=>e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>Im(Le.id,It),disabled:X0,children:[e.jsx(Gj,{className:"h-4 w-4 mr-1"}),It,"-day trial"]},It))})]})]}),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:[Le.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Le.email_confirmed_at).toLocaleString()]}),Le.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Le.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Le.created_at).toLocaleString()]})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:Rx,children:"Cancel"}),e.jsx(q,{onClick:Q1,children:"Save Changes"})]})]})}),e.jsxs(fs,{value:"access",children:[c.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx(q,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Member Access Matrix"}),e.jsx(Ur,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents by name or email...",value:D,onChange:It=>{R(It.target.value),O(1)},className:"pl-9"})]})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left p-4 font-semibold sticky left-0 bg-card z-10",children:"Member"}),c.map(It=>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:It.icon}),e.jsx("span",{className:"text-sm",children:It.name})]})},It.id))]})}),e.jsxs("tbody",{children:[Xd.map(It=>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:It.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:It.email})]})}),c.map(ar=>{const Pr=Ca(It.tags,ar.required_tags),Sn=`${It.id}-${ar.id}`,Vr=Se===Sn;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Vr?e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(Rr,{checked:Pr,onCheckedChange:()=>Ji(It.id,ar,Pr),disabled:ar.required_tags.length===0})})},ar.id)})]},It.id)),Xd.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"})})]})]})}),Su>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 ",Xo+1,"-",Math.min(Pg,vh)," of ",vh," • Page ",F," of ",Su]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(It=>Math.max(1,It-1)),disabled:F===1,children:e.jsx(jl,{className:"h-4 w-4"})}),e.jsx(q,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(It=>Math.min(Su,It+1)),disabled:F===Su,children:e.jsx(Ia,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(q,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(fs,{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(_n,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search brokerages...",value:In,onChange:It=>Br(It.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(It=>It.name.toLowerCase().includes(In.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>{const It=[];for(const Va of u){const ri=f[Va.id]??[];for(const An of ri){const fd=l.find(Gh=>Gh.id===An);if(fd){const Gh=(fd.name||"").trim().split(/\s+/),Cu=Gh[0]||"",Ox=Gh.slice(1).join(" ")||"";It.push({firstName:Cu,lastName:Ox,email:fd.email,brokerageName:Va.name})}}}if(It.length===0){i({title:"No managers found to export"});return}const Pr=[["First Name","Last Name","Email","Brokerage Name"].join(","),...It.map(Va=>[Va.firstName,Va.lastName,Va.email,Va.brokerageName].map(ri=>`"${(ri||"").replace(/"/g,'""')}"`).join(","))].join(` `),Sn=new Blob([Pr],{type:"text/csv"}),Vr=URL.createObjectURL(Sn),na=document.createElement("a");na.href=Vr,na.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,na.click(),URL.revokeObjectURL(Vr),i({title:`Exported ${It.length} managers`})},children:[e.jsx(li,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(vs,{open:We,onOpenChange:Ce,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{size:"sm",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create New Brokerage"}),e.jsx(an,{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(ce,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(Ne,{id:"brokerage-name",placeholder:"Enter brokerage name",value:qe,onChange:It=>et(It.target.value),maxLength:100})]})}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>Ce(!1),children:"Cancel"}),e.jsx(q,{onClick:Zo,disabled:Ze,children:Ze?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(At,{className:"font-semibold",children:"Manager(s)"}),e.jsx(At,{className:"font-semibold",children:"Agents"}),e.jsx(At,{className:"w-[150px]"})]})}),e.jsx(ha,{children:(()=>{const It=u.filter(ar=>ar.name.toLowerCase().includes(In.toLowerCase()));return It.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:In?"No brokerages match your search":"No brokerages found"})}):It.map(ar=>{const Pr=l.filter(Va=>Va.brokerage_id===ar.id),Vr=(f[ar.id]??[]).map(Va=>l.find(ri=>ri.id===Va)).filter(Boolean),na=Pr.length;return e.jsxs(Ws,{className:"hover:bg-muted/30",children:[e.jsx(xt,{children:e.jsx("button",{onClick:()=>vl(ar),className:"text-primary hover:underline font-medium",children:ar.name})}),e.jsx(xt,{children:Vr.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Vr.map(Va=>e.jsx(Xe,{variant:"secondary",className:"text-xs",children:Va.name},Va.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(xt,{children:[na," member",na!==1?"s":""]}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(q,{size:"sm",variant:"outline",className:"h-8",onClick:()=>qh(ar),children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>vl(ar),title:"Edit brokerage",children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>sp(ar),title:"Delete brokerage",children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},ar.id)})})()})]})}),e.jsx(vs,{open:ct,onOpenChange:vt,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Edit Brokerage"}),e.jsx(an,{children:"Update brokerage details and manage managers"})]}),kt&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(Ne,{id:"edit-brokerage-name",value:Yt,onChange:It=>es(It.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{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 ar=(f[kt.id]??[]).map(Pr=>l.find(Sn=>Sn.id===Pr)).filter(Boolean);return ar.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):ar.map(Pr=>e.jsxs(Xe,{variant:"default",className:"gap-1",children:[e.jsx(Oh,{className:"h-3 w-3"}),Pr.name,e.jsx("button",{onClick:()=>vr(Pr.id,"brokerage_manager","remove",kt.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx($r,{className:"h-3 w-3"})})]},Pr.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(sl,{open:ps,onOpenChange:Or,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",role:"combobox","aria-expanded":ps,className:"w-full justify-between",children:["Search for a member...",e.jsx(_n,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-full p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search by name or email..."}),e.jsxs(kg,{className:"max-h-[200px]",children:[e.jsx(Sg,{children:"No members found."}),e.jsx(Cg,{children:(()=>{const It=new Set(f[kt.id]??[]);return l.filter(ar=>!It.has(ar.id)&&(r||ar.brokerage_id===kt.id)).map(ar=>e.jsxs(Sp,{value:`${ar.name} ${ar.email}`,onSelect:()=>{ju(ar.id,kt.id),Or(!1)},children:[ar.name," (",ar.email,")"]},ar.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(It=>It.brokerage_id===kt.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(It=>It.brokerage_id===kt.id).map(It=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:It.name}),It.roles.includes("brokerage_manager")&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Manager"})]},It.id))})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:vo,children:"Cancel"}),e.jsx(q,{onClick:hd,disabled:zs,children:zs?"Saving...":"Save Changes"})]})]})}),e.jsx(vs,{open:ms,onOpenChange:gt,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(an,{children:['Are you sure you want to delete "',Ut==null?void 0:Ut.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 "',Ut==null?void 0:Ut.name,'"']}),e.jsxs("li",{children:["All ",l.filter(It=>It.brokerage_id===(Ut==null?void 0:Ut.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>gt(!1),children:"Cancel"}),e.jsx(q,{variant:"destructive",onClick:Nu,disabled:Jt,children:Jt?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(vs,{open:ts,onOpenChange:Xs,children:e.jsxs(ys,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-5 w-5"}),"Manage ",js==null?void 0:js.name]}),e.jsx(an,{children:"Add, remove, or manage users in this brokerage"})]}),js&&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(_n,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search members...",value:Js,onChange:It=>or(It.target.value),className:"pl-10 h-9"})]}),e.jsxs(vs,{open:Er,onOpenChange:Sr,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{size:"sm",children:[e.jsx(xl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Add New Agent"}),e.jsxs(an,{children:["Create a new agent for ",js.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"agent-name",children:"Name"}),e.jsx(Ne,{id:"agent-name",placeholder:"John Doe",value:Gr.name,onChange:It=>Yr({...Gr,name:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"agent-email",children:"Email"}),e.jsx(Ne,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Gr.email,onChange:It=>Yr({...Gr,email:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"agent-password",children:"Password"}),e.jsx(Ne,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Gr.password,onChange:It=>Yr({...Gr,password:It.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(Ne,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Gr.phone,onChange:It=>Yr({...Gr,phone:It.target.value})})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>Sr(!1),children:"Cancel"}),e.jsx(q,{onClick:gw,disabled:Fn,children:Fn?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(sl,{open:Qr,onOpenChange:Tn,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",role:"combobox","aria-expanded":Qr,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(_n,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-[300px] p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search users...",value:Qt,onValueChange:Re}),e.jsxs(kg,{children:[e.jsx(Sg,{children:"No users found."}),e.jsx(Cg,{children:Y0(js.id).filter(It=>Qt===""||It.name.toLowerCase().includes(Qt.toLowerCase())||It.email.toLowerCase().includes(Qt.toLowerCase())).map(It=>e.jsxs(Sp,{value:`${It.name} ${It.email}`,onSelect:()=>{vv(It.id,js.id),Tn(!1),Re("")},children:[It.name," (",It.email,")"]},It.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(At,{className:"font-semibold",children:"Name"}),e.jsx(At,{className:"font-semibold",children:"Email"}),e.jsx(At,{className:"font-semibold",children:"Status"}),e.jsx(At,{className:"font-semibold",children:"Role"}),e.jsx(At,{className:"w-[120px]"})]})}),e.jsx(ha,{children:K0(js.id).length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:Js?"No matching members found":"No members in this brokerage"})}):K0(js.id).map(It=>e.jsxs(Ws,{className:"hover:bg-muted/30",children:[e.jsx(xt,{className:"font-medium",children:It.name}),e.jsx(xt,{className:"text-muted-foreground",children:It.email}),e.jsx(xt,{children:It.claimed?e.jsx(Xe,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(Xe,{variant:"secondary",children:"Pending"})}),e.jsx(xt,{children:It.roles.includes("brokerage_manager")?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Oh,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!It.claimed&&e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Qa(It.id),title:"Resend welcome email",children:e.jsx(Ks,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Cd(It.id),title:"Remove from brokerage",children:e.jsx($r,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Mc(It.id),disabled:a||It.id===(t==null?void 0:t.id),title:It.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${It.name}`,children:a?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(RE,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Gi(It.id,It.name),title:"Delete user",children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},It.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Vh(js.id).length," total member",Vh(js.id).length!==1?"s":""," •",Vh(js.id).filter(It=>It.roles.includes("brokerage_manager")).length," manager",Vh(js.id).filter(It=>It.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(fn,{children:e.jsx(q,{variant:"outline",onClick:ku,children:"Close"})})]})})]}),e.jsx(fs,{value:"teams",children:e.jsx(Zps,{})}),e.jsx(fs,{value:"trials",children:e.jsx(Hps,{})}),e.jsx(fs,{value:"celebrations",children:e.jsx(Vps,{})}),e.jsx(fs,{value:"deletions",children:e.jsx(Wps,{})})]})]}),e.jsx(fft,{open:gs,onOpenChange:mi,brokerages:u,onSuccess:kn}),cr&&e.jsx(pft,{open:Bs,onOpenChange:It=>{us(It),It||Ar(null)},userId:cr.id,userName:cr.name}),e.jsx(Xps,{open:je,onOpenChange:xe,recipients:l.filter(It=>Ke.has(It.id)).map(It=>({id:It.id,name:It.name,email:It.email}))})]})},Jps=()=>{const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,m]=k.useState(""),[f,x]=k.useState("");k.useEffect(()=>{y()},[]);const y=async()=>{const{data:E,error:D}=await U.from("invite_codes").select("*").order("created_at",{ascending:!1});D?(he.error("Failed to load invite codes"),console.error(D)):t(E||[]),n(!1)},_=async E=>{if(E.preventDefault(),!l.trim()){he.error("Please enter a code");return}i(!0);const{error:D}=await U.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:f?parseInt(f):null});D?D.code==="23505"?he.error("This code already exists"):(he.error("Failed to create invite code"),console.error(D)):(he.success("Invite code created"),o(""),d(""),m(""),x(""),y()),i(!1)},b=async(E,D)=>{const{error:R}=await U.from("invite_codes").update({is_active:!D}).eq("id",E);R?he.error("Failed to update code"):t(s.map(F=>F.id===E?{...F,is_active:!D}:F))},j=async E=>{const{error:D}=await U.from("invite_codes").delete().eq("id",E);D?he.error("Failed to delete code"):(he.success("Code deleted"),t(s.filter(R=>R.id!==E)))},N="https://dashboard.relevelup.com",C=E=>{const D=`${N}/join?code=${E}`;navigator.clipboard.writeText(D),he.success("Link copied to clipboard")},A=`${N}/join`;return e.jsx(ws,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Create New Code"}),e.jsxs(Ur,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:A})]})]}),e.jsx(Pe,{children:e.jsxs("form",{onSubmit:_,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"code",children:"Code"}),e.jsx(Ne,{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(ce,{htmlFor:"description",children:"Description (optional)"}),e.jsx(Ne,{id:"description",placeholder:"For marketing campaign",value:c,onChange:E=>d(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(Ne,{id:"maxUses",type:"number",placeholder:"Unlimited",value:u,onChange:E=>m(E.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(Ne,{id:"trialDays",type:"number",placeholder:"None",value:f,onChange:E=>x(E.target.value),className:"w-28"})]}),e.jsxs(q,{type:"submit",disabled:a,children:[a?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Active Codes"})}),e.jsx(Pe,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx("p",{className:"text-center py-8 text-muted-foreground",children:"No invite codes yet"}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Code"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Uses"}),e.jsx(At,{children:"Trial"}),e.jsx(At,{children:"Created"}),e.jsx(At,{children:"Active"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(E=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-mono font-medium",children:E.code}),e.jsx(xt,{className:"text-muted-foreground",children:E.description||"—"}),e.jsxs(xt,{children:[E.uses_count,E.max_uses&&` / ${E.max_uses}`]}),e.jsx(xt,{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(xt,{className:"text-muted-foreground",children:As(new Date(E.created_at),"MMM d, yyyy")}),e.jsx(xt,{children:e.jsx(Rr,{checked:E.is_active,onCheckedChange:()=>b(E.id,E.is_active)})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>C(E.code),title:"Copy invite link",children:e.jsx(si,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>j(E.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},E.id))})]})})]})]})})},BB=async s=>{try{const{data:t,error:r}=await U.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return r?(console.error("Error checking notification setting:",r),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},R8=async s=>{try{const{data:t,error:r}=await U.functions.invoke("send-push-notification",{body:s});return r?(console.error("Error sending notification:",r),{success:!1,error:r}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},exs=async(s,t)=>await BB("new_templates")?R8({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}),txs=async(s,t)=>R8({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),sxs=async(s,t)=>await BB("new_events")?R8({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),rxs=async(s,t)=>await BB("new_toolbox")?R8({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),MSe=async(s,t)=>await BB("new_social_swag")?R8({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}),nxs=async(s,t)=>await BB("new_newsletters")?R8({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),Qq={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 axs(){const s=qr(),t=is(),[r,n]=k.useState(!1),[a,i]=k.useState(null),[l,o]=k.useState(Qq),[c,d]=k.useState(null),[u,m]=k.useState(null),[f,x]=k.useState(!1),y=k.useRef(null),[_,b]=k.useState(!1),[j,N]=k.useState(null),[C,A]=k.useState(!1),[E,D]=k.useState(null),[R,F]=k.useState(null),[O,B]=k.useState(!0),[K,Z]=k.useState(""),{data:Q,isLoading:W}=pt({queryKey:["admin-events"],queryFn:async()=>{const{data:Ce,error:qe}=await U.from("events").select("*").order("event_date",{ascending:!0});if(qe)throw qe;return Ce}}),{data:te}=pt({queryKey:["event-registrations-count"],queryFn:async()=>{let Ce=[],qe=0;const et=1e3;for(;;){const{data:rt,error:ct}=await U.from("event_registrations").select("event_id").range(qe,qe+et-1);if(ct)throw ct;if(!rt||rt.length===0||(Ce=Ce.concat(rt),rt.length{Ze[rt.event_id]=(Ze[rt.event_id]||0)+1}),Ze}}),{data:ne,isLoading:ae}=pt({queryKey:["event-registrations-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:Ce,error:qe}=await U.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(qe)throw qe;if(!Ce||Ce.length===0)return[];const et=Ce.map(ct=>ct.user_id).filter(Boolean);let Ze=[];if(et.length>0){const{data:ct,error:vt}=await U.from("profiles").select("id, name, email").in("id",et);if(vt)throw vt;Ze=ct||[]}const rt=new Map((Ze==null?void 0:Ze.map(ct=>[ct.id,ct]))||[]);return Ce.map(ct=>({...ct,profiles:ct.user_id&&rt.get(ct.user_id)||null}))},enabled:!!j}),{data:ue,isLoading:me}=pt({queryKey:["event-attendees-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:Ce,error:qe}=await U.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",j.id).order("created_at",{ascending:!1});if(qe)throw qe;if(!Ce||Ce.length===0)return[];const et=Ce.map(kt=>kt.user_id).filter(Boolean);let Ze=[];if(et.length>0){const{data:kt,error:St}=await U.from("profiles").select("id, name, email").in("id",et);if(St)throw St;Ze=kt||[]}const{data:rt}=await U.from("agent_points").select("user_id").eq("event_id",j.id),ct=new Set((rt==null?void 0:rt.map(kt=>kt.user_id))||[]),vt=new Map((Ze==null?void 0:Ze.map(kt=>[kt.id,kt]))||[]);return Ce.map(kt=>({...kt,profiles:kt.user_id&&vt.get(kt.user_id)||null,points_awarded:kt.user_id?ct.has(kt.user_id):!1}))},enabled:!!j}),de=Ce=>{N(Ce),b(!0)},fe=Mt({mutationFn:async Ce=>{const{data:{session:qe}}=await U.auth.getSession();if(!qe)throw new Error("Not authenticated");const et=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qe.access_token}`},body:JSON.stringify({event_id:Ce})}),Ze=await et.json();if(!et.ok)throw new Error(Ze.error||"Failed to sync");return Ze},onSuccess:Ce=>{t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),he.success(Ce.message)},onError:Ce=>{he.error("Failed to sync: "+Ce.message)}}),je=Mt({mutationFn:async Ce=>{const{data:{session:qe}}=await U.auth.getSession();if(!qe)throw new Error("Not authenticated");const et=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qe.access_token}`},body:JSON.stringify({event_id:Ce})}),Ze=await et.json();if(!et.ok)throw new Error(Ze.error||"Failed to sync attendees");return Ze},onSuccess:Ce=>{t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ce!=null&&Ce.message?he.success(Ce.message):he.success(`Synced ${Ce.synced||0} attendees. ${Ce.points_awarded||0} points awarded!`)},onError:Ce=>{he.error("Failed to sync attendees: "+Ce.message)}}),xe=Mt({mutationFn:async()=>{const{data:Ce,error:qe}=await U.functions.invoke("zoom-retry-registrations",{body:{}});if(qe)throw qe;return Ce},onSuccess:Ce=>{t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),he.success(`Retry complete: ${(Ce==null?void 0:Ce.successCount)??0} fixed, ${(Ce==null?void 0:Ce.failCount)??0} still failing, ${(Ce==null?void 0:Ce.rateLimitedCount)??0} rate-limited`)},onError:Ce=>{he.error("Retry failed: "+Ce.message)}}),Ee=Mt({mutationFn:async({eventId:Ce,testMode:qe})=>{const{data:{session:et}}=await U.auth.getSession();if(!et)throw new Error("Not authenticated");const Ze=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${et.access_token}`},body:JSON.stringify({event_id:Ce,test_mode:qe})}),rt=await Ze.json();if(!Ze.ok)throw new Error(rt.error||"Failed to send reminders");return rt},onSuccess:Ce=>{Ce.test?he.success(Ce.message||"Test email sent!"):he.success(Ce.message||`Reminder emails sent to ${Ce.sent} registrants!`)},onError:Ce=>{he.error("Failed to send reminders: "+Ce.message)}}),{data:Me}=pt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ce=[],qe=0;const et=1e3;for(;;){const{data:Ze,error:rt}=await U.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(qe,qe+et-1);if(rt)throw rt;if(!Ze||Ze.length===0||(Ce=[...Ce,...Ze],Ze.length{const{error:rt}=await U.from("event_attendees").update({user_id:qe}).eq("id",Ce);if(rt)throw rt;if(Ze&&et){const{error:vt}=await U.from("zoom_email_aliases").upsert({user_id:qe,zoom_email:et.toLowerCase()},{onConflict:"zoom_email"});vt&&console.error("Failed to save alias:",vt)}const ct=j==null?void 0:j.id;if(ct){const{data:vt}=await U.from("user_roles").select("id").eq("user_id",qe).eq("role","admin").single();if(!vt){const{data:kt}=await U.from("agent_points").select("id").eq("user_id",qe).eq("event_id",ct).single();kt||(await U.rpc("award_attendance_points",{p_user_id:qe,p_event_id:ct,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await U.rpc("check_and_award_badges",{p_user_id:qe}))}}return{userId:qe,zoomEmail:et,shouldSaveAlias:Ze}},onSuccess:Ce=>{t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let qe="Attendee linked and points awarded!";Ce.shouldSaveAlias&&Ce.zoomEmail&&(qe+=` Email "${Ce.zoomEmail}" will be auto-matched in the future.`),he.success(qe),A(!1),D(null),F(null),Z("")},onError:Ce=>{he.error("Failed to link attendee: "+Ce.message)}}),Ie=Ce=>{D(Ce),F(null),B(!0),Z(""),A(!0)},ze=()=>{!E||!R||Oe.mutate({attendeeId:E.id,userId:R,zoomEmail:E.zoom_email,shouldSaveAlias:O})},Ve=(Me==null?void 0:Me.filter(Ce=>{var et,Ze;if(!K)return!0;const qe=K.toLowerCase();return((et=Ce.name)==null?void 0:et.toLowerCase().includes(qe))||((Ze=Ce.email)==null?void 0:Ze.toLowerCase().includes(qe))}))||[],Le=async Ce=>{const qe=Ce.name.split(".").pop(),Ze=`${`${crypto.randomUUID()}.${qe}`}`,{error:rt}=await U.storage.from("event-images").upload(Ze,Ce);if(rt)throw rt;const{data:{publicUrl:ct}}=U.storage.from("event-images").getPublicUrl(Ze);return ct},$e=Ce=>{var et;const qe=(et=Ce.target.files)==null?void 0:et[0];if(qe){if(qe.size>5*1024*1024){he.error("Image must be less than 5MB");return}d(qe),m(URL.createObjectURL(qe))}},ve=()=>{d(null),m(null),o({...l,image_url:""}),y.current&&(y.current.value="")},Qe=Mt({mutationFn:async Ce=>{x(!0);let qe=Ce.image_url;c&&(qe=await Le(c)||"");const et=new Date(Ce.event_date),[Ze,rt]=Ce.event_time.split(":");et.setHours(parseInt(Ze),parseInt(rt));const ct=[new Date(et)];if(Ce.is_recurring&&Ce.recurrence_end_date){let Yt=new Date(et);for(;Ce.recurrence_pattern==="weekly"?Yt=KT(Yt,1):Ce.recurrence_pattern==="biweekly"?Yt=KT(Yt,2):Yt=Ex(Yt,1),!(Yt>Ce.recurrence_end_date);)ct.push(new Date(Yt))}const vt=ct.map(Yt=>({title:Ce.title,description:Ce.description||null,image_url:qe||null,video_url:Ce.video_url||null,event_date:Yt.toISOString(),zoom_link:Ce.zoom_link,zoom_meeting_id:Ce.zoom_meeting_id||null,capacity:Ce.capacity?parseInt(Ce.capacity):null,is_published:Ce.is_published})),{data:kt,error:St}=await U.from("events").insert(vt).select();if(St)throw St;return kt&&kt.length>0&&sxs(Ce.title,kt[0].id),ct.length},onSuccess:Ce=>{t.invalidateQueries({queryKey:["admin-events"]}),he.success(Ce>1?`${Ce} recurring events created successfully`:"Event created successfully"),n(!1),o(Qq),d(null),m(null),x(!1)},onError:Ce=>{he.error("Failed to create event: "+Ce.message),x(!1)}}),we=Mt({mutationFn:async({id:Ce,data:qe})=>{x(!0);let et=qe.image_url;c&&(et=await Le(c)||"");const Ze=new Date(qe.event_date),[rt,ct]=qe.event_time.split(":");Ze.setHours(parseInt(rt),parseInt(ct));const{error:vt}=await U.from("events").update({title:qe.title,description:qe.description||null,image_url:et||null,video_url:qe.video_url||null,event_date:Ze.toISOString(),zoom_link:qe.zoom_link,zoom_meeting_id:qe.zoom_meeting_id||null,capacity:qe.capacity?parseInt(qe.capacity):null,is_published:qe.is_published}).eq("id",Ce);if(vt)throw vt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),he.success("Event updated successfully"),n(!1),i(null),o(Qq),d(null),m(null),x(!1)},onError:Ce=>{he.error("Failed to update event: "+Ce.message),x(!1)}}),nt=Mt({mutationFn:async Ce=>{const{error:qe}=await U.from("events").delete().eq("id",Ce);if(qe)throw qe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),he.success("Event deleted successfully")},onError:Ce=>{he.error("Failed to delete event: "+Ce.message)}}),Se=Ce=>{var et;const qe=new Date(Ce.event_date);i(Ce),o({title:Ce.title,description:Ce.description||"",image_url:Ce.image_url||"",video_url:Ce.video_url||"",event_date:qe,event_time:As(qe,"HH:mm"),zoom_link:Ce.zoom_link,zoom_meeting_id:Ce.zoom_meeting_id||"",capacity:((et=Ce.capacity)==null?void 0:et.toString())||"",is_published:Ce.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),m(Ce.image_url||null),d(null),n(!0)},Ge=Ce=>{if(Ce.preventDefault(),!l.event_date){he.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){he.error("Please select an end date for recurring events");return}a?we.mutate({id:a.id,data:l}):Qe.mutate(l)},We=()=>{n(!1),i(null),o(Qq),d(null),m(null)};return e.jsx("div",{className:"min-h-screen bg-background p-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>s("/dashboard"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Event Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage upcoming events"})]})]}),e.jsxs(ke,{className:"mb-6",children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{children:"All Events"}),e.jsxs(vs,{open:r,onOpenChange:Ce=>!Ce&&We(),children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{onClick:()=>n(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:Ge,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:l.title,onChange:Ce=>o({...l,title:Ce.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(V1,{content:l.description,onChange:Ce=>o({...l,description:Ce}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Event Image"}),e.jsx("input",{type:"file",ref:y,accept:"image/*",onChange:$e,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(q,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:ve,children:e.jsx($r,{className:"h-4 w-4"})})]}):e.jsxs(q,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var Ce;return(Ce=y.current)==null?void 0:Ce.click()},children:[e.jsx(ka,{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(ce,{children:"Date *"}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),l.event_date?As(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:l.event_date,onSelect:Ce=>o({...l,event_date:Ce}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"time",children:"Time *"}),e.jsx(Ne,{id:"time",type:"time",value:l.event_time,onChange:Ce=>o({...l,event_time:Ce.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(Ne,{id:"zoom_link",value:l.zoom_link,onChange:Ce=>o({...l,zoom_link:Ce.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(Ne,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:Ce=>o({...l,zoom_meeting_id:Ce.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(ce,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(Ne,{id:"video_url",value:l.video_url,onChange:Ce=>o({...l,video_url:Ce.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(ce,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(Ne,{id:"capacity",type:"number",value:l.capacity,onChange:Ce=>o({...l,capacity:Ce.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(qF,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ce,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(Rr,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Ce=>o({...l,is_recurring:Ce})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Frequency"}),e.jsxs(Ds,{value:l.recurrence_pattern,onValueChange:Ce=>o({...l,recurrence_pattern:Ce}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"weekly",children:"Weekly"}),e.jsx(lt,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(lt,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Repeat Until"}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?As(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:l.recurrence_end_date,onSelect:Ce=>o({...l,recurrence_end_date:Ce}),disabled:Ce=>Ce<(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 Ce=1,qe=new Date(l.event_date);for(;qe=l.recurrence_pattern==="weekly"?KT(qe,1):l.recurrence_pattern==="biweekly"?KT(qe,2):Ex(qe,1),!(qe>l.recurrence_end_date);)Ce++;return Ce})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{htmlFor:"is_published",children:"Published"}),e.jsx(Rr,{id:"is_published",checked:l.is_published,onCheckedChange:Ce=>o({...l,is_published:Ce})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:We,className:"flex-1",children:"Cancel"}),e.jsx(q,{type:"submit",className:"flex-1",disabled:Qe.isPending||we.isPending||f,children:f?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Pe,{children:W?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(Q==null?void 0:Q.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Date & Time"}),e.jsx(At,{children:"Registrations"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:Q==null?void 0:Q.map(Ce=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:Ce.title}),e.jsx(xt,{children:As(new Date(Ce.event_date),"PPP p")}),e.jsx(xt,{children:e.jsxs(q,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>de(Ce),children:[e.jsx(Dr,{className:"h-4 w-4"}),(te==null?void 0:te[Ce.id])||0,Ce.capacity&&` / ${Ce.capacity}`]})}),e.jsx(xt,{children:e.jsx("span",{className:zt("px-2 py-1 rounded-full text-xs font-medium",Ce.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:Ce.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>window.open(Ce.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(un,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>Se(Ce),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&nt.mutate(Ce.id)},children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},Ce.id))})]})})]}),e.jsx(vs,{open:_,onOpenChange:b,children:e.jsxs(ys,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),j==null?void 0:j.title]}),e.jsx(an,{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(q,{variant:"ghost",size:"sm",onClick:()=>Ee.mutate({eventId:j.id,testMode:!0}),disabled:Ee.isPending,children:[e.jsx(Ks,{className:zt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>Ee.mutate({eventId:j.id}),disabled:Ee.isPending||!(ne!=null&&ne.length),children:[e.jsx(Ks,{className:zt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),Ee.isPending?"Sending...":"Send Reminder to All"]}),(j==null?void 0:j.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>fe.mutate(j.id),disabled:fe.isPending,children:[e.jsx(lo,{className:zt("h-4 w-4 mr-2",fe.isPending&&"animate-spin")}),fe.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>xe.mutate(),disabled:xe.isPending,children:[e.jsx(lo,{className:zt("h-4 w-4 mr-2",xe.isPending&&"animate-spin")}),xe.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(q,{variant:"default",size:"sm",onClick:()=>je.mutate(j.id),disabled:je.isPending,children:[e.jsx(wo,{className:zt("h-4 w-4 mr-2",je.isPending&&"animate-spin")}),je.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(ta,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(ea,{className:"grid w-full grid-cols-2",children:[e.jsxs(rs,{value:"registrations",className:"gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),"Registrations (",(ne==null?void 0:ne.length)||0,")"]}),e.jsxs(rs,{value:"attendees",className:"gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),"Attendees (",(ue==null?void 0:ue.length)||0,")"]})]}),e.jsx(fs,{value:"registrations",className:"mt-4",children:ae?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(ne==null?void 0:ne.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(j==null?void 0:j.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Registered"}),e.jsx(At,{children:"Status"})]})}),e.jsx(ha,{children:ne==null?void 0:ne.map(Ce=>{var rt,ct;const qe=((rt=Ce.profiles)==null?void 0:rt.name)||Ce.zoom_name||"Unknown",et=((ct=Ce.profiles)==null?void 0:ct.email)||Ce.zoom_email||null,Ze=!Ce.user_id;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[qe,Ze&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(xt,{children:et?e.jsxs("a",{href:`mailto:${et}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Ks,{className:"h-3 w-3"}),et]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(xt,{className:"text-muted-foreground text-sm",children:As(new Date(Ce.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(xt,{children:Ce.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"})})]},Ce.id)})})]})}),e.jsx(fs,{value:"attendees",className:"mt-4",children:me?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ue==null?void 0:ue.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:[(ue==null?void 0:ue.filter(Ce=>!Ce.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(go,{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 (",ue==null?void 0:ue.filter(Ce=>!Ce.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:ue==null?void 0:ue.filter(Ce=>!Ce.user_id).map(Ce=>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:Ce.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ce.zoom_email||"No email"})]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>Ie(Ce),className:"gap-1",children:[e.jsx(Ul,{className:"h-3 w-3"}),"Link to Profile"]})]},Ce.id))})]}),e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Duration"}),e.jsx(At,{children:"Points"})]})}),e.jsx(ha,{children:ue==null?void 0:ue.filter(Ce=>Ce.user_id).map(Ce=>{var Ze,rt;const qe=((Ze=Ce.profiles)==null?void 0:Ze.name)||Ce.zoom_name||"Unknown",et=((rt=Ce.profiles)==null?void 0:rt.email)||Ce.zoom_email||null;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[qe,Ce.manually_added&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",children:"Manual"})]})}),e.jsx(xt,{children:et?e.jsxs("a",{href:`mailto:${et}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Ks,{className:"h-3 w-3"}),et]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(xt,{children:Ce.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(jn,{className:"h-3 w-3"}),Ce.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{children:Ce.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(wo,{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"})})]},Ce.id)})})]})]})})]})]})}),e.jsx(vs,{open:C,onOpenChange:A,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ul,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(an,{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(ce,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:K,onChange:Ce=>Z(Ce.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Ve.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:Ve.slice(0,20).map(Ce=>e.jsxs("button",{type:"button",onClick:()=>F(Ce.id),className:zt("w-full p-3 text-left hover:bg-muted/50 transition-colors",R===Ce.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:Ce.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ce.email})]},Ce.id))})}),E.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ri,{id:"save-alias",checked:O,onCheckedChange:Ce=>B(Ce)}),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(q,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(q,{onClick:ze,disabled:!R||Oe.isPending,children:Oe.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}function ixs({selectedKitIds:s,onChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l=[]}=pt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:m,error:f}=await U.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(f)throw f;return m}}),o=l.filter(m=>s.includes(m.id)),c=l.filter(m=>!s.includes(m.id)&&m.name.toLowerCase().includes(r.toLowerCase())),d=m=>{t([...s,m])},u=m=>{t(s.filter(f=>f!==m))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(m=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 pr-1",children:[m.name,e.jsx("button",{type:"button",onClick:()=>u(m.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx($r,{className:"h-3 w-3"})})]},m.id))}),e.jsxs(sl,{open:a,onOpenChange:i,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(yc,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(Ko,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(_n,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search toolkits...",value:r,onChange:m=>n(m.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:r?"No toolkits found":"All toolkits selected"}):c.map(m=>e.jsxs("button",{type:"button",onClick:()=>{d(m.id),n("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[m.featured_image_url?e.jsx("img",{src:m.featured_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(yc,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link toolkits that agents can download alongside this template."})]})}const oxs=()=>{const{user:s}=Cs(),{toast:t}=Ba(),r=is(),[n,a]=ic(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[m,f]=k.useState(null),[x,y]=k.useState(0),[_,b]=k.useState(!1),[j,N]=k.useState(null),[C,A]=k.useState(""),[E,D]=k.useState([]),[R,F]=k.useState(""),[O,B]=k.useState(""),[K,Z]=k.useState(!1),[Q,W]=k.useState(!1),{data:te=[]}=pt({queryKey:["template-categories"],queryFn:async()=>{const{data:Se,error:Ge}=await U.from("template_categories").select("*").order("name");if(Ge)throw Ge;return Se}}),{data:ne=[]}=pt({queryKey:["template-types"],queryFn:async()=>{const{data:Se,error:Ge}=await U.from("template_types").select("*").order("name");if(Ge)throw Ge;return Se}}),{data:ae=[],isLoading:ue}=pt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Se,error:Ge}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Ge)throw Ge;const{data:We,error:Ce}=await U.from("template_links").select("*").order("sort_order");if(Ce)throw Ce;const{data:qe,error:et}=await U.from("template_guides").select("*").order("sort_order");if(et)throw et;return Se.map(rt=>({...rt,links:(We==null?void 0:We.filter(ct=>ct.template_id===rt.id))||[],guides:(qe==null?void 0:qe.filter(ct=>ct.template_id===rt.id))||[]}))}});k.useEffect(()=>{const Se=n.get("edit");if(Se&&ae.length>0){const Ge=ae.find(We=>We.id===Se);Ge&&(Me(Ge),a({},{replace:!0}))}},[ae,n]);const me=Mt({mutationFn:async Se=>{const{data:Ge,error:We}=await U.from("template_categories").insert({name:Se}).select().single();if(We)throw We;return Ge},onSuccess:Se=>{r.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Se.id}),F(""),Z(!1),t({title:"Category added"})},onError:Se=>{t({title:"Error adding category",description:Se.message,variant:"destructive"})}}),de=Mt({mutationFn:async Se=>{const{data:Ge,error:We}=await U.from("template_types").insert({name:Se}).select().single();if(We)throw We;return Ge},onSuccess:Se=>{r.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Se.id}),B(""),W(!1),t({title:"Type added"})},onError:Se=>{t({title:"Error adding type",description:Se.message,variant:"destructive"})}}),fe=Mt({mutationFn:async Se=>{var et;let Ge=Se.existingImageUrl;if(Se.image){const Ze=Se.image.name.split(".").pop(),rt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Ze}`,{error:ct}=await U.storage.from("template-previews").upload(rt,Se.image);if(ct)throw ct;const{data:vt}=U.storage.from("template-previews").getPublicUrl(rt);Ge=vt.publicUrl}const We={name:Se.template.name,description:Se.template.description||null,category_id:Se.template.category_id||null,type_id:Se.template.type_id||null,preview_image_url:Ge,video_url:Se.videoUrl||null,publish_date:Se.template.publish_date?new Date(Se.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ce=Se.templateId;if(Ce){const{error:Ze}=await U.from("canva_templates").update(We).eq("id",Ce);if(Ze)throw Ze;const{error:rt}=await U.from("template_links").delete().eq("template_id",Ce);if(rt)throw rt;const ct=((et=Se.existingGuides)==null?void 0:et.map(St=>St.id).filter(Boolean))||[],vt=Se.template.guides.map(St=>St.id).filter(Boolean),kt=ct.filter(St=>!vt.includes(St));kt.length>0&&await U.from("template_guides").delete().in("id",kt)}else{const{data:Ze,error:rt}=await U.from("canva_templates").insert(We).select().single();if(rt)throw rt;Ce=Ze.id,exs(Se.template.name,Ze.id)}const qe=Se.template.links.filter(Ze=>Ze.title.trim()&&Ze.canva_share_link.trim());if(qe.length>0){const Ze=qe.map((ct,vt)=>({template_id:Ce,title:ct.title.trim(),canva_share_link:ct.canva_share_link.trim(),sort_order:vt})),{error:rt}=await U.from("template_links").insert(Ze);if(rt)throw rt}for(let Ze=0;Ze0)){const{error:Ze}=await U.from("resource_kit_templates").insert(Se.linkedKitIds.map(rt=>({template_id:Ce,kit_id:rt})));if(Ze)throw Ze}},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),Ee(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Se=>{t({title:"Error saving template",description:Se.message,variant:"destructive"})}}),je=Mt({mutationFn:async Se=>{const{error:Ge}=await U.from("canva_templates").delete().eq("id",Se);if(Ge)throw Ge},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Se=>{t({title:"Error deleting template",description:Se.message,variant:"destructive"})}}),xe=Mt({mutationFn:async({id:Se,is_featured:Ge})=>{const{error:We}=await U.from("canva_templates").update({is_featured:Ge}).eq("id",Se);if(We)throw We},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]})},onError:Se=>{t({title:"Error updating featured",description:Se.message,variant:"destructive"})}}),Ee=()=>{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:""}),N(null),A(""),c(null),Z(!1),W(!1),F(""),B(""),f(null),y(0),b(!1),D([])},Me=async Se=>{var We;c(Se),u({name:Se.name,description:Se.description||"",category_id:Se.category_id||"",type_id:Se.type_id||"",publish_date:Se.publish_date?new Date(Se.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Se.links&&Se.links.length>0?Se.links.map(Ce=>({id:Ce.id,title:Ce.title,canva_share_link:Ce.canva_share_link,sort_order:Ce.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((We=Se.guides)==null?void 0:We.map(Ce=>({id:Ce.id,name:Ce.name,file_url:Ce.file_url,file_type:Ce.file_type,file_size:Ce.file_size,sort_order:Ce.sort_order})))||[],video_url:Se.video_url||""}),A(Se.preview_image_url||""),f(null);const{data:Ge}=await U.from("resource_kit_templates").select("kit_id").eq("template_id",Se.id);D((Ge||[]).map(Ce=>Ce.kit_id)),l(!0)},Oe=Se=>{var We;const Ge=(We=Se.target.files)==null?void 0:We[0];Ge&&(N(Ge),A(URL.createObjectURL(Ge)))},Ie=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},ze=Se=>{if(d.links.length<=1)return;const Ge=d.links.filter((We,Ce)=>Ce!==Se);u({...d,links:Ge})},Ve=(Se,Ge,We)=>{const Ce=[...d.links];Ce[Se]={...Ce[Se],[Ge]:We},u({...d,links:Ce})},Le=Se=>{const Ge=Se.target.files;if(!Ge)return;const We=Array.from(Ge).map((Ce,qe)=>({name:Ce.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ce.type,file_size:Ce.size,sort_order:d.guides.length+qe,file:Ce}));u({...d,guides:[...d.guides,...We]}),Se.target.value=""},$e=Se=>{const Ge=d.guides.filter((We,Ce)=>Ce!==Se);u({...d,guides:Ge})},ve=(Se,Ge)=>{const We=[...d.guides];We[Se]={...We[Se],name:Ge},u({...d,guides:We})},Qe=async()=>{if(!m)return null;b(!0),y(0);try{const{data:Se,error:Ge}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||m.name}});if(Ge)throw new Error(Ge.message);const{videoId:We,libraryId:Ce}=Se,{data:qe,error:et}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:We}});if(et)throw new Error(et.message);const Ze=new XMLHttpRequest;return await new Promise((ct,vt)=>{Ze.upload.addEventListener("progress",kt=>{if(kt.lengthComputable){const St=Math.round(kt.loaded/kt.total*100);y(St)}}),Ze.addEventListener("load",()=>{Ze.status>=200&&Ze.status<300?ct():vt(new Error(`Upload failed with status ${Ze.status}`))}),Ze.addEventListener("error",()=>vt(new Error("Upload failed"))),Ze.open("PUT",qe.uploadUrl),Ze.setRequestHeader("AccessKey",qe.apiKey),Ze.send(m)}),`https://player.mediadelivery.net/embed/${Ce}/${We}`}catch(Se){return console.error("Bunny upload error:",Se),t({title:"Video upload failed",description:Se instanceof Error?Se.message:"Unknown error",variant:"destructive"}),null}finally{b(!1)}},we=Se=>{var We;const Ge=(We=Se.target.files)==null?void 0:We[0];Ge&&f(Ge),Se.target.value=""},nt=async Se=>{if(Se.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ce=>Ce.title.trim()&&Ce.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let We=d.video_url;if(m){const Ce=await Qe();if(!Ce)return;We=Ce}fe.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:We,linkedKitIds:E})};return e.jsx(ws,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Manage Templates",description:"Create and manage Canva templates"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ae.length})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:te.length})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.length})})]})]}),e.jsxs(vs,{open:i,onOpenChange:Se=>{l(Se),Se||Ee()},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:nt,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"name",children:"Name *"}),e.jsx(Ne,{id:"name",value:d.name,onChange:Se=>u({...d,name:Se.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(V1,{content:d.description,onChange:Se=>u({...d,description:Se}),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(ce,{children:"Canva Links *"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:Ie,className:"gap-1",children:[e.jsx(Ys,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Se,Ge)=>e.jsxs("div",{className:"flex gap-2 items-start p-3 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ne,{value:Se.title,onChange:We=>Ve(Ge,"title",We.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(Ne,{value:Se.canva_share_link,onChange:We=>Ve(Ge,"canva_share_link",We.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(q,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>ze(Ge),children:e.jsx($r,{className:"h-4 w-4"})})]},Ge))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Category"}),K?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:R,onChange:Se=>F(Se.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(q,{type:"button",size:"sm",onClick:()=>R.trim()&&me.mutate(R.trim()),disabled:me.isPending,children:"Add"}),e.jsx(q,{type:"button",size:"sm",variant:"ghost",onClick:()=>{Z(!1),F("")},children:e.jsx($r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ds,{value:d.category_id,onValueChange:Se=>u({...d,category_id:Se}),children:[e.jsx(Ps,{className:"flex-1",children:e.jsx(Fs,{placeholder:"Select category"})}),e.jsx(Ls,{children:te.map(Se=>e.jsx(lt,{value:Se.id,children:Se.name},Se.id))})]}),e.jsx(q,{type:"button",variant:"outline",size:"icon",onClick:()=>Z(!0),children:e.jsx(Ys,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Template Type"}),Q?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:O,onChange:Se=>B(Se.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(q,{type:"button",size:"sm",onClick:()=>O.trim()&&de.mutate(O.trim()),disabled:de.isPending,children:"Add"}),e.jsx(q,{type:"button",size:"sm",variant:"ghost",onClick:()=>{W(!1),B("")},children:e.jsx($r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ds,{value:d.type_id,onValueChange:Se=>u({...d,type_id:Se}),children:[e.jsx(Ps,{className:"flex-1",children:e.jsx(Fs,{placeholder:"Select type"})}),e.jsx(Ls,{children:ne.map(Se=>e.jsx(lt,{value:Se.id,children:Se.name},Se.id))})]}),e.jsx(q,{type:"button",variant:"outline",size:"icon",onClick:()=>W(!0),children:e.jsx(Ys,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:d.publish_date,onChange:Se=>u({...d,publish_date:Se.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(ce,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[C?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:C,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(q,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{N(null),A("")},children:e.jsx($r,{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(zo,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Ne,{type:"file",accept:"image/*",onChange:Oe,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(ce,{children:"Video (Optional)"}),d.video_url&&!m?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(bn,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(q,{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(ls,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",x,"%"]})]}),e.jsx(ki,{value:x,className:"h-2"})]}):m?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(bn,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:m.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(m.size/1024/1024).toFixed(1)," MB"]}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>f(null),children:e.jsx($r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(Ne,{type:"file",accept:"video/*",onChange:we,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(bn,{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(ce,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(Ne,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Le,className:"hidden"}),e.jsx(q,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(ka,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Se,Ge)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(En,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(Ne,{value:Se.name,onChange:We=>ve(Ge,We.target.value),placeholder:"Guide name",className:"flex-1"}),Se.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Se.file_size/1024).toFixed(0)," KB"]}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>$e(Ge),children:e.jsx($r,{className:"h-4 w-4"})})]},Se.id||Ge))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No guide files added. Upload PDFs to help agents understand how to use this template."})]}),e.jsx(ixs,{selectedKitIds:E,onChange:D}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>{l(!1),Ee()},children:"Cancel"}),e.jsx(q,{type:"submit",disabled:fe.isPending,children:fe.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:ue?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):ae.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Preview"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Links"}),e.jsx(At,{children:"Category"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:ae.map(Se=>{var Ge,We,Ce,qe,et;return e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Se.preview_image_url?e.jsx("img",{src:Se.preview_image_url,alt:Se.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(zo,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(xt,{className:"font-medium",children:Se.name}),e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(Xe,{variant:"secondary",children:[((Ge=Se.links)==null?void 0:Ge.length)||0," link",(((We=Se.links)==null?void 0:We.length)||0)!==1?"s":""]}),(((Ce=Se.guides)==null?void 0:Ce.length)||0)>0&&e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(En,{className:"h-3 w-3"}),(qe=Se.guides)==null?void 0:qe.length," guide",(((et=Se.guides)==null?void 0:et.length)||0)!==1?"s":""]})]})}),e.jsx(xt,{children:Se.category?e.jsx(Xe,{variant:"secondary",children:Se.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(xt,{children:Se.type?e.jsx(Xe,{variant:"outline",children:Se.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(xt,{className:"text-muted-foreground",children:new Date(Se.publish_date).toLocaleDateString()}),e.jsx(xt,{className:"text-center",children:e.jsx(q,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Se.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>xe.mutate({id:Se.id,is_featured:!Se.is_featured}),children:e.jsx(fa,{className:`h-4 w-4 ${Se.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{size:"icon",variant:"ghost",onClick:()=>Me(Se),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&je.mutate(Se.id)},children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},Se.id)})})]})})})]})})};function _ft({selectedTemplateIds:s,onChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l=[]}=pt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:m,error:f}=await U.from("canva_templates").select("id, name, preview_image_url").order("name");if(f)throw f;return m}}),o=l.filter(m=>s.includes(m.id)),c=l.filter(m=>!s.includes(m.id)&&m.name.toLowerCase().includes(r.toLowerCase())),d=m=>{t([...s,m])},u=m=>{t(s.filter(f=>f!==m))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(DE,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(m=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 pr-1",children:[m.name,e.jsx("button",{type:"button",onClick:()=>u(m.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx($r,{className:"h-3 w-3"})})]},m.id))}),e.jsxs(sl,{open:a,onOpenChange:i,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(DE,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Ko,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(_n,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search templates...",value:r,onChange:m=>n(m.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:r?"No templates found":"All templates selected"}):c.map(m=>e.jsxs("button",{type:"button",onClick:()=>{d(m.id),n("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[m.preview_image_url?e.jsx("img",{src:m.preview_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(DE,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link templates that agents can use alongside this content."})]})}const lxs=[{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"}],cxs=()=>{const{user:s}=Cs(),[t,r]=ic(),{toast:n}=Ba(),a=is(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[m,f]=k.useState(null),[x,y]=k.useState(""),[_,b]=k.useState([]),[j,N]=k.useState([]),[C,A]=k.useState([]),[E,D]=k.useState([]),[R,F]=k.useState(""),[O,B]=k.useState(!1),[K,Z]=k.useState(null),[Q,W]=k.useState(0),[te,ne]=k.useState(!1),[ae,ue]=k.useState(null),{data:me=[]}=pt({queryKey:["academy-categories"],queryFn:async()=>{const{data:Se,error:Ge}=await U.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Ge)throw Ge;return Se}}),{data:de=[],isLoading:fe}=pt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Se,error:Ge}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Ge)throw Ge;const{data:We,error:Ce}=await U.from("academy_resources").select("*").order("sort_order");if(Ce)throw Ce;return Se.map(et=>({...et,resources:(We==null?void 0:We.filter(Ze=>Ze.video_id===et.id))||[]}))}});k.useEffect(()=>{const Se=t.get("edit");if(Se&&de.length>0){const Ge=de.find(We=>We.id===Se);Ge&&(Ve(Ge),r({},{replace:!0}))}},[de,t]);const je=Mt({mutationFn:async Se=>{const{data:Ge,error:We}=await U.from("academy_categories").insert({name:Se,sort_order:me.length}).select().single();if(We)throw We;return Ge},onSuccess:Se=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Se.id}),F(""),B(!1),n({title:"Category added"})},onError:Se=>{n({title:"Error adding category",description:Se.message,variant:"destructive"})}}),xe=Mt({mutationFn:async Se=>{let Ge=Se.existingThumbnailUrl;if(Se.thumbnail){const qe=Se.thumbnail.name.split(".").pop(),et=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${qe}`,{error:Ze}=await U.storage.from("academy-resources").upload(et,Se.thumbnail);if(Ze)throw Ze;const{data:rt}=U.storage.from("academy-resources").getPublicUrl(et);Ge=rt.publicUrl}const We={title:Se.video.title,description:Se.video.description||null,video_url:Se.video.video_url,video_type:Se.video.video_type,duration:Se.video.duration||null,thumbnail_url:Ge,category_id:Se.video.category_id||null,publish_date:Se.video.publish_date?new Date(Se.video.publish_date).toISOString():new Date().toISOString(),is_published:Se.video.is_published,created_by:s==null?void 0:s.id};let Ce=Se.videoId;if(Ce){const{error:qe}=await U.from("academy_videos").update(We).eq("id",Ce);if(qe)throw qe}else{const{data:qe,error:et}=await U.from("academy_videos").insert(We).select().single();if(et)throw et;Ce=qe.id,txs(Se.video.title,qe.id)}if(Se.resourcesToDelete.length>0){const{error:qe}=await U.from("academy_resources").delete().in("id",Se.resourcesToDelete);if(qe)throw qe}for(let qe=0;qe0){const{error:qe}=await U.from("academy_video_templates").insert(E.map(et=>({video_id:Ce,template_id:et})));if(qe)throw qe}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),ze(),l(!1),n({title:o?"Video updated":"Video created"})},onError:Se=>{n({title:"Error saving video",description:Se.message,variant:"destructive"})}}),Ee=Mt({mutationFn:async Se=>{const{error:Ge}=await U.from("academy_videos").delete().eq("id",Se);if(Ge)throw Ge},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),n({title:"Video deleted"})},onError:Se=>{n({title:"Error deleting video",description:Se.message,variant:"destructive"})}}),Me=Mt({mutationFn:async({id:Se,is_published:Ge})=>{const{error:We}=await U.from("academy_videos").update({is_published:Ge}).eq("id",Se);if(We)throw We},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Se=>{n({title:"Error updating video",description:Se.message,variant:"destructive"})}}),Oe=async Se=>{try{let Ge=Se.public_slug||null,We=!!Se.is_public;if(!Ge||!We){const qe=(Se.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!Ge){let Ze=qe;const{data:rt}=await U.from("academy_videos").select("id").eq("public_slug",Ze).maybeSingle();rt&&rt.id!==Se.id&&(Ze=`${qe}-${Se.id.slice(0,6)}`),Ge=Ze}const{error:et}=await U.from("academy_videos").update({public_slug:Ge,is_public:!0}).eq("id",Se.id);if(et)throw et;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ce=`${window.location.origin}/watch/${Ge}`;await navigator.clipboard.writeText(Ce),n({title:"Public link copied",description:Ce})}catch(Ge){n({title:"Could not copy link",description:Ge.message,variant:"destructive"})}},Ie=async Se=>{if(!confirm("Disable the public teaser link for this video?"))return;const{error:Ge}=await U.from("academy_videos").update({is_public:!1}).eq("id",Se.id);if(Ge){n({title:"Error",description:Ge.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),n({title:"Public link disabled"})},ze=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),f(null),y(""),b([]),N([]),A([]),c(null),D([]),F(""),Z(null),W(0),ne(!1),ue(null)},Ve=async Se=>{c(Se),u({title:Se.title,description:Se.description||"",video_url:Se.video_url,video_type:Se.video_type,duration:Se.duration||"",category_id:Se.category_id||"",publish_date:Se.publish_date?new Date(Se.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Se.is_published}),y(Se.thumbnail_url||""),N(Se.resources||[]),b([]),A([]);const{data:Ge}=await U.from("academy_video_templates").select("template_id").eq("video_id",Se.id);D((Ge||[]).map(We=>We.template_id)),l(!0)},Le=Se=>{var We;const Ge=(We=Se.target.files)==null?void 0:We[0];Ge&&(f(Ge),y(URL.createObjectURL(Ge)))},$e=Se=>{const Ge=Se.target.files;if(Ge){const We=Array.from(Ge).map(Ce=>({file:Ce,title:Ce.name.replace(/\.[^/.]+$/,"")}));b([..._,...We])}Se.target.value=""},ve=Se=>{b(_.filter((Ge,We)=>We!==Se))},Qe=Se=>{A([...C,Se]),N(j.filter(Ge=>Ge.id!==Se))},we=async()=>{if(!K)return null;ne(!0),W(0);try{const{data:Se,error:Ge}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||K.name}});if(Ge)throw new Error(Ge.message);const{videoId:We,libraryId:Ce}=Se;ue(We);const{data:qe,error:et}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:We}});if(et)throw new Error(et.message);const Ze=new XMLHttpRequest;return await new Promise((ct,vt)=>{Ze.upload.addEventListener("progress",kt=>{if(kt.lengthComputable){const St=Math.round(kt.loaded/kt.total*100);W(St)}}),Ze.addEventListener("load",()=>{Ze.status>=200&&Ze.status<300?ct():vt(new Error(`Upload failed with status ${Ze.status}`))}),Ze.addEventListener("error",()=>vt(new Error("Upload failed"))),Ze.open("PUT",qe.uploadUrl),Ze.setRequestHeader("AccessKey",qe.apiKey),Ze.send(K)}),`https://player.mediadelivery.net/embed/${Ce}/${We}`}catch(Se){return console.error("Bunny upload error:",Se),n({title:"Video upload failed",description:Se instanceof Error?Se.message:"Unknown error",variant:"destructive"}),null}finally{ne(!1)}},nt=async Se=>{if(Se.preventDefault(),!d.title.trim()){n({title:"Please enter a video title",variant:"destructive"});return}let Ge=d.video_url;if(d.video_type==="bunny_stream"&&K&&!o){const We=await we();if(!We)return;Ge=We}else if(!d.video_url.trim()&&d.video_type!=="bunny_stream"){n({title:"Please enter a video URL",variant:"destructive"});return}else if(d.video_type==="bunny_stream"&&!K&&!d.video_url&&!o){n({title:"Please select a video file to upload",variant:"destructive"});return}xe.mutate({video:{...d,video_url:Ge},thumbnail:m,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:_,resourcesToDelete:C})};return e.jsx(ws,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Manage Academy",description:"Create and manage training videos and resources"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.length})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.filter(Se=>Se.is_published).length})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.filter(Se=>Se.is_public).length})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:de.reduce((Se,Ge)=>Se+(Ge.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(vs,{open:i,onOpenChange:Se=>{l(Se),Se||ze()},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:nt,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:d.title,onChange:Se=>u({...d,title:Se.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(V1,{content:d.description,onChange:Se=>u({...d,description:Se}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Video Type"}),e.jsxs(Ds,{value:d.video_type,onValueChange:Se=>{u({...d,video_type:Se,video_url:""}),Z(null)},disabled:te,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:lxs.map(Se=>e.jsx(lt,{value:Se.value,children:Se.label},Se.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ce,{children:["Upload Video File ",!o&&"*"]}),o&&d.video_url&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Current video: ",e.jsx("a",{href:d.video_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"View"})]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(Ne,{type:"file",accept:"video/*",onChange:Se=>{var We;const Ge=(We=Se.target.files)==null?void 0:We[0];Ge&&Z(Ge)},disabled:te}),K&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bn,{className:"h-4 w-4"}),K.name," (",(K.size/(1024*1024)).toFixed(1)," MB)"]}),te&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(ki,{value:Q,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[Q,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(Ne,{id:"video_url",value:d.video_url,onChange:Se=>u({...d,video_url:Se.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(ce,{htmlFor:"duration",children:"Duration"}),e.jsx(Ne,{id:"duration",value:d.duration,onChange:Se=>u({...d,duration:Se.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:d.publish_date,onChange:Se=>u({...d,publish_date:Se.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Category"}),O?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:R,onChange:Se=>F(Se.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(q,{type:"button",size:"sm",onClick:()=>R.trim()&&je.mutate(R.trim()),disabled:je.isPending,children:"Add"}),e.jsx(q,{type:"button",size:"sm",variant:"ghost",onClick:()=>{B(!1),F("")},children:e.jsx($r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ds,{value:d.category_id,onValueChange:Se=>u({...d,category_id:Se}),children:[e.jsx(Ps,{className:"flex-1",children:e.jsx(Fs,{placeholder:"Select category"})}),e.jsx(Ls,{children:me.map(Se=>e.jsx(lt,{value:Se.id,children:Se.name},Se.id))})]}),e.jsx(q,{type:"button",variant:"outline",size:"sm",onClick:()=>B(!0),children:e.jsx(Ys,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[x&&e.jsx("img",{src:x,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Ne,{type:"file",accept:"image/*",onChange:Le,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(ce,{children:"Resource Files"}),e.jsx(q,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:$e,className:"hidden"})]})})]}),(j.length>0||_.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[j.map(Se=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Se.title}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:Se.file_type}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>Qe(Se.id),className:"text-destructive hover:text-destructive",children:e.jsx($r,{className:"h-4 w-4"})})]},Se.id)),_.map((Se,Ge)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:Se.title,onChange:We=>{const Ce=[..._];Ce[Ge].title=We.target.value,b(Ce)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>ve(Ge),className:"text-destructive hover:text-destructive",children:e.jsx($r,{className:"h-4 w-4"})})]},Ge))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(_ft,{selectedTemplateIds:E,onChange:D}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{id:"is_published",checked:d.is_published,onCheckedChange:Se=>u({...d,is_published:Se})}),e.jsx(ce,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(fn,{children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:te,children:"Cancel"}),e.jsx(q,{type:"submit",disabled:xe.isPending||te,children:te?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):xe.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:fe?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"})}):de.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(bn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No videos yet"}),e.jsx("p",{className:"text-sm",children:"Add your first academy video"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Category"}),e.jsx(At,{children:"Duration"}),e.jsx(At,{children:"Resources"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Public Views"}),e.jsx(At,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(ha,{children:de.map(Se=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Se.thumbnail_url?e.jsx("img",{src:Se.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(bn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Se.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Se.video_type.replace("_"," ")})]})]})}),e.jsx(xt,{children:Se.category?e.jsx(Xe,{variant:"outline",children:Se.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(xt,{children:Se.duration||"-"}),e.jsx(xt,{children:Se.resources&&Se.resources.length>0?e.jsxs(Xe,{variant:"secondary",children:[Se.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(xt,{children:new Date(Se.publish_date).toLocaleDateString()}),e.jsx(xt,{children:e.jsx(Rr,{checked:Se.is_published,onCheckedChange:Ge=>Me.mutate({id:Se.id,is_published:Ge})})}),e.jsx(xt,{children:Se.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Se.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"ghost",size:"sm",title:Se.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>Oe(Se),children:Se.is_public?e.jsx(si,{className:"h-4 w-4 text-primary"}):e.jsx(Ec,{className:"h-4 w-4"})}),Se.is_public&&e.jsx(q,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>Ie(Se),children:e.jsx(Ql,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>Ve(Se),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>Ee.mutate(Se.id),className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},Se.id))})]})})})]})})};function dxs(){var xe,Ee,Me;const s=is(),[t,r]=ic(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=k.useState(null),[m,f]=k.useState(""),[x,y]=k.useState([]),[_,b]=k.useState([]),[j,N]=k.useState([]),[C,A]=k.useState(null),{data:E,isLoading:D}=pt({queryKey:["resource-kits"],queryFn:async()=>{const{data:Oe,error:Ie}=await U.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ie)throw Ie;return Oe}}),{data:R}=pt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:Oe,error:Ie}=await U.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ie)throw Ie;return Oe}}),{data:F}=pt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:Oe,error:Ie}=await U.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ie)throw Ie;return Oe}});k.useEffect(()=>{const Oe=t.get("edit");if(Oe&&E&&E.length>0&&R&&F){const Ie=E.find(ze=>ze.id===Oe);Ie&&(B(Ie),r({},{replace:!0}))}},[E,R,F,t]);const O=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),f(""),y([]),b([]),N([]),l(null)},B=async Oe=>{l(Oe),c({name:Oe.name,description:Oe.description||"",publish_date:Oe.publish_date.split("T")[0],is_published:Oe.is_published}),f(Oe.featured_image_url||"");const Ie=(R==null?void 0:R.filter(Le=>Le.kit_id===Oe.id))||[];y(Ie.map(Le=>({id:Le.id,name:Le.name,file_url:Le.file_url,file_type:Le.file_type,file_size:Le.file_size,sort_order:Le.sort_order})));const ze=(F==null?void 0:F.filter(Le=>Le.kit_id===Oe.id))||[];b(ze.map(Le=>({id:Le.id,title:Le.title,canva_share_link:Le.canva_share_link,sort_order:Le.sort_order})));const{data:Ve}=await U.from("resource_kit_templates").select("template_id").eq("kit_id",Oe.id);N((Ve||[]).map(Le=>Le.template_id)),a(!0)},K=Oe=>{var ze;const Ie=(ze=Oe.target.files)==null?void 0:ze[0];Ie&&(u(Ie),f(URL.createObjectURL(Ie)))},Z=()=>{y([...x,{name:"",file_url:"",sort_order:x.length}])},Q=Oe=>{y(x.filter((Ie,ze)=>ze!==Oe))},W=(Oe,Ie,ze)=>{const Ve=[...x];Ve[Oe]={...Ve[Oe],[Ie]:ze},y(Ve)},te=()=>{b([..._,{title:"",canva_share_link:"",sort_order:_.length}])},ne=Oe=>{b(_.filter((Ie,ze)=>ze!==Oe))},ae=(Oe,Ie,ze)=>{const Ve=[..._];Ve[Oe]={...Ve[Oe],[Ie]:ze},b(Ve)},ue=(Oe,Ie)=>{var Ve;const ze=(Ve=Ie.target.files)==null?void 0:Ve[0];if(ze){const Le=[...x],$e=ze.name.replace(/\.[^/.]+$/,"");Le[Oe]={...Le[Oe],file:ze,file_type:ze.type,file_size:ze.size,name:Le[Oe].name||$e},y(Le)}},me=Mt({mutationFn:async()=>{let Oe=(i==null?void 0:i.featured_image_url)||null;if(d){const $e=d.name.split(".").pop(),ve=`${Date.now()}.${$e}`,{error:Qe}=await U.storage.from("resource-kits").upload(`featured/${ve}`,d);if(Qe)throw Qe;const{data:we}=U.storage.from("resource-kits").getPublicUrl(`featured/${ve}`);Oe=we.publicUrl}const Ie={name:o.name,description:o.description||null,featured_image_url:Oe,publish_date:o.publish_date,is_published:o.is_published};let ze;const Ve=!i,Le=(i==null?void 0:i.is_published)||!1;if(i){const{error:$e}=await U.from("resource_kits").update(Ie).eq("id",i.id);if($e)throw $e;ze=i.id;const ve=(R==null?void 0:R.filter(We=>We.kit_id===i.id).map(We=>We.id))||[],Qe=x.filter(We=>We.id).map(We=>We.id),we=ve.filter(We=>!Qe.includes(We));we.length>0&&await U.from("resource_kit_files").delete().in("id",we);const nt=(F==null?void 0:F.filter(We=>We.kit_id===i.id).map(We=>We.id))||[],Se=_.filter(We=>We.id).map(We=>We.id),Ge=nt.filter(We=>!Se.includes(We));Ge.length>0&&await U.from("resource_kit_links").delete().in("id",Ge)}else{const{data:$e,error:ve}=await U.from("resource_kits").insert(Ie).select().single();if(ve)throw ve;ze=$e.id}for(let $e=0;$e0){const{error:$e}=await U.from("resource_kit_templates").insert(j.map(ve=>({kit_id:ze,template_id:ve})));if($e)throw $e}return{kitId:ze,kitName:o.name,isNewKit:Ve,wasPublished:Le,isPublished:o.is_published}},onSuccess:Oe=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),he.success(i?"Resource kit updated":"Resource kit created"),Oe.isPublished&&(Oe.isNewKit||!Oe.wasPublished)&&rxs(Oe.kitName,Oe.kitId),a(!1),O()},onError:Oe=>{he.error("Failed to save resource kit: "+Oe.message)}}),de=Mt({mutationFn:async Oe=>{const{error:Ie}=await U.from("resource_kits").delete().eq("id",Oe);if(Ie)throw Ie},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),he.success("Resource kit deleted")},onError:Oe=>{he.error("Failed to delete: "+Oe.message)}}),fe=Oe=>{if(Oe.preventDefault(),!o.name){he.error("Please enter a name");return}me.mutate()},je=Oe=>(R==null?void 0:R.filter(Ie=>Ie.kit_id===Oe).length)||0;return e.jsx(ws,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(E==null?void 0:E.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(E==null?void 0:E.filter(Oe=>Oe.is_published).length)||0})})]})]}),e.jsxs(q,{onClick:()=>{O(),a(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Files"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:D?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(E==null?void 0:E.length)===0?e.jsx(Ws,{children:e.jsx(xt,{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(Oe=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Oe.featured_image_url?e.jsx("img",{src:Oe.featured_image_url,alt:Oe.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(yc,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Oe.name}),Oe.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Oe.description})]})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),je(Oe.id)]})}),e.jsx(xt,{children:As(new Date(Oe.publish_date),"MMM d, yyyy")}),e.jsx(xt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Oe.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Oe.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{const Ie=(R==null?void 0:R.filter(Ve=>Ve.kit_id===Oe.id))||[],ze=(F==null?void 0:F.filter(Ve=>Ve.kit_id===Oe.id))||[];A({...Oe,files:Ie,links:ze})},children:e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>B(Oe),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&de.mutate(Oe.id)},children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},Oe.id))})]})})}),e.jsx(vs,{open:n,onOpenChange:a,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:fe,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[m?e.jsx("img",{src:m,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(yc,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:K})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"name",children:"Name *"}),e.jsx(Ne,{id:"name",value:o.name,onChange:Oe=>c({...o,name:Oe.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(V1,{content:o.description,onChange:Oe=>c({...o,description:Oe}),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(ce,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:o.publish_date,onChange:Oe=>c({...o,publish_date:Oe.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Rr,{checked:o.is_published,onCheckedChange:Oe=>c({...o,is_published:Oe})}),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(ce,{children:"Resource Files"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:Z,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),x.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:x.map((Oe,Ie)=>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 ",Ie+1]}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Q(Ie),children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsx(Ne,{placeholder:"File name (e.g., Getting Started Guide)",value:Oe.name,onChange:ze=>W(Ie,"name",ze.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"file",onChange:ze=>ue(Ie,ze),className:"flex-1"}),Oe.file_url&&!Oe.file&&e.jsx("a",{href:Oe.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),Oe.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Ie))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ce,{children:"Canva Links"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:te,children:[e.jsx(Ys,{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((Oe,Ie)=>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 ",Ie+1]}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>ne(Ie),children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsx(Ne,{placeholder:"Link title (e.g., Social Media Post Template)",value:Oe.title,onChange:ze=>ae(Ie,"title",ze.target.value)}),e.jsx(Ne,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:Oe.canva_share_link,onChange:ze=>ae(Ie,"canva_share_link",ze.target.value)})]},Ie))})]}),e.jsx(_ft,{selectedTemplateIds:j,onChange:N}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:me.isPending,children:me.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(vs,{open:!!C,onOpenChange:()=>A(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(_s,{children:e.jsx(bs,{children:C==null?void 0:C.name})}),e.jsxs("div",{className:"space-y-4",children:[(C==null?void 0:C.featured_image_url)&&e.jsx("img",{src:C.featured_image_url,alt:C.name,className:"w-full h-48 object-cover rounded-lg"}),(C==null?void 0:C.description)&&e.jsx("p",{className:"text-muted-foreground",children:C.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((xe=C==null?void 0:C.files)==null?void 0:xe.length)||0,")"]}),((Ee=C==null?void 0:C.files)==null?void 0:Ee.length)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No files in this kit"}):e.jsx("div",{className:"space-y-2",children:(Me=C==null?void 0:C.files)==null?void 0:Me.map(Oe=>e.jsxs("a",{href:Oe.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(En,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Oe.name})]},Oe.id))})]}),(C==null?void 0:C.links)&&C.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",C.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:C.links.map(Oe=>e.jsxs("a",{href:Oe.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(tl,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Oe.title})]},Oe.id))})]})]})]})})]})})}const uxs=()=>{const{user:s}=Cs(),{toast:t}=Ba(),r=is(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=k.useState(null),[m,f]=k.useState(""),{data:x=[],isLoading:y}=pt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:F,error:O}=await U.from("social_swag").select("*").order("publish_date",{ascending:!1});if(O)throw O;const{data:B,error:K}=await U.from("social_swag_links").select("*").order("sort_order");if(K)throw K;return F.map(Q=>({...Q,links:(B==null?void 0:B.filter(W=>W.swag_id===Q.id))||[]}))}}),_=Mt({mutationFn:async F=>{let O=F.existingImageUrl;if(F.image){const te=F.image.name.split(".").pop(),ne=`${Date.now()}-${Math.random().toString(36).substring(7)}.${te}`,{error:ae}=await U.storage.from("template-previews").upload(ne,F.image);if(ae)throw ae;const{data:ue}=U.storage.from("template-previews").getPublicUrl(ne);O=ue.publicUrl}const B={title:F.item.title,description:F.item.description||null,preview_image_url:O,publish_date:F.item.publish_date?new Date(F.item.publish_date).toISOString():new Date().toISOString(),is_published:F.item.is_published,created_by:s==null?void 0:s.id};let K=F.itemId;const Z=!K,Q=(i==null?void 0:i.is_published)||!1;if(K){const{error:te}=await U.from("social_swag").update(B).eq("id",K);if(te)throw te;await U.from("social_swag_links").delete().eq("swag_id",K)}else{const{data:te,error:ne}=await U.from("social_swag").insert(B).select().single();if(ne)throw ne;K=te.id}const W=F.item.links.filter(te=>te.title.trim()&&te.canva_share_link.trim());if(W.length>0){const te=W.map((ae,ue)=>({swag_id:K,title:ae.title.trim(),canva_share_link:ae.canva_share_link.trim(),sort_order:ue})),{error:ne}=await U.from("social_swag_links").insert(te);if(ne)throw ne}return{itemId:K,itemTitle:F.item.title,isNewItem:Z,wasPublished:Q,isPublished:F.item.is_published}},onSuccess:F=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),F.isPublished&&(F.isNewItem||!F.wasPublished)&&MSe(F.itemTitle,F.itemId),a(!1),j()},onError:F=>{t({title:"Error saving item",description:F.message,variant:"destructive"})}}),b=Mt({mutationFn:async F=>{const{error:O}=await U.from("social_swag").delete().eq("id",F);if(O)throw O},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:F=>{t({title:"Error deleting item",description:F.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),f(""),l(null)},N=F=>{l(F),c({title:F.title,description:F.description||"",publish_date:F.publish_date?new Date(F.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:F.is_published,links:F.links&&F.links.length>0?F.links.map(O=>({id:O.id,title:O.title,canva_share_link:O.canva_share_link,sort_order:O.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),f(F.preview_image_url||""),a(!0)},C=F=>{var B;const O=(B=F.target.files)==null?void 0:B[0];O&&(u(O),f(URL.createObjectURL(O)))},A=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},E=F=>{if(o.links.length<=1)return;const O=o.links.filter((B,K)=>K!==F);c({...o,links:O})},D=(F,O,B)=>{const K=[...o.links];K[F]={...K[F],[O]:B},c({...o,links:K})},R=F=>{if(F.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(ws,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Manage Social Swag",description:"Create and manage social media content"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:x.length})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:x.filter(F=>F.is_published).length})})]})]}),e.jsxs(vs,{open:n,onOpenChange:F=>{a(F),F||j()},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:R,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:o.title,onChange:F=>c({...o,title:F.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(V1,{content:o.description,onChange:F=>c({...o,description:F}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:o.publish_date,onChange:F=>c({...o,publish_date:F.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Rr,{id:"is_published",checked:o.is_published,onCheckedChange:F=>c({...o,is_published:F})}),e.jsx(ce,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Preview Image"}),m?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:m,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(q,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),f("")},children:e.jsx($r,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(zo,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:C,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Canva Links"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((F,O)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",O+1]}),o.links.length>1&&e.jsx(q,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>E(O),children:e.jsx($r,{className:"h-3 w-3"})})]}),e.jsx(Ne,{placeholder:"Link title (e.g., Instagram Post)",value:F.title,onChange:B=>D(O,"title",B.target.value)}),e.jsx(Ne,{placeholder:"Canva share link",value:F.canva_share_link,onChange:B=>D(O,"canva_share_link",B.target.value)})]})},O))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:_.isPending,children:_.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{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"})}):x.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-16",children:"Preview"}),e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Links"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:x.map(F=>{var O;return e.jsxs(Ws,{children:[e.jsx(xt,{children:F.preview_image_url?e.jsx("img",{src:F.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(zo,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(xt,{className:"font-medium",children:F.title}),e.jsxs(xt,{children:[((O=F.links)==null?void 0:O.length)||0," links"]}),e.jsx(xt,{children:new Date(F.publish_date).toLocaleDateString()}),e.jsx(xt,{children:e.jsx(Xe,{variant:F.is_published?"default":"secondary",children:F.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${F.id}`,"_blank"),children:e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>N(F),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&b.mutate(F.id)},children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},F.id)})})]})})})]})})};function hxs(){for(var s=arguments.length,t=new Array(s),r=0;rn=>{t.forEach(a=>a(n))},t)}const h0e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function O8(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function GAe(s){return"nodeType"in s}function Ag(s){var t,r;return s?O8(s)?s:GAe(s)&&(t=(r=s.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function WAe(s){const{Document:t}=Ag(s);return s instanceof t}function $B(s){return O8(s)?!1:s instanceof Ag(s).HTMLElement}function wft(s){return s instanceof Ag(s).SVGElement}function F8(s){return s?O8(s)?s.document:GAe(s)?WAe(s)?s:$B(s)||wft(s)?s.ownerDocument:document:document:document}const V_=h0e?k.useLayoutEffect:k.useEffect;function KAe(s){const t=k.useRef(s);return V_(()=>{t.current=s}),k.useCallback(function(){for(var r=arguments.length,n=new Array(r),a=0;a{s.current=setInterval(n,a)},[]),r=k.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,r]}function Z9(s,t){t===void 0&&(t=[s]);const r=k.useRef(s);return V_(()=>{r.current!==s&&(r.current=s)},t),r}function UB(s,t){const r=k.useRef();return k.useMemo(()=>{const n=s(r.current);return r.current=n,n},[...t])}function Efe(s){const t=KAe(s),r=k.useRef(null),n=k.useCallback(a=>{a!==r.current&&(t==null||t(a,r.current)),r.current=a},[]);return[r,n]}function ISe(s){const t=k.useRef();return k.useEffect(()=>{t.current=s},[s]),t.current}let ywe={};function qB(s,t){return k.useMemo(()=>{if(t)return t;const r=ywe[s]==null?0:ywe[s]+1;return ywe[s]=r,s+"-"+r},[s,t])}function jft(s){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),a=1;a{const o=Object.entries(l);for(const[c,d]of o){const u=i[c];u!=null&&(i[c]=u+s*d)}return i},{...t})}}const CP=jft(1),X9=jft(-1);function fxs(s){return"clientX"in s&&"clientY"in s}function YAe(s){if(!s)return!1;const{KeyboardEvent:t}=Ag(s.target);return t&&s instanceof t}function pxs(s){if(!s)return!1;const{TouchEvent:t}=Ag(s.target);return t&&s instanceof t}function PSe(s){if(pxs(s)){if(s.touches&&s.touches.length){const{clientX:t,clientY:r}=s.touches[0];return{x:t,y:r}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:t,clientY:r}=s.changedTouches[0];return{x:t,y:r}}}return fxs(s)?{x:s.clientX,y:s.clientY}:null}const zS=Object.freeze({Translate:{toString(s){if(!s)return;const{x:t,y:r}=s;return"translate3d("+(t?Math.round(t):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:t,scaleY:r}=s;return"scaleX("+t+") scaleY("+r+")"}},Transform:{toString(s){if(s)return[zS.Translate.toString(s),zS.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:r,easing:n}=s;return t+" "+r+"ms "+n}}}),gUe="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function xxs(s){return s.matches(gUe)?s:s.querySelector(gUe)}const gxs={display:"none"};function yxs(s){let{id:t,value:r}=s;return Ct.createElement("div",{id:t,style:gxs},r)}function vxs(s){let{id:t,announcement:r,ariaLiveType:n="assertive"}=s;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Ct.createElement("div",{id:t,style:a,role:"status","aria-live":n,"aria-atomic":!0},r)}function bxs(){const[s,t]=k.useState("");return{announce:k.useCallback(n=>{n!=null&&t(n)},[]),announcement:s}}const Nft=k.createContext(null);function _xs(s){const t=k.useContext(Nft);k.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function wxs(){const[s]=k.useState(()=>new Set),t=k.useCallback(n=>(s.add(n),()=>s.delete(n)),[s]);return[k.useCallback(n=>{let{type:a,event:i}=n;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const jxs={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. `},Nxs={onDragStart(s){let{active:t}=s;return"Picked up draggable item "+t.id+"."},onDragOver(s){let{active:t,over:r}=s;return r?"Draggable item "+t.id+" was moved over droppable area "+r.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(s){let{active:t,over:r}=s;return r?"Draggable item "+t.id+" was dropped over droppable area "+r.id:"Draggable item "+t.id+" was dropped."},onDragCancel(s){let{active:t}=s;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function kxs(s){let{announcements:t=Nxs,container:r,hiddenTextDescribedById:n,screenReaderInstructions:a=jxs}=s;const{announce:i,announcement:l}=bxs(),o=qB("DndLiveRegion"),[c,d]=k.useState(!1);if(k.useEffect(()=>{d(!0)},[]),_xs(k.useMemo(()=>({onDragStart(m){let{active:f}=m;i(t.onDragStart({active:f}))},onDragMove(m){let{active:f,over:x}=m;t.onDragMove&&i(t.onDragMove({active:f,over:x}))},onDragOver(m){let{active:f,over:x}=m;i(t.onDragOver({active:f,over:x}))},onDragEnd(m){let{active:f,over:x}=m;i(t.onDragEnd({active:f,over:x}))},onDragCancel(m){let{active:f,over:x}=m;i(t.onDragCancel({active:f,over:x}))}}),[i,t])),!c)return null;const u=Ct.createElement(Ct.Fragment,null,Ct.createElement(yxs,{id:n,value:a.draggable}),Ct.createElement(vxs,{id:o,announcement:l}));return r?vx.createPortal(u,r):u}var om;(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"})(om||(om={}));function Afe(){}function NL(s,t){return k.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function m0e(){for(var s=arguments.length,t=new Array(s),r=0;r[...t].filter(n=>n!=null),[...t])}const B1=Object.freeze({x:0,y:0});function kft(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function Sft(s,t){let{data:{value:r}}=s,{data:{value:n}}=t;return r-n}function Sxs(s,t){let{data:{value:r}}=s,{data:{value:n}}=t;return n-r}function yUe(s){let{left:t,top:r,height:n,width:a}=s;return[{x:t,y:r},{x:t+a,y:r},{x:t,y:r+n},{x:t+a,y:r+n}]}function Cft(s,t){if(!s||s.length===0)return null;const[r]=s;return r[t]}function vUe(s,t,r){return t===void 0&&(t=s.left),r===void 0&&(r=s.top),{x:t+s.width*.5,y:r+s.height*.5}}const f0e=s=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=vUe(t,t.left,t.top),i=[];for(const l of n){const{id:o}=l,c=r.get(o);if(c){const d=kft(vUe(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(Sft)},Cxs=s=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=yUe(t),i=[];for(const l of n){const{id:o}=l,c=r.get(o);if(c){const d=yUe(c),u=a.reduce((f,x,y)=>f+kft(d[y],x),0),m=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:m}})}}return i.sort(Sft)};function Txs(s,t){const r=Math.max(t.top,s.top),n=Math.max(t.left,s.left),a=Math.min(t.left+t.width,s.left+s.width),i=Math.min(t.top+t.height,s.top+s.height),l=a-n,o=i-r;if(n{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=[];for(const i of n){const{id:l}=i,o=r.get(l);if(o){const c=Txs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(Sxs)};function Axs(s,t,r){return{...s,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function Tft(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:B1}function Mxs(s){return function(r){for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i({...l,top:l.top+s*o.y,bottom:l.bottom+s*o.y,left:l.left+s*o.x,right:l.right+s*o.x}),{...r})}}const Ixs=Mxs(1);function Pxs(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 Lxs(s,t,r){const n=Pxs(t);if(!n)return s;const{scaleX:a,scaleY:i,x:l,y:o}=n,c=s.left-l-(1-a)*parseFloat(r),d=s.top-o-(1-i)*parseFloat(r.slice(r.indexOf(" ")+1)),u=a?s.width/a:s.width,m=i?s.height/i:s.height;return{width:u,height:m,top:d,right:c+u,bottom:d+m,left:c}}const Dxs={ignoreTransform:!1};function z8(s,t){t===void 0&&(t=Dxs);let r=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=Ag(s).getComputedStyle(s);d&&(r=Lxs(r,d,u))}const{top:n,left:a,width:i,height:l,bottom:o,right:c}=r;return{top:n,left:a,width:i,height:l,bottom:o,right:c}}function bUe(s){return z8(s,{ignoreTransform:!0})}function Rxs(s){const t=s.innerWidth,r=s.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function Oxs(s,t){return t===void 0&&(t=Ag(s).getComputedStyle(s)),t.position==="fixed"}function Fxs(s,t){t===void 0&&(t=Ag(s).getComputedStyle(s));const r=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const i=t[a];return typeof i=="string"?r.test(i):!1})}function p0e(s,t){const r=[];function n(a){if(t!=null&&r.length>=t||!a)return r;if(WAe(a)&&a.scrollingElement!=null&&!r.includes(a.scrollingElement))return r.push(a.scrollingElement),r;if(!$B(a)||wft(a)||r.includes(a))return r;const i=Ag(s).getComputedStyle(a);return a!==s&&Fxs(a,i)&&r.push(a),Oxs(a,i)?r:n(a.parentNode)}return s?n(s):r}function Eft(s){const[t]=p0e(s,1);return t??null}function vwe(s){return!h0e||!s?null:O8(s)?s:GAe(s)?WAe(s)||s===F8(s).scrollingElement?window:$B(s)?s:null:null}function Aft(s){return O8(s)?s.scrollX:s.scrollLeft}function Mft(s){return O8(s)?s.scrollY:s.scrollTop}function LSe(s){return{x:Aft(s),y:Mft(s)}}var Jm;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(Jm||(Jm={}));function Ift(s){return!h0e||!s?!1:s===document.scrollingElement}function Pft(s){const t={x:0,y:0},r=Ift(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},n={x:s.scrollWidth-r.width,y:s.scrollHeight-r.height},a=s.scrollTop<=t.y,i=s.scrollLeft<=t.x,l=s.scrollTop>=n.y,o=s.scrollLeft>=n.x;return{isTop:a,isLeft:i,isBottom:l,isRight:o,maxScroll:n,minScroll:t}}const zxs={x:.2,y:.2};function Bxs(s,t,r,n,a){let{top:i,left:l,right:o,bottom:c}=r;n===void 0&&(n=10),a===void 0&&(a=zxs);const{isTop:d,isBottom:u,isLeft:m,isRight:f}=Pft(s),x={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?(x.y=Jm.Backward,y.y=n*Math.abs((t.top+_.height-i)/_.height)):!u&&c>=t.bottom-_.height&&(x.y=Jm.Forward,y.y=n*Math.abs((t.bottom-_.height-c)/_.height)),!f&&o>=t.right-_.width?(x.x=Jm.Forward,y.x=n*Math.abs((t.right-_.width-o)/_.width)):!m&&l<=t.left+_.width&&(x.x=Jm.Backward,y.x=n*Math.abs((t.left+_.width-l)/_.width)),{direction:x,speed:y}}function $xs(s){if(s===document.scrollingElement){const{innerWidth:i,innerHeight:l}=window;return{top:0,left:0,right:i,bottom:l,width:i,height:l}}const{top:t,left:r,right:n,bottom:a}=s.getBoundingClientRect();return{top:t,left:r,right:n,bottom:a,width:s.clientWidth,height:s.clientHeight}}function Lft(s){return s.reduce((t,r)=>CP(t,LSe(r)),B1)}function Uxs(s){return s.reduce((t,r)=>t+Aft(r),0)}function qxs(s){return s.reduce((t,r)=>t+Mft(r),0)}function Vxs(s,t){if(t===void 0&&(t=z8),!s)return;const{top:r,left:n,bottom:a,right:i}=t(s);Eft(s)&&(a<=0||i<=0||r>=window.innerHeight||n>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const Hxs=[["x",["left","right"],Uxs],["y",["top","bottom"],qxs]];class ZAe{constructor(t,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const n=p0e(r),a=Lft(n);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of Hxs)for(const c of l)Object.defineProperty(this,c,{get:()=>{const d=o(n),u=a[i]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class R7{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(r=>{var n;return(n=this.target)==null?void 0:n.removeEventListener(...r)})},this.target=t}add(t,r,n){var a;(a=this.target)==null||a.addEventListener(t,r,n),this.listeners.push([t,r,n])}}function Gxs(s){const{EventTarget:t}=Ag(s);return s instanceof t?s:F8(s)}function bwe(s,t){const r=Math.abs(s.x),n=Math.abs(s.y);return typeof t=="number"?Math.sqrt(r**2+n**2)>t:"x"in t&&"y"in t?r>t.x&&n>t.y:"x"in t?r>t.x:"y"in t?n>t.y:!1}var Dy;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(Dy||(Dy={}));function _Ue(s){s.preventDefault()}function Wxs(s){s.stopPropagation()}var wl;(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"})(wl||(wl={}));const Dft={start:[wl.Space,wl.Enter],cancel:[wl.Esc],end:[wl.Space,wl.Enter,wl.Tab]},Kxs=(s,t)=>{let{currentCoordinates:r}=t;switch(s.code){case wl.Right:return{...r,x:r.x+25};case wl.Left:return{...r,x:r.x-25};case wl.Down:return{...r,y:r.y+25};case wl.Up:return{...r,y:r.y-25}}};class x0e{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:r}}=t;this.props=t,this.listeners=new R7(F8(r)),this.windowListeners=new R7(Ag(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Dy.Resize,this.handleCancel),this.windowListeners.add(Dy.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Dy.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,n=t.node.current;n&&Vxs(n),r(B1)}handleKeyDown(t){if(YAe(t)){const{active:r,context:n,options:a}=this.props,{keyboardCodes:i=Dft,coordinateGetter:l=Kxs,scrollBehavior:o="smooth"}=a,{code:c}=t;if(i.end.includes(c)){this.handleEnd(t);return}if(i.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:d}=n.current,u=d?{x:d.left,y:d.top}:B1;this.referenceCoordinates||(this.referenceCoordinates=u);const m=l(t,{active:r,context:n.current,currentCoordinates:u});if(m){const f=X9(m,u),x={x:0,y:0},{scrollableAncestors:y}=n.current;for(const _ of y){const b=t.code,{isTop:j,isRight:N,isLeft:C,isBottom:A,maxScroll:E,minScroll:D}=Pft(_),R=$xs(_),F={x:Math.min(b===wl.Right?R.right-R.width/2:R.right,Math.max(b===wl.Right?R.left:R.left+R.width/2,m.x)),y:Math.min(b===wl.Down?R.bottom-R.height/2:R.bottom,Math.max(b===wl.Down?R.top:R.top+R.height/2,m.y))},O=b===wl.Right&&!N||b===wl.Left&&!C,B=b===wl.Down&&!A||b===wl.Up&&!j;if(O&&F.x!==m.x){const K=_.scrollLeft+f.x,Z=b===wl.Right&&K<=E.x||b===wl.Left&&K>=D.x;if(Z&&!f.y){_.scrollTo({left:K,behavior:o});return}Z?x.x=_.scrollLeft-K:x.x=b===wl.Right?_.scrollLeft-E.x:_.scrollLeft-D.x,x.x&&_.scrollBy({left:-x.x,behavior:o});break}else if(B&&F.y!==m.y){const K=_.scrollTop+f.y,Z=b===wl.Down&&K<=E.y||b===wl.Up&&K>=D.y;if(Z&&!f.x){_.scrollTo({top:K,behavior:o});return}Z?x.y=_.scrollTop-K:x.y=b===wl.Down?_.scrollTop-E.y:_.scrollTop-D.y,x.y&&_.scrollBy({top:-x.y,behavior:o});break}}this.handleMove(t,CP(X9(m,this.referenceCoordinates),x))}}}handleMove(t,r){const{onMove:n}=this.props;t.preventDefault(),n(r)}handleEnd(t){const{onEnd:r}=this.props;t.preventDefault(),this.detach(),r()}handleCancel(t){const{onCancel:r}=this.props;t.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}x0e.activators=[{eventName:"onKeyDown",handler:(s,t,r)=>{let{keyboardCodes:n=Dft,onActivation:a}=t,{active:i}=r;const{code:l}=s.nativeEvent;if(n.start.includes(l)){const o=i.activatorNode.current;return o&&s.target!==o?!1:(s.preventDefault(),a==null||a({event:s.nativeEvent}),!0)}return!1}}];function wUe(s){return!!(s&&"distance"in s)}function jUe(s){return!!(s&&"delay"in s)}class XAe{constructor(t,r,n){var a;n===void 0&&(n=Gxs(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=r;const{event:i}=t,{target:l}=i;this.props=t,this.events=r,this.document=F8(l),this.documentListeners=new R7(this.document),this.listeners=new R7(n),this.windowListeners=new R7(Ag(l)),this.initialCoordinates=(a=PSe(i))!=null?a:B1,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:r,bypassActivationConstraint:n}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(Dy.Resize,this.handleCancel),this.windowListeners.add(Dy.DragStart,_Ue),this.windowListeners.add(Dy.VisibilityChange,this.handleCancel),this.windowListeners.add(Dy.ContextMenu,_Ue),this.documentListeners.add(Dy.Keydown,this.handleKeydown),r){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(jUe(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(wUe(r)){this.handlePending(r);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,r){const{active:n,onPending:a}=this.props;a(n,t,this.initialCoordinates,r)}handleStart(){const{initialCoordinates:t}=this,{onStart:r}=this.props;t&&(this.activated=!0,this.documentListeners.add(Dy.Click,Wxs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Dy.SelectionChange,this.removeTextSelection),r(t))}handleMove(t){var r;const{activated:n,initialCoordinates:a,props:i}=this,{onMove:l,options:{activationConstraint:o}}=i;if(!a)return;const c=(r=PSe(t))!=null?r:B1,d=X9(a,c);if(!n&&o){if(wUe(o)){if(o.tolerance!=null&&bwe(d,o.tolerance))return this.handleCancel();if(bwe(d,o.distance))return this.handleStart()}if(jUe(o)&&bwe(d,o.tolerance))return this.handleCancel();this.handlePending(o,d);return}t.cancelable&&t.preventDefault(),l(c)}handleEnd(){const{onAbort:t,onEnd:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleCancel(){const{onAbort:t,onCancel:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleKeydown(t){t.code===wl.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const Yxs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class B8 extends XAe{constructor(t){const{event:r}=t,n=F8(r.target);super(t,Yxs,n)}}B8.activators=[{eventName:"onPointerDown",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;return!r.isPrimary||r.button!==0?!1:(n==null||n({event:r}),!0)}}];const Zxs={move:{name:"mousemove"},end:{name:"mouseup"}};var DSe;(function(s){s[s.RightClick=2]="RightClick"})(DSe||(DSe={}));class Xxs extends XAe{constructor(t){super(t,Zxs,F8(t.event.target))}}Xxs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;return r.button===DSe.RightClick?!1:(n==null||n({event:r}),!0)}}];const _we={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class Qxs extends XAe{constructor(t){super(t,_we)}static setup(){return window.addEventListener(_we.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(_we.move.name,t)};function t(){}}}Qxs.activators=[{eventName:"onTouchStart",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;const{touches:a}=r;return a.length>1?!1:(n==null||n({event:r}),!0)}}];var O7;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(O7||(O7={}));var Mfe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Mfe||(Mfe={}));function Jxs(s){let{acceleration:t,activator:r=O7.Pointer,canScroll:n,draggingRect:a,enabled:i,interval:l=5,order:o=Mfe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:m,threshold:f}=s;const x=tgs({delta:m,disabled:!i}),[y,_]=mxs(),b=k.useRef({x:0,y:0}),j=k.useRef({x:0,y:0}),N=k.useMemo(()=>{switch(r){case O7.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case O7.DraggableRect:return a}},[r,a,c]),C=k.useRef(null),A=k.useCallback(()=>{const D=C.current;if(!D)return;const R=b.current.x*j.current.x,F=b.current.y*j.current.y;D.scrollBy(R,F)},[]),E=k.useMemo(()=>o===Mfe.TreeOrder?[...d].reverse():d,[o,d]);k.useEffect(()=>{if(!i||!d.length||!N){_();return}for(const D of E){if((n==null?void 0:n(D))===!1)continue;const R=d.indexOf(D),F=u[R];if(!F)continue;const{direction:O,speed:B}=Bxs(D,F,N,t,f);for(const K of["x","y"])x[K][O[K]]||(B[K]=0,O[K]=0);if(B.x>0||B.y>0){_(),C.current=D,y(A,l),b.current=B,j.current=O;return}}b.current={x:0,y:0},j.current={x:0,y:0},_()},[t,A,n,_,i,l,JSON.stringify(N),JSON.stringify(x),y,d,E,u,JSON.stringify(f)])}const egs={x:{[Jm.Backward]:!1,[Jm.Forward]:!1},y:{[Jm.Backward]:!1,[Jm.Forward]:!1}};function tgs(s){let{delta:t,disabled:r}=s;const n=ISe(t);return UB(a=>{if(r||!n||!a)return egs;const i={x:Math.sign(t.x-n.x),y:Math.sign(t.y-n.y)};return{x:{[Jm.Backward]:a.x[Jm.Backward]||i.x===-1,[Jm.Forward]:a.x[Jm.Forward]||i.x===1},y:{[Jm.Backward]:a.y[Jm.Backward]||i.y===-1,[Jm.Forward]:a.y[Jm.Forward]||i.y===1}}},[r,t,n])}function sgs(s,t){const r=t!=null?s.get(t):void 0,n=r?r.node.current:null;return UB(a=>{var i;return t==null?null:(i=n??a)!=null?i:null},[n,t])}function rgs(s,t){return k.useMemo(()=>s.reduce((r,n)=>{const{sensor:a}=n,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,n)}));return[...r,...i]},[]),[s,t])}var Q9;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(Q9||(Q9={}));var RSe;(function(s){s.Optimized="optimized"})(RSe||(RSe={}));const NUe=new Map;function ngs(s,t){let{dragging:r,dependencies:n,config:a}=t;const[i,l]=k.useState(null),{frequency:o,measure:c,strategy:d}=a,u=k.useRef(s),m=b(),f=Z9(m),x=k.useCallback(function(j){j===void 0&&(j=[]),!f.current&&l(N=>N===null?j:N.concat(j.filter(C=>!N.includes(C))))},[f]),y=k.useRef(null),_=UB(j=>{if(m&&!r)return NUe;if(!j||j===NUe||u.current!==s||i!=null){const N=new Map;for(let C of s){if(!C)continue;if(i&&i.length>0&&!i.includes(C.id)&&C.rect.current){N.set(C.id,C.rect.current);continue}const A=C.node.current,E=A?new ZAe(c(A),A):null;C.rect.current=E,E&&N.set(C.id,E)}return N}return j},[s,i,r,m,c]);return k.useEffect(()=>{u.current=s},[s]),k.useEffect(()=>{m||x()},[r,m]),k.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),k.useEffect(()=>{m||typeof o!="number"||y.current!==null||(y.current=setTimeout(()=>{x(),y.current=null},o))},[o,m,x,...n]),{droppableRects:_,measureDroppableContainers:x,measuringScheduled:i!=null};function b(){switch(d){case Q9.Always:return!1;case Q9.BeforeDragging:return r;default:return!r}}}function Rft(s,t){return UB(r=>s?r||(typeof t=="function"?t(s):s):null,[t,s])}function ags(s,t){return Rft(s,t)}function igs(s){let{callback:t,disabled:r}=s;const n=KAe(t),a=k.useMemo(()=>{if(r||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(n)},[n,r]);return k.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function g0e(s){let{callback:t,disabled:r}=s;const n=KAe(t),a=k.useMemo(()=>{if(r||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(n)},[r]);return k.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function ogs(s){return new ZAe(z8(s),s)}function kUe(s,t,r){t===void 0&&(t=ogs);const[n,a]=k.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??r)!=null?d:null}const u=t(s);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const l=igs({callback(c){if(s)for(const d of c){const{type:u,target:m}=d;if(u==="childList"&&m instanceof HTMLElement&&m.contains(s)){i();break}}}}),o=g0e({callback:i});return V_(()=>{i(),s?(o==null||o.observe(s),l==null||l.observe(document.body,{childList:!0,subtree:!0})):(o==null||o.disconnect(),l==null||l.disconnect())},[s]),n}function lgs(s){const t=Rft(s);return Tft(s,t)}const SUe=[];function cgs(s){const t=k.useRef(s),r=UB(n=>s?n&&n!==SUe&&s&&t.current&&s.parentNode===t.current.parentNode?n:p0e(s):SUe,[s]);return k.useEffect(()=>{t.current=s},[s]),r}function dgs(s){const[t,r]=k.useState(null),n=k.useRef(s),a=k.useCallback(i=>{const l=vwe(i.target);l&&r(o=>o?(o.set(l,LSe(l)),new Map(o)):null)},[]);return k.useEffect(()=>{const i=n.current;if(s!==i){l(i);const o=s.map(c=>{const d=vwe(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,LSe(d)]):null}).filter(c=>c!=null);r(o.length?new Map(o):null),n.current=s}return()=>{l(s),l(i)};function l(o){o.forEach(c=>{const d=vwe(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),k.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>CP(i,l),B1):Lft(s):B1,[s,t])}function CUe(s,t){t===void 0&&(t=[]);const r=k.useRef(null);return k.useEffect(()=>{r.current=null},t),k.useEffect(()=>{const n=s!==B1;n&&!r.current&&(r.current=s),!n&&r.current&&(r.current=null)},[s]),r.current?X9(s,r.current):B1}function ugs(s){k.useEffect(()=>{if(!h0e)return;const t=s.map(r=>{let{sensor:n}=r;return n.setup==null?void 0:n.setup()});return()=>{for(const r of t)r==null||r()}},s.map(t=>{let{sensor:r}=t;return r}))}function hgs(s,t){return k.useMemo(()=>s.reduce((r,n)=>{let{eventName:a,handler:i}=n;return r[a]=l=>{i(l,t)},r},{}),[s,t])}function Oft(s){return k.useMemo(()=>s?Rxs(s):null,[s])}const TUe=[];function mgs(s,t){t===void 0&&(t=z8);const[r]=s,n=Oft(r?Ag(r):null),[a,i]=k.useState(TUe);function l(){i(()=>s.length?s.map(c=>Ift(c)?n:new ZAe(t(c),c)):TUe)}const o=g0e({callback:l});return V_(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function fgs(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return $B(t)?t:s}function pgs(s){let{measure:t}=s;const[r,n]=k.useState(null),a=k.useCallback(d=>{for(const{target:u}of d)if($B(u)){n(m=>{const f=t(u);return m?{...m,width:f.width,height:f.height}:f});break}},[t]),i=g0e({callback:a}),l=k.useCallback(d=>{const u=fgs(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),n(u?t(u):null)},[t,i]),[o,c]=Efe(l);return k.useMemo(()=>({nodeRef:o,rect:r,setRef:c}),[r,o,c])}const xgs=[{sensor:B8,options:{}},{sensor:x0e,options:{}}],ggs={current:{}},ohe={draggable:{measure:bUe},droppable:{measure:bUe,strategy:Q9.WhileDragging,frequency:RSe.Optimized},dragOverlay:{measure:z8}};class F7 extends Map{get(t){var r;return t!=null&&(r=super.get(t))!=null?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:r}=t;return!r})}getNodeFor(t){var r,n;return(r=(n=this.get(t))==null?void 0:n.node.current)!=null?r:void 0}}const ygs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new F7,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Afe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:ohe,measureDroppableContainers:Afe,windowRect:null,measuringScheduled:!1},vgs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Afe,draggableNodes:new Map,over:null,measureDroppableContainers:Afe},y0e=k.createContext(vgs),Fft=k.createContext(ygs);function bgs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new F7}}}function _gs(s,t){switch(t.type){case om.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case om.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 om.DragEnd:case om.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case om.RegisterDroppable:{const{element:r}=t,{id:n}=r,a=new F7(s.droppable.containers);return a.set(n,r),{...s,droppable:{...s.droppable,containers:a}}}case om.SetDroppableDisabled:{const{id:r,key:n,disabled:a}=t,i=s.droppable.containers.get(r);if(!i||n!==i.key)return s;const l=new F7(s.droppable.containers);return l.set(r,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case om.UnregisterDroppable:{const{id:r,key:n}=t,a=s.droppable.containers.get(r);if(!a||n!==a.key)return s;const i=new F7(s.droppable.containers);return i.delete(r),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function wgs(s){let{disabled:t}=s;const{active:r,activatorEvent:n,draggableNodes:a}=k.useContext(y0e),i=ISe(n),l=ISe(r==null?void 0:r.id);return k.useEffect(()=>{if(!t&&!n&&i&&l!=null){if(!YAe(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 m=xxs(u);if(m){m.focus();break}}})}},[n,t,a,l,i]),null}function jgs(s,t){let{transform:r,...n}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...n}),r):r}function Ngs(s){return k.useMemo(()=>({draggable:{...ohe.draggable,...s==null?void 0:s.draggable},droppable:{...ohe.droppable,...s==null?void 0:s.droppable},dragOverlay:{...ohe.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 kgs(s){let{activeNode:t,measure:r,initialRect:n,config:a=!0}=s;const i=k.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;V_(()=>{if(!l&&!o||!t){i.current=!1;return}if(i.current||!n)return;const d=t==null?void 0:t.node.current;if(!d||d.isConnected===!1)return;const u=r(d),m=Tft(u,n);if(l||(m.x=0),o||(m.y=0),i.current=!0,Math.abs(m.x)>0||Math.abs(m.y)>0){const f=Eft(d);f&&f.scrollBy({top:m.y,left:m.x})}},[t,l,o,n,r])}const zft=k.createContext({...B1,scaleX:1,scaleY:1});var ck;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(ck||(ck={}));const v0e=k.memo(function(t){var r,n,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=xgs,collisionDetection:m=Exs,measuring:f,modifiers:x,...y}=t;const _=k.useReducer(_gs,void 0,bgs),[b,j]=_,[N,C]=wxs(),[A,E]=k.useState(ck.Uninitialized),D=A===ck.Initialized,{draggable:{active:R,nodes:F,translate:O},droppable:{containers:B}}=b,K=R!=null?F.get(R):null,Z=k.useRef({initial:null,translated:null}),Q=k.useMemo(()=>{var Js;return R!=null?{id:R,data:(Js=K==null?void 0:K.data)!=null?Js:ggs,rect:Z}:null},[R,K]),W=k.useRef(null),[te,ne]=k.useState(null),[ae,ue]=k.useState(null),me=Z9(y,Object.values(y)),de=qB("DndDescribedBy",l),fe=k.useMemo(()=>B.getEnabled(),[B]),je=Ngs(f),{droppableRects:xe,measureDroppableContainers:Ee,measuringScheduled:Me}=ngs(fe,{dragging:D,dependencies:[O.x,O.y],config:je.droppable}),Oe=sgs(F,R),Ie=k.useMemo(()=>ae?PSe(ae):null,[ae]),ze=$s(),Ve=ags(Oe,je.draggable.measure);kgs({activeNode:R!=null?F.get(R):null,config:ze.layoutShiftCompensation,initialRect:Ve,measure:je.draggable.measure});const Le=kUe(Oe,je.draggable.measure,Ve),$e=kUe(Oe?Oe.parentElement:null),ve=k.useRef({activatorEvent:null,active:null,activeNode:Oe,collisionRect:null,collisions:null,droppableRects:xe,draggableNodes:F,draggingNode:null,draggingNodeRect:null,droppableContainers:B,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Qe=B.getNodeFor((r=ve.current.over)==null?void 0:r.id),we=pgs({measure:je.dragOverlay.measure}),nt=(n=we.nodeRef.current)!=null?n:Oe,Se=D?(a=we.rect)!=null?a:Le:null,Ge=!!(we.nodeRef.current&&we.rect),We=lgs(Ge?null:Le),Ce=Oft(nt?Ag(nt):null),qe=cgs(D?Qe??Oe:null),et=mgs(qe),Ze=jgs(x,{transform:{x:O.x-We.x,y:O.y-We.y,scaleX:1,scaleY:1},activatorEvent:ae,active:Q,activeNodeRect:Le,containerNodeRect:$e,draggingNodeRect:Se,over:ve.current.over,overlayNodeRect:we.rect,scrollableAncestors:qe,scrollableAncestorRects:et,windowRect:Ce}),rt=Ie?CP(Ie,O):null,ct=dgs(qe),vt=CUe(ct),kt=CUe(ct,[Le]),St=CP(Ze,vt),Yt=Se?Ixs(Se,Ze):null,es=Q&&Yt?m({active:Q,collisionRect:Yt,droppableRects:xe,droppableContainers:fe,pointerCoordinates:rt}):null,zs=Cft(es,"id"),[sr,ms]=k.useState(null),gt=Ge?Ze:CP(Ze,kt),Ut=Axs(gt,(i=sr==null?void 0:sr.rect)!=null?i:null,Le),ht=k.useRef(null),Jt=k.useCallback((Js,or)=>{let{sensor:Er,options:Sr}=or;if(W.current==null)return;const Gr=F.get(W.current);if(!Gr)return;const Yr=Js.nativeEvent,Fn=new Er({active:W.current,activeNode:Gr,event:Yr,options:Sr,context:ve,onAbort(gs){if(!F.get(gs))return;const{onDragAbort:In}=me.current,Br={id:gs};In==null||In(Br),N({type:"onDragAbort",event:Br})},onPending(gs,mi,In,Br){if(!F.get(gs))return;const{onDragPending:Or}=me.current,Qr={id:gs,constraint:mi,initialCoordinates:In,offset:Br};Or==null||Or(Qr),N({type:"onDragPending",event:Qr})},onStart(gs){const mi=W.current;if(mi==null)return;const In=F.get(mi);if(!In)return;const{onDragStart:Br}=me.current,ps={activatorEvent:Yr,active:{id:mi,data:In.data,rect:Z}};vx.unstable_batchedUpdates(()=>{Br==null||Br(ps),E(ck.Initializing),j({type:om.DragStart,initialCoordinates:gs,active:mi}),N({type:"onDragStart",event:ps}),ne(ht.current),ue(Yr)})},onMove(gs){j({type:om.DragMove,coordinates:gs})},onEnd:sa(om.DragEnd),onCancel:sa(om.DragCancel)});ht.current=Fn;function sa(gs){return async function(){const{active:In,collisions:Br,over:ps,scrollAdjustedTranslate:Or}=ve.current;let Qr=null;if(In&&Or){const{cancelDrop:Tn}=me.current;Qr={activatorEvent:Yr,active:In,collisions:Br,delta:Or,over:ps},gs===om.DragEnd&&typeof Tn=="function"&&await Promise.resolve(Tn(Qr))&&(gs=om.DragCancel)}W.current=null,vx.unstable_batchedUpdates(()=>{j({type:gs}),E(ck.Uninitialized),ms(null),ne(null),ue(null),ht.current=null;const Tn=gs===om.DragEnd?"onDragEnd":"onDragCancel";if(Qr){const Qt=me.current[Tn];Qt==null||Qt(Qr),N({type:Tn,event:Qr})}})}}},[F]),Ms=k.useCallback((Js,or)=>(Er,Sr)=>{const Gr=Er.nativeEvent,Yr=F.get(Sr);if(W.current!==null||!Yr||Gr.dndKit||Gr.defaultPrevented)return;const Fn={active:Yr};Js(Er,or.options,Fn)===!0&&(Gr.dndKit={capturedBy:or.sensor},W.current=Sr,Jt(Er,or))},[F,Jt]),ts=rgs(u,Ms);ugs(u),V_(()=>{Le&&A===ck.Initializing&&E(ck.Initialized)},[Le,A]),k.useEffect(()=>{const{onDragMove:Js}=me.current,{active:or,activatorEvent:Er,collisions:Sr,over:Gr}=ve.current;if(!or||!Er)return;const Yr={active:or,activatorEvent:Er,collisions:Sr,delta:{x:St.x,y:St.y},over:Gr};vx.unstable_batchedUpdates(()=>{Js==null||Js(Yr),N({type:"onDragMove",event:Yr})})},[St.x,St.y]),k.useEffect(()=>{const{active:Js,activatorEvent:or,collisions:Er,droppableContainers:Sr,scrollAdjustedTranslate:Gr}=ve.current;if(!Js||W.current==null||!or||!Gr)return;const{onDragOver:Yr}=me.current,Fn=Sr.get(zs),sa=Fn&&Fn.rect.current?{id:Fn.id,rect:Fn.rect.current,data:Fn.data,disabled:Fn.disabled}:null,gs={active:Js,activatorEvent:or,collisions:Er,delta:{x:Gr.x,y:Gr.y},over:sa};vx.unstable_batchedUpdates(()=>{ms(sa),Yr==null||Yr(gs),N({type:"onDragOver",event:gs})})},[zs]),V_(()=>{ve.current={activatorEvent:ae,active:Q,activeNode:Oe,collisionRect:Yt,collisions:es,droppableRects:xe,draggableNodes:F,draggingNode:nt,draggingNodeRect:Se,droppableContainers:B,over:sr,scrollableAncestors:qe,scrollAdjustedTranslate:St},Z.current={initial:Se,translated:Yt}},[Q,Oe,es,Yt,F,nt,Se,xe,B,sr,qe,St]),Jxs({...ze,delta:O,draggingRect:Yt,pointerCoordinates:rt,scrollableAncestors:qe,scrollableAncestorRects:et});const Xs=k.useMemo(()=>({active:Q,activeNode:Oe,activeNodeRect:Le,activatorEvent:ae,collisions:es,containerNodeRect:$e,dragOverlay:we,draggableNodes:F,droppableContainers:B,droppableRects:xe,over:sr,measureDroppableContainers:Ee,scrollableAncestors:qe,scrollableAncestorRects:et,measuringConfiguration:je,measuringScheduled:Me,windowRect:Ce}),[Q,Oe,Le,ae,es,$e,we,F,B,xe,sr,Ee,qe,et,je,Me,Ce]),js=k.useMemo(()=>({activatorEvent:ae,activators:ts,active:Q,activeNodeRect:Le,ariaDescribedById:{draggable:de},dispatch:j,draggableNodes:F,over:sr,measureDroppableContainers:Ee}),[ae,ts,Q,Le,j,de,F,sr,Ee]);return Ct.createElement(Nft.Provider,{value:C},Ct.createElement(y0e.Provider,{value:js},Ct.createElement(Fft.Provider,{value:Xs},Ct.createElement(zft.Provider,{value:Ut},d)),Ct.createElement(wgs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Ct.createElement(kxs,{...o,hiddenTextDescribedById:de}));function $s(){const Js=(te==null?void 0:te.autoScrollEnabled)===!1,or=typeof c=="object"?c.enabled===!1:c===!1,Er=D&&!Js&&!or;return typeof c=="object"?{...c,enabled:Er}:{enabled:Er}}}),Sgs=k.createContext(null),EUe="button",Cgs="Draggable";function Tgs(s){let{id:t,data:r,disabled:n=!1,attributes:a}=s;const i=qB(Cgs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:m,over:f}=k.useContext(y0e),{role:x=EUe,roleDescription:y="draggable",tabIndex:_=0}=a??{},b=(c==null?void 0:c.id)===t,j=k.useContext(b?zft:Sgs),[N,C]=Efe(),[A,E]=Efe(),D=hgs(l,t),R=Z9(r);V_(()=>(m.set(t,{id:t,key:i,node:N,activatorNode:A,data:R}),()=>{const O=m.get(t);O&&O.key===i&&m.delete(t)}),[m,t]);const F=k.useMemo(()=>({role:x,tabIndex:_,"aria-disabled":n,"aria-pressed":b&&x===EUe?!0:void 0,"aria-roledescription":y,"aria-describedby":u.draggable}),[n,x,_,b,y,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:F,isDragging:b,listeners:n?void 0:D,node:N,over:f,setNodeRef:C,setActivatorNodeRef:E,transform:j}}function Egs(){return k.useContext(Fft)}const Ags="Droppable",Mgs={timeout:25};function Igs(s){let{data:t,disabled:r=!1,id:n,resizeObserverConfig:a}=s;const i=qB(Ags),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=k.useContext(y0e),u=k.useRef({disabled:r}),m=k.useRef(!1),f=k.useRef(null),x=k.useRef(null),{disabled:y,updateMeasurementsFor:_,timeout:b}={...Mgs,...a},j=Z9(_??n),N=k.useCallback(()=>{if(!m.current){m.current=!0;return}x.current!=null&&clearTimeout(x.current),x.current=setTimeout(()=>{d(Array.isArray(j.current)?j.current:[j.current]),x.current=null},b)},[b]),C=g0e({callback:N,disabled:y||!l}),A=k.useCallback((F,O)=>{C&&(O&&(C.unobserve(O),m.current=!1),F&&C.observe(F))},[C]),[E,D]=Efe(A),R=Z9(t);return k.useEffect(()=>{!C||!E.current||(C.disconnect(),m.current=!1,C.observe(E.current))},[E,C]),k.useEffect(()=>(o({type:om.RegisterDroppable,element:{id:n,key:i,disabled:r,node:E,rect:f,data:R}}),()=>o({type:om.UnregisterDroppable,key:i,id:n})),[n]),k.useEffect(()=>{r!==u.current.disabled&&(o({type:om.SetDroppableDisabled,id:n,key:i,disabled:r}),u.current.disabled=r)},[n,i,r,o]),{active:l,rect:f,isOver:(c==null?void 0:c.id)===n,node:E,over:c,setNodeRef:D}}function b0e(s,t,r){const n=s.slice();return n.splice(r<0?n.length+r:r,0,n.splice(t,1)[0]),n}function Pgs(s,t){return s.reduce((r,n,a)=>{const i=t.get(n);return i&&(r[a]=i),r},Array(s.length))}function Jq(s){return s!==null&&s>=0}function Lgs(s,t){if(s===t)return!0;if(s.length!==t.length)return!1;for(let r=0;r{var t;let{rects:r,activeNodeRect:n,activeIndex:a,overIndex:i,index:l}=s;const o=(t=r[a])!=null?t:n;if(!o)return null;const c=Rgs(r,l,a);if(l===a){const d=r[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...eV}:l=i?{x:o.width+c,y:0,...eV}:{x:0,y:0,...eV}};function Rgs(s,t,r){const n=s[t],a=s[t-1],i=s[t+1];return!n||!a&&!i?0:r{let{rects:t,activeIndex:r,overIndex:n,index:a}=s;const i=b0e(t,n,r),l=t[a],o=i[a];return!o||!l?null:{x:o.left-l.left,y:o.top-l.top,scaleX:o.width/l.width,scaleY:o.height/l.height}},tV={scaleX:1,scaleY:1},Ogs=s=>{var t;let{activeIndex:r,activeNodeRect:n,index:a,rects:i,overIndex:l}=s;const o=(t=i[r])!=null?t:n;if(!o)return null;if(a===r){const d=i[l];return d?{x:0,y:rr&&a<=l?{x:0,y:-o.height-c,...tV}:a=l?{x:0,y:o.height+c,...tV}:{x:0,y:0,...tV}};function Fgs(s,t,r){const n=s[t],a=s[t-1],i=s[t+1];return n?rn.map(D=>typeof D=="object"&&"id"in D?D.id:D),[n]),y=l!=null,_=l?x.indexOf(l.id):-1,b=d?x.indexOf(d.id):-1,j=k.useRef(x),N=!Lgs(x,j.current),C=b!==-1&&_===-1||N,A=Dgs(i);V_(()=>{N&&y&&u(x)},[N,x,y,u]),k.useEffect(()=>{j.current=x},[x]);const E=k.useMemo(()=>({activeIndex:_,containerId:m,disabled:A,disableTransforms:C,items:x,overIndex:b,useDragOverlay:f,sortedRects:Pgs(x,c),strategy:a}),[_,m,A.draggable,A.droppable,C,x,b,c,f,a]);return Ct.createElement($ft.Provider,{value:E},t)}const zgs=s=>{let{id:t,items:r,activeIndex:n,overIndex:a}=s;return b0e(r,n,a).indexOf(t)},Bgs=s=>{let{containerId:t,isSorting:r,wasDragging:n,index:a,items:i,newIndex:l,previousItems:o,previousContainerId:c,transition:d}=s;return!d||!n||o!==i&&a===l?!1:r?!0:l!==a&&t===c},$gs={duration:200,easing:"ease"},Uft="transform",Ugs=zS.Transition.toString({property:Uft,duration:0,easing:"linear"}),qgs={roleDescription:"sortable"};function Vgs(s){let{disabled:t,index:r,node:n,rect:a}=s;const[i,l]=k.useState(null),o=k.useRef(r);return V_(()=>{if(!t&&r!==o.current&&n.current){const c=a.current;if(c){const d=z8(n.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)}}r!==o.current&&(o.current=r)},[t,r,n,a]),k.useEffect(()=>{i&&l(null)},[i]),i}function w0e(s){let{animateLayoutChanges:t=Bgs,attributes:r,disabled:n,data:a,getNewIndex:i=zgs,id:l,strategy:o,resizeObserverConfig:c,transition:d=$gs}=s;const{items:u,containerId:m,activeIndex:f,disabled:x,disableTransforms:y,sortedRects:_,overIndex:b,useDragOverlay:j,strategy:N}=k.useContext($ft),C=Hgs(n,x),A=u.indexOf(l),E=k.useMemo(()=>({sortable:{containerId:m,index:A,items:u},...a}),[m,a,A,u]),D=k.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:R,node:F,isOver:O,setNodeRef:B}=Igs({id:l,data:E,disabled:C.droppable,resizeObserverConfig:{updateMeasurementsFor:D,...c}}),{active:K,activatorEvent:Z,activeNodeRect:Q,attributes:W,setNodeRef:te,listeners:ne,isDragging:ae,over:ue,setActivatorNodeRef:me,transform:de}=Tgs({id:l,data:E,attributes:{...qgs,...r},disabled:C.draggable}),fe=hxs(B,te),je=!!K,xe=je&&!y&&Jq(f)&&Jq(b),Ee=!j&&ae,Me=Ee&&xe?de:null,Ie=xe?Me??(o??N)({rects:_,activeNodeRect:Q,activeIndex:f,overIndex:b,index:A}):null,ze=Jq(f)&&Jq(b)?i({id:l,items:u,activeIndex:f,overIndex:b}):A,Ve=K==null?void 0:K.id,Le=k.useRef({activeId:Ve,items:u,newIndex:ze,containerId:m}),$e=u!==Le.current.items,ve=t({active:K,containerId:m,isDragging:ae,isSorting:je,id:l,index:A,items:u,newIndex:Le.current.newIndex,previousItems:Le.current.items,previousContainerId:Le.current.containerId,transition:d,wasDragging:Le.current.activeId!=null}),Qe=Vgs({disabled:!ve,index:A,node:F,rect:R});return k.useEffect(()=>{je&&Le.current.newIndex!==ze&&(Le.current.newIndex=ze),m!==Le.current.containerId&&(Le.current.containerId=m),u!==Le.current.items&&(Le.current.items=u)},[je,ze,m,u]),k.useEffect(()=>{if(Ve===Le.current.activeId)return;if(Ve!=null&&Le.current.activeId==null){Le.current.activeId=Ve;return}const nt=setTimeout(()=>{Le.current.activeId=Ve},50);return()=>clearTimeout(nt)},[Ve]),{active:K,activeIndex:f,attributes:W,data:E,rect:R,index:A,newIndex:ze,items:u,isOver:O,isSorting:je,isDragging:ae,listeners:ne,node:F,overIndex:b,over:ue,setNodeRef:fe,setActivatorNodeRef:me,setDroppableNodeRef:B,setDraggableNodeRef:te,transform:Qe??Ie,transition:we()};function we(){if(Qe||$e&&Le.current.newIndex===A)return Ugs;if(!(Ee&&!YAe(Z)||!d)&&(je||ve))return zS.Transition.toString({...d,property:Uft})}}function Hgs(s,t){var r,n;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(r=s==null?void 0:s.draggable)!=null?r:t.draggable,droppable:(n=s==null?void 0:s.droppable)!=null?n:t.droppable}}function Ife(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 Ggs=[wl.Down,wl.Right,wl.Up,wl.Left],qft=(s,t)=>{let{context:{active:r,collisionRect:n,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(Ggs.includes(s.code)){if(s.preventDefault(),!r||!n)return;const c=[];i.getEnabled().forEach(m=>{if(!m||m!=null&&m.disabled)return;const f=a.get(m.id);if(f)switch(s.code){case wl.Down:n.topf.top&&c.push(m);break;case wl.Left:n.left>f.left&&c.push(m);break;case wl.Right:n.left1&&(u=d[1].id),u!=null){const m=i.get(r.id),f=i.get(u),x=f?a.get(f.id):null,y=f==null?void 0:f.node.current;if(y&&x&&m&&f){const b=p0e(y).some((D,R)=>o[R]!==D),j=Vft(m,f),N=Wgs(m,f),C=b||!j?{x:0,y:0}:{x:N?n.width-x.width:0,y:N?n.height-x.height:0},A={x:x.left,y:x.top};return C.x&&C.y?A:X9(A,C)}}}};function Vft(s,t){return!Ife(s)||!Ife(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function Wgs(s,t){return!Ife(s)||!Ife(t)||!Vft(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>r(s),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Xe,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(vn,{className:"h-2.5 w-2.5"}),As(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:zt("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(vn,{className:"h-3 w-3"}),s.post_date?As(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(Ko,{className:"w-auto p-0",align:"start",children:[e.jsx(_g,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:m=>n(s.id,m?As(m,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(q,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>n(s.id,null),children:"Clear date"})})]})]})]})]})})}const Ygs=()=>{const s=is(),[t,r]=k.useState("all"),[n,a]=k.useState(!1),[i,l]=k.useState(As(new Date,"yyyy-MM")),[o,c]=k.useState([]),[d,u]=k.useState(!1),[m,f]=k.useState(null),[x,y]=k.useState(null),[_,b]=k.useState(""),[j,N]=k.useState(null),[C,A]=k.useState(!1),[E,D]=k.useState(!1),[R,F]=k.useState(As(new Date,"yyyy-MM")),[O,B]=k.useState(null),[K,Z]=k.useState(""),[Q,W]=k.useState(""),[te,ne]=k.useState(""),[ae,ue]=k.useState(!1),me=m0e(NL(B8,{activationConstraint:{distance:5}}),NL(x0e,{coordinateGetter:qft})),{data:de=[],isLoading:fe}=pt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:rt,error:ct}=await U.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ct)throw ct;return rt}}),{data:je=[]}=pt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:rt,error:ct}=await U.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ct)throw ct;return rt}}),{data:xe=[]}=pt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:rt,error:ct}=await U.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ct)throw ct;return rt}}),Ee=[...new Set(de.map(rt=>rt.month))].sort((rt,ct)=>ct.localeCompare(rt)),Me=t==="all"?de:de.filter(rt=>rt.month===t),Oe=rt=>{const ct=hTe(rt,"yyyy-MM",new Date);return As(ct,"MMMM yyyy")},Ie=rt=>{y(rt),b(rt.caption),N(rt.post_date)},ze=async()=>{if(x){A(!0);try{const{error:rt}=await U.from("social_swag_2").update({caption:_,post_date:j}).eq("id",x.id);if(rt)throw rt;he.success("Image updated"),y(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{he.error("Failed to update image")}finally{A(!1)}}},Ve=async rt=>{const{active:ct,over:vt}=rt;if(!vt||ct.id===vt.id)return;const kt=Me,St=kt.findIndex(zs=>zs.id===ct.id),Yt=kt.findIndex(zs=>zs.id===vt.id);if(St===-1||Yt===-1)return;const es=b0e(kt,St,Yt);s.setQueryData(["admin-social-swag-2"],zs=>{if(!zs)return zs;const sr={};return es.forEach((ms,gt)=>{sr[ms.id]=gt}),zs.map(ms=>sr[ms.id]!==void 0?{...ms,sort_order:sr[ms.id]}:ms).sort((ms,gt)=>ms.month!==gt.month?gt.month.localeCompare(ms.month):ms.sort_order-gt.sort_order)});try{await Promise.all(es.map((zs,sr)=>U.from("social_swag_2").update({sort_order:sr}).eq("id",zs.id)))}catch{he.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Le=rt=>{const vt=Array.from(rt.target.files||[]).sort((kt,St)=>kt.name.localeCompare(St.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(kt=>({file:kt,preview:URL.createObjectURL(kt),caption:""}));c(kt=>[...kt,...vt].slice(0,16))},$e=rt=>{c(ct=>{const vt=[...ct];return URL.revokeObjectURL(vt[rt].preview),vt.splice(rt,1),vt})},ve=(rt,ct)=>{c(vt=>{const kt=[...vt];return kt[rt]={...kt[rt],caption:ct},kt})},Qe=async()=>{var ct;if(o.length===0){he.error("Please add at least one image");return}if(o.filter(vt=>!vt.caption.trim()).length>0){he.error("Please add captions to all images");return}u(!0);try{const{data:vt}=await U.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),kt=(((ct=vt==null?void 0:vt[0])==null?void 0:ct.sort_order)??-1)+1;for(let St=0;St{const ct=rt.image_url.split("/social-swag-2/");ct[1]&&await U.storage.from("social-swag-2").remove([ct[1]]);const{error:vt}=await U.from("social_swag_2").delete().eq("id",rt.id);if(vt)throw vt},onSuccess:()=>{he.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>he.error("Failed to delete image")}),nt=Mt({mutationFn:async({id:rt,postDate:ct})=>{const{error:vt}=await U.from("social_swag_2").update({post_date:ct}).eq("id",rt);if(vt)throw vt},onSuccess:()=>{he.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>he.error("Failed to update post date")}),Se=Mt({mutationFn:async({month:rt,link:ct})=>{const{error:vt}=await U.from("social_swag_2_months").upsert({month:rt,canva_link:ct||null},{onConflict:"month"});if(vt)throw vt},onSuccess:()=>{he.success("Canva link updated"),f(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>he.error("Failed to update Canva link")}),Ge=rt=>{var ct;return((ct=je.find(vt=>vt.month===rt))==null?void 0:ct.canva_link)||""},We=rt=>xe.find(ct=>ct.month===rt)||null,Ce=rt=>{var vt;const ct=(vt=rt.target.files)==null?void 0:vt[0];ct&&(B(ct),Z(URL.createObjectURL(ct)))},qe=()=>{K&&URL.revokeObjectURL(K),B(null),Z(""),W(""),ne("")},et=async()=>{if(!O){he.error("Please select an image");return}ue(!0);try{const rt=O.name.split(".").pop(),ct=`reels/${R}-${Date.now()}.${rt}`,{error:vt}=await U.storage.from("social-swag-2").upload(ct,O);if(vt)throw vt;const{data:{publicUrl:kt}}=U.storage.from("social-swag-2").getPublicUrl(ct),{error:St}=await U.from("social_swag_2_reels").upsert({month:R,image_url:kt,canva_link:te||null,caption:Q||null},{onConflict:"month"});if(St)throw St;he.success("Reel uploaded successfully!"),MSe(`${Oe(R)} Reel`,"social-swag-2"),qe(),D(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(rt){console.error("Reel upload error:",rt),he.error("Failed to upload reel")}finally{ue(!1)}},Ze=Mt({mutationFn:async rt=>{const ct=rt.image_url.split("/social-swag-2/");ct[1]&&await U.storage.from("social-swag-2").remove([ct[1]]);const{error:vt}=await U.from("social_swag_2_reels").delete().eq("id",rt.id);if(vt)throw vt},onSuccess:()=>{he.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>he.error("Failed to delete reel")});return e.jsxs(ws,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{open:n,onOpenChange:a,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(ys,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Month"}),e.jsx(Ne,{type:"month",value:i,onChange:rt=>l(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{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:Le,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(ka,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select images (max 16)"})]})]})]}),o.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map((rt,ct)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative aspect-[4/5] rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:rt.preview,alt:`Upload ${ct+1}`,className:"w-full h-full object-cover"}),e.jsx(q,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>$e(ct),children:e.jsx($r,{className:"h-3 w-3"})})]}),e.jsx(pr,{placeholder:"Caption...",value:rt.caption,onChange:vt=>ve(ct,vt.target.value),className:"text-xs h-20"})]},ct))}),e.jsx(q,{onClick:Qe,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(vs,{open:E,onOpenChange:rt=>{D(rt),rt||qe()},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:"gap-2",children:[e.jsx(rf,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(ys,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Month"}),e.jsx(Ne,{type:"month",value:R,onChange:rt=>F(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Reel Preview Image"}),K?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:K,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(q,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(K),B(null),Z("")},children:e.jsx($r,{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:Ce,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(rf,{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(ce,{children:"Canva Download Link"}),e.jsx(Ne,{value:te,onChange:rt=>ne(rt.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Caption"}),e.jsx(pr,{value:Q,onChange:rt=>W(rt.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(q,{onClick:et,disabled:ae||!O,className:"w-full gap-2",children:ae?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:de.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Ee.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ta,{value:t,onValueChange:r,children:e.jsxs(ea,{children:[e.jsx(rs,{value:"all",children:"All"}),Ee.map(rt=>e.jsx(rs,{value:rt,children:Oe(rt)},rt))]})}),t!=="all"&&e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ce,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",Oe(t)]}),(m==null?void 0:m.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(Ne,{value:m.link,onChange:rt=>f({...m,link:rt.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(q,{size:"sm",onClick:()=>Se.mutate(m),children:"Save"}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>f(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:Ge(t)||"No link set"}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>f({month:t,link:Ge(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(rf,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ce,{className:"text-sm text-muted-foreground",children:["Reel for ",Oe(t)]}),(()=>{const rt=We(t);return rt?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:rt.image_url,alt:"Reel preview",className:"w-16 h-28 object-cover rounded"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("p",{className:"line-clamp-2",children:rt.caption||"No caption"}),rt.canva_link&&e.jsx("a",{href:rt.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(q,{variant:"destructive",size:"sm",onClick:()=>Ze.mutate(rt),children:e.jsx(zr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),fe?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):Me.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(zo,{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(v0e,{sensors:me,collisionDetection:f0e,onDragEnd:Ve,children:e.jsx(_0e,{items:Me.map(rt=>rt.id),strategy:VB,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:Me.map(rt=>e.jsx(Kgs,{item:rt,onEdit:Ie,onDelete:ct=>we.mutate(ct),onDateChange:(ct,vt)=>nt.mutate({id:ct,postDate:vt})},rt.id))})})})]}),e.jsx(vs,{open:!!x,onOpenChange:rt=>{rt||y(null)},children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Edit Image"})}),x&&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:x.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Caption"}),e.jsx(pr,{value:_,onChange:rt=>b(rt.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("flex-1 justify-start gap-2 font-normal",!j&&"text-muted-foreground"),children:[e.jsx(vn,{className:"h-4 w-4"}),j?As(new Date(j+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:j?new Date(j+"T00:00:00"):void 0,onSelect:rt=>N(rt?As(rt,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),j&&e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>N(null),children:e.jsx($r,{className:"h-4 w-4"})})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>y(null),children:"Cancel"}),e.jsx(q,{onClick:ze,disabled:C,className:"gap-2",children:C?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},Zgs=()=>{const{toast:s}=Ba(),t=is(),[r,n]=k.useState("categories"),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState({name:"",description:"",icon:""}),[u,m]=k.useState(!1),[f,x]=k.useState(null),[y,_]=k.useState({name:"",description:"",icon:""}),[b,j]=k.useState(!1),[N,C]=k.useState(null),[A,E]=k.useState(""),{data:D=[],isLoading:R}=pt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Ve,error:Le}=await U.from("community_categories").select("*").order("sort_order");if(Le)throw Le;return Ve}}),{data:F=[],isLoading:O}=pt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Ve,error:Le}=await U.from("community_private_groups").select("*").order("sort_order");if(Le)throw Le;return Ve}}),{data:B=[]}=pt({queryKey:["admin-group-members",N==null?void 0:N.id],queryFn:async()=>{if(!N)return[];const{data:Ve,error:Le}=await U.from("community_private_group_members").select("*").eq("group_id",N.id);if(Le)throw Le;return Ve},enabled:!!N}),{data:K=[]}=pt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Le=[],$e=0,ve=!0;for(;ve;){const{data:Qe,error:we}=await U.from("profiles").select("id, name, email, brokerage_id").order("name").range($e,$e+1e3-1);if(we)throw we;Qe&&Qe.length>0?(Le=[...Le,...Qe],$e+=1e3,ve=Qe.length===1e3):ve=!1}return Le}}),{data:Z=[]}=pt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Ve,error:Le}=await U.from("brokerages").select("*").order("name");if(Le)throw Le;return Ve}}),Q=Mt({mutationFn:async Ve=>{if(Ve.id){const{error:Le}=await U.from("community_categories").update({name:Ve.name,description:Ve.description||null,icon:Ve.icon||null}).eq("id",Ve.id);if(Le)throw Le}else{const Le=Math.max(...D.map(ve=>ve.sort_order),0),{error:$e}=await U.from("community_categories").insert({name:Ve.name,description:Ve.description||null,icon:Ve.icon||null,sort_order:Le+1});if($e)throw $e}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Ve=>{s({title:"Error",description:Ve.message,variant:"destructive"})}}),W=Mt({mutationFn:async Ve=>{const{error:Le}=await U.from("community_categories").delete().eq("id",Ve);if(Le)throw Le},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),te=Mt({mutationFn:async({id:Ve,direction:Le})=>{const $e=D.findIndex(ve=>ve.id===Ve);if(Le==="up"&&$e>0){const ve=D[$e-1],Qe=D[$e];await U.from("community_categories").update({sort_order:Qe.sort_order}).eq("id",ve.id),await U.from("community_categories").update({sort_order:ve.sort_order}).eq("id",Qe.id)}else if(Le==="down"&&$et.invalidateQueries({queryKey:["admin-community-categories"]})}),ne=Mt({mutationFn:async Ve=>{if(Ve.id){const{error:Le}=await U.from("community_private_groups").update({name:Ve.name,description:Ve.description||null,icon:Ve.icon||null}).eq("id",Ve.id);if(Le)throw Le}else{const Le=Math.max(...F.map(ve=>ve.sort_order),0),{error:$e}=await U.from("community_private_groups").insert({name:Ve.name,description:Ve.description||null,icon:Ve.icon||null,sort_order:Le+1});if($e)throw $e}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),m(!1),x(null),_({name:"",description:"",icon:""}),s({title:f?"Private group updated!":"Private group created!"})},onError:Ve=>{s({title:"Error",description:Ve.message,variant:"destructive"})}}),ae=Mt({mutationFn:async Ve=>{const{error:Le}=await U.from("community_private_groups").delete().eq("id",Ve);if(Le)throw Le},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ue=Mt({mutationFn:async({id:Ve,direction:Le})=>{const $e=F.findIndex(ve=>ve.id===Ve);if(Le==="up"&&$e>0){const ve=F[$e-1],Qe=F[$e];await U.from("community_private_groups").update({sort_order:Qe.sort_order}).eq("id",ve.id),await U.from("community_private_groups").update({sort_order:ve.sort_order}).eq("id",Qe.id)}else if(Le==="down"&&$et.invalidateQueries({queryKey:["admin-private-groups"]})}),me=Mt({mutationFn:async({groupId:Ve,userId:Le,isMember:$e})=>{if($e){const{error:ve}=await U.from("community_private_group_members").delete().eq("group_id",Ve).eq("user_id",Le);if(ve)throw ve}else{const{error:ve}=await U.from("community_private_group_members").insert({group_id:Ve,user_id:Le});if(ve)throw ve}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",N==null?void 0:N.id]})}}),de=Mt({mutationFn:async({groupId:Ve,brokerageId:Le,isMember:$e})=>{if($e){const{error:ve}=await U.from("community_private_group_members").delete().eq("group_id",Ve).eq("brokerage_id",Le);if(ve)throw ve}else{const{error:ve}=await U.from("community_private_group_members").insert({group_id:Ve,brokerage_id:Le});if(ve)throw ve}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",N==null?void 0:N.id]})}}),fe=Ve=>{o(Ve),d({name:Ve.name,description:Ve.description||"",icon:Ve.icon||""}),i(!0)},je=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},xe=Ve=>{x(Ve),_({name:Ve.name,description:Ve.description||"",icon:Ve.icon||""}),m(!0)},Ee=()=>{x(null),_({name:"",description:"",icon:""}),m(!0)},Me=Ve=>{C(Ve),E(""),j(!0)},Oe=Ve=>B.some(Le=>Le.user_id===Ve),Ie=Ve=>B.some(Le=>Le.brokerage_id===Ve),ze=K.filter(Ve=>Ve.name.toLowerCase().includes(A.toLowerCase())||Ve.email.toLowerCase().includes(A.toLowerCase()));return e.jsx(ws,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(ta,{value:r,onValueChange:n,children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"categories",children:"Public Categories"}),e.jsxs(rs,{value:"private-groups",children:[e.jsx(Gc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(fs,{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(q,{onClick:je,children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-[50px]",children:"Order"}),e.jsx(At,{className:"w-[80px]",children:"Icon"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(ha,{children:R?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):D.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):D.map((Ve,Le)=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===0,onClick:()=>te.mutate({id:Ve.id,direction:"up"}),children:"↑"}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===D.length-1,onClick:()=>te.mutate({id:Ve.id,direction:"down"}),children:"↓"})]})}),e.jsx(xt,{className:"text-2xl",children:Ve.icon||"📁"}),e.jsx(xt,{className:"font-medium",children:Ve.name}),e.jsx(xt,{className:"text-muted-foreground",children:Ve.description||"—"}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>fe(Ve),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&W.mutate(Ve.id)},children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},Ve.id))})]})})})]}),e.jsxs(fs,{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(Ga,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(q,{onClick:Ee,children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-[50px]",children:"Order"}),e.jsx(At,{className:"w-[80px]",children:"Icon"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{className:"w-[120px]",children:"Members"}),e.jsx(At,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(ha,{children:O?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):F.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):F.map((Ve,Le)=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===0,onClick:()=>ue.mutate({id:Ve.id,direction:"up"}),children:"↑"}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===F.length-1,onClick:()=>ue.mutate({id:Ve.id,direction:"down"}),children:"↓"})]})}),e.jsx(xt,{className:"text-2xl",children:Ve.icon||"🔒"}),e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ve.name,Ve.brokerage_id?e.jsxs(Xe,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Ga,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[e.jsx(Gc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(xt,{className:"text-muted-foreground",children:Ve.description||"—"}),e.jsx(xt,{children:e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>Me(Ve),children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Ve.brokerage_id&&e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>xe(Ve),children:e.jsx(Ua,{className:"h-4 w-4"})}),!Ve.brokerage_id&&e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&ae.mutate(Ve.id)},children:e.jsx(zr,{className:"h-4 w-4"})}),Ve.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Ve.id))})]})})})]})]}),e.jsx(vs,{open:a,onOpenChange:i,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(Ne,{value:c.icon,onChange:Ve=>d(Le=>({...Le,icon:Ve.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(Ne,{value:c.name,onChange:Ve=>d(Le=>({...Le,name:Ve.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(pr,{value:c.description,onChange:Ve=>d(Le=>({...Le,description:Ve.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(q,{onClick:()=>Q.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(vs,{open:u,onOpenChange:m,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:f?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(Ne,{value:y.icon,onChange:Ve=>_(Le=>({...Le,icon:Ve.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(Ne,{value:y.name,onChange:Ve=>_(Le=>({...Le,name:Ve.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(pr,{value:y.description,onChange:Ve=>_(Le=>({...Le,description:Ve.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsx(q,{onClick:()=>ne.mutate({...y,id:f==null?void 0:f.id}),disabled:!y.name.trim(),children:f?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(vs,{open:b,onOpenChange:j,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsxs(bs,{children:["Manage Members: ",N==null?void 0:N.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ta,{defaultValue:"brokerages",children:[e.jsxs(ea,{className:"w-full",children:[e.jsx(rs,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(rs,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(fs,{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(ui,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Z.map(Ve=>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(Ri,{checked:Ie(Ve.id),onCheckedChange:()=>{N&&de.mutate({groupId:N.id,brokerageId:Ve.id,isMember:Ie(Ve.id)})}}),e.jsx("span",{className:"font-medium",children:Ve.name})]}),e.jsxs(Xe,{variant:"secondary",children:[K.filter(Le=>Le.brokerage_id===Ve.id).length," agents"]})]},Ve.id)),Z.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(fs,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search users...",value:A,onChange:Ve=>E(Ve.target.value),className:"pl-9"})]}),e.jsx(ui,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[ze.map(Ve=>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(Ri,{checked:Oe(Ve.id),onCheckedChange:()=>{N&&me.mutate({groupId:N.id,userId:Ve.id,isMember:Oe(Ve.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ve.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ve.email})]})]})},Ve.id)),ze.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(q,{onClick:()=>j(!1),children:"Done"})})]})]})})]})})},AUe=s=>{switch(s){case"academy_video":return e.jsx(Al,{className:"h-3 w-3"});case"template":return e.jsx(En,{className:"h-3 w-3"});case"toolbox":return e.jsx(yc,{className:"h-3 w-3"});case"newsletter":return e.jsx(E1,{className:"h-3 w-3"});case"social_swag":return e.jsx(Ir,{className:"h-3 w-3"});default:return e.jsx(un,{className:"h-3 w-3"})}},Xgs=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}},Qgs=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}},Jgs=()=>{const{toast:s}=Ba(),[t,r]=k.useState([]),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,u]=k.useState(""),[m,f]=k.useState(null),[x,y]=k.useState([]),[_,b]=k.useState([]);k.useEffect(()=>{j()},[]);const j=async()=>{try{c(!0);const{data:B,error:K}=await U.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(K)throw K;const{data:Z,error:Q}=await U.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(Q)throw Q;const W=[...new Set((Z==null?void 0:Z.map(fe=>fe.user_id))||[])],{data:te}=await U.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",W),ne=new Map((te==null?void 0:te.map(fe=>[fe.id,fe]))||[]),ae=(B==null?void 0:B.map(fe=>{var je,xe,Ee,Me;return{id:fe.id,user_id:fe.user_id,app_name:fe.app_name,launched_at:fe.launched_at,user_name:((je=fe.profiles)==null?void 0:je.name)||"Unknown",user_email:((xe=fe.profiles)==null?void 0:xe.email)||"Unknown",brokerage_name:((Me=(Ee=fe.profiles)==null?void 0:Ee.brokerages)==null?void 0:Me.name)||null}}))||[],ue=(Z==null?void 0:Z.map(fe=>{var xe;const je=ne.get(fe.user_id);return{id:fe.id,user_id:fe.user_id,resource_type:fe.resource_type,resource_id:fe.resource_id,resource_title:fe.resource_title,action_type:fe.action_type,created_at:fe.created_at,user_name:(je==null?void 0:je.name)||"Unknown",user_email:(je==null?void 0:je.email)||"Unknown",brokerage_name:((xe=je==null?void 0:je.brokerages)==null?void 0:xe.name)||null}}))||[];r(ae),a(ue);const me=new Map;ae.forEach(fe=>{if(!me.has(fe.user_id))me.set(fe.user_id,{user_id:fe.user_id,user_name:fe.user_name,user_email:fe.user_email,brokerage_name:fe.brokerage_name,last_activity_type:"app",last_activity_name:fe.app_name,last_activity_at:fe.launched_at,total_app_launches:1,total_content_views:0});else{const je=me.get(fe.user_id);je.total_app_launches++,new Date(fe.launched_at)>new Date(je.last_activity_at)&&(je.last_activity_type="app",je.last_activity_name=fe.app_name,je.last_activity_at=fe.launched_at)}}),ue.forEach(fe=>{if(!me.has(fe.user_id))me.set(fe.user_id,{user_id:fe.user_id,user_name:fe.user_name,user_email:fe.user_email,brokerage_name:fe.brokerage_name,last_activity_type:fe.resource_type,last_activity_name:fe.resource_title,last_activity_at:fe.created_at,total_app_launches:0,total_content_views:1});else{const je=me.get(fe.user_id);je.total_content_views++,new Date(fe.created_at)>new Date(je.last_activity_at)&&(je.last_activity_type=fe.resource_type,je.last_activity_name=fe.resource_title,je.last_activity_at=fe.created_at)}});const de=Array.from(me.values()).sort((fe,je)=>new Date(je.last_activity_at).getTime()-new Date(fe.last_activity_at).getTime());l(de)}catch(B){console.error("Error loading activity:",B),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},N=B=>{f({id:B.user_id,name:B.user_name,email:B.user_email});const K=t.filter(Q=>Q.user_id===B.user_id),Z=n.filter(Q=>Q.user_id===B.user_id);y(K),b(Z)},C=()=>{f(null),y([]),b([])},{sortKey:A,sortDirection:E,handleSort:D,sortData:R}=zB("last_activity_at","desc"),F=i.filter(B=>{var Z;if(!d)return!0;const K=d.toLowerCase();return B.user_name.toLowerCase().includes(K)||B.user_email.toLowerCase().includes(K)||((Z=B.brokerage_name)==null?void 0:Z.toLowerCase().includes(K))}),O=R(F,{user:B=>{var K;return((K=B.user_name)==null?void 0:K.toLowerCase())||""},brokerage:B=>{var K;return((K=B.brokerage_name)==null?void 0:K.toLowerCase())||""},last_activity_at:B=>new Date(B.last_activity_at).getTime(),apps:B=>B.total_app_launches,content:B=>B.total_content_views});return o?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"User Activity"}),e.jsx(Ur,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:B=>u(B.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(mc,{sortKey:"user",currentSortKey:A,currentDirection:E,onSort:D,children:"User"}),e.jsx(mc,{sortKey:"brokerage",currentSortKey:A,currentDirection:E,onSort:D,children:"Brokerage"}),e.jsx(At,{children:"Last Activity"}),e.jsx(mc,{sortKey:"last_activity_at",currentSortKey:A,currentDirection:E,onSort:D,children:"Last Active"}),e.jsx(mc,{sortKey:"apps",currentSortKey:A,currentDirection:E,onSort:D,className:"text-right",children:"Apps"}),e.jsx(mc,{sortKey:"content",currentSortKey:A,currentDirection:E,onSort:D,className:"text-right",children:"Content"})]})}),e.jsx(ha,{children:O.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):O.map(B=>e.jsxs(Ws,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>N(B),children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:B.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:B.user_email})]})}),e.jsx(xt,{children:B.brokerage_name?e.jsx(Xe,{variant:"outline",children:B.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(xt,{children:e.jsx("div",{className:"flex items-center gap-2",children:B.last_activity_type==="app"?e.jsxs(Xe,{variant:"secondary",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),B.last_activity_name]}):e.jsxs(Xe,{variant:"outline",className:"flex items-center gap-1",children:[AUe(B.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:B.last_activity_name})]})})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:Nl(new Date(B.last_activity_at),{addSuffix:!0})}),e.jsx(xt,{className:"text-right",children:e.jsx(Xe,{variant:"outline",children:B.total_app_launches})}),e.jsx(xt,{className:"text-right",children:e.jsx(Xe,{variant:"outline",children:B.total_content_views})})]},B.user_id))})]})})]})]}),e.jsx(vs,{open:!!m,onOpenChange:B=>!B&&C(),children:e.jsxs(ys,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(_s,{children:[e.jsxs(bs,{children:[m==null?void 0:m.name,"'s Activity"]}),e.jsx(an,{children:m==null?void 0:m.email})]}),e.jsxs(ta,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ea,{className:"grid w-full grid-cols-2",children:[e.jsxs(rs,{value:"content",children:["Content (",_.length,")"]}),e.jsxs(rs,{value:"apps",children:["App Launches (",x.length,")"]})]}),e.jsx(fs,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Resource"}),e.jsx(At,{children:"Action"}),e.jsx(At,{children:"Time"})]})}),e.jsx(ha,{children:_.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):_.map(B=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs(Xe,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[AUe(B.resource_type),Xgs(B.resource_type)]})}),e.jsx(xt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:B.resource_title})}),e.jsx(xt,{children:e.jsx(Xe,{variant:"secondary",children:Qgs(B.action_type)})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:Nl(new Date(B.created_at),{addSuffix:!0})})]},B.id))})]})})}),e.jsx(fs,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"App"}),e.jsx(At,{children:"Time"})]})}),e.jsx(ha,{children:x.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):x.map(B=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsx(Xe,{variant:"secondary",children:B.app_name})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:Nl(new Date(B.launched_at),{addSuffix:!0})})]},B.id))})]})})})]})]})})]})},e0s=()=>{const{toast:s}=Ba(),[t,r]=k.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[n,a]=k.useState(!0);k.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await U.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await U.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await U.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await U.from("activity_logs").select("*",{count:"exact",head:!0}),m=new Date;m.setDate(m.getDate()-7);const{count:f}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",m.toISOString()),x=new Date;x.setMonth(x.getMonth()-1);const{count:y}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",x.toISOString()),{data:_}=await U.from("activity_logs").select("user_id").gte("launched_at",m.toISOString()),b=new Set(_==null?void 0:_.map(j=>j.user_id)).size;r({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:f||0,launchesThisMonth:y||0,uniqueActiveThisWeek:b})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return n?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.activeUsers," active, ",t.pendingUsers," pending"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Ti,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.activeUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.totalUsers>0?`${Math.round(t.activeUsers/t.totalUsers*100)}% of total`:"0% of total"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(jn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.pendingUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalBrokerages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total brokerages"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(xm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(xm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(xm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(Wo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},MUe={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},IUe={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 Hft({brokerageOnly:s=!1,brokerageId:t}){const[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(""),[c,d]=k.useState("all");k.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let D=[];if(s&&t){const{data:W}=await U.from("profiles").select("id").eq("brokerage_id",t);if(D=(W==null?void 0:W.map(te=>te.id))||[],D.length===0){n([]),i(!1);return}}let R=U.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&D.length>0&&(R=R.or(`sender_id.in.(${D.join(",")}),recipient_id.in.(${D.join(",")})`));const{data:F,error:O}=await R;if(O)throw O;const B=new Set;F==null||F.forEach(W=>{B.add(W.sender_id),B.add(W.recipient_id)});const{data:K}=await U.from("profiles").select("id, name, email").in("id",Array.from(B)),Z=new Map((K==null?void 0:K.map(W=>[W.id,W]))||[]),Q=(F==null?void 0:F.map(W=>({...W,sender:Z.get(W.sender_id),recipient:Z.get(W.recipient_id)})))||[];n(Q)}catch(D){console.error("Error loading shares:",D)}finally{i(!1)}},{sortKey:m,sortDirection:f,handleSort:x,sortData:y}=zB("created_at","desc"),_=r.filter(D=>{var O,B;const R=l===""||D.resource_title.toLowerCase().includes(l.toLowerCase())||((O=D.sender)==null?void 0:O.name.toLowerCase().includes(l.toLowerCase()))||((B=D.recipient)==null?void 0:B.name.toLowerCase().includes(l.toLowerCase())),F=c==="all"||D.resource_type===c;return R&&F}),b=y(_,{resource:D=>{var R;return((R=D.resource_title)==null?void 0:R.toLowerCase())||""},type:D=>D.resource_type,sender:D=>{var R,F;return((F=(R=D.sender)==null?void 0:R.name)==null?void 0:F.toLowerCase())||""},recipient:D=>{var R,F;return((F=(R=D.recipient)==null?void 0:R.name)==null?void 0:F.toLowerCase())||""},status:D=>D.is_read?1:0,created_at:D=>new Date(D.created_at).getTime()}),j=r.length,N=new Set(r.map(D=>D.sender_id)).size,C=new Set(r.map(D=>D.recipient_id)).size,A=r.length>0?Math.round(r.filter(D=>D.is_read).length/r.length*100):0,E=r.reduce((D,R)=>(D[R.resource_type]=(D[R.resource_type]||0)+1,D),{});return a?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((D,R)=>e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(dr,{className:"h-4 w-20"})}),e.jsx(Pe,{children:e.jsx(dr,{className:"h-8 w-16"})})]},R))}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-6",children:e.jsx(dr,{className:"h-[300px]"})})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(Ec,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:j})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:N})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(Wo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:C})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(En,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[A,"%"]})})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(E).map(([D,R])=>e.jsxs(Xe,{variant:"secondary",className:IUe[D],children:[MUe[D],": ",R]},D)),Object.keys(E).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Share History"}),e.jsxs(Ur,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:D=>o(D.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:c,onValueChange:d,children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{placeholder:"Resource type"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),e.jsx(lt,{value:"event",children:"Events"}),e.jsx(lt,{value:"template",children:"Templates"}),e.jsx(lt,{value:"academy_video",children:"Academy Videos"}),e.jsx(lt,{value:"resource_kit",children:"Resource Kits"}),e.jsx(lt,{value:"newsletter",children:"Newsletters"}),e.jsx(lt,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(ui,{className:"h-[400px]",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(mc,{sortKey:"resource",currentSortKey:m,currentDirection:f,onSort:x,children:"Resource"}),e.jsx(mc,{sortKey:"type",currentSortKey:m,currentDirection:f,onSort:x,children:"Type"}),e.jsx(mc,{sortKey:"sender",currentSortKey:m,currentDirection:f,onSort:x,children:"Sender"}),e.jsx(mc,{sortKey:"recipient",currentSortKey:m,currentDirection:f,onSort:x,children:"Recipient"}),e.jsx(mc,{sortKey:"status",currentSortKey:m,currentDirection:f,onSort:x,children:"Status"}),e.jsx(mc,{sortKey:"created_at",currentSortKey:m,currentDirection:f,onSort:x,children:"Date"})]})}),e.jsx(ha,{children:b.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):b.map(D=>{var R,F;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium max-w-[200px] truncate",children:D.resource_title}),e.jsx(xt,{children:e.jsx(Xe,{variant:"secondary",className:IUe[D.resource_type],children:MUe[D.resource_type]})}),e.jsx(xt,{children:((R=D.sender)==null?void 0:R.name)||"Unknown"}),e.jsx(xt,{children:((F=D.recipient)==null?void 0:F.name)||"Unknown"}),e.jsx(xt,{children:e.jsx(Xe,{variant:D.is_read?"default":"outline",children:D.is_read?"Read":"Unread"})}),e.jsx(xt,{className:"text-muted-foreground",children:As(new Date(D.created_at),"MMM d, yyyy")})]},D.id)})})]})})]})]})]})}const wwe={academy_video:{label:"Academy Videos",icon:bn,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:Nn},template:{label:"Templates",icon:Fj,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:dm},toolbox:{label:"Toolkit",icon:A_,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:li},newsletter:{label:"Newsletters",icon:Ks,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:dm},social_swag:{label:"Social Swag",icon:dl,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:dm},event:{label:"Events",icon:vn,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:dm}};function PUe(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function t0s(s,t){return s==="toolbox"?t.downloads:t.clicks}function s0s(){var D;const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(null),l=k.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=zB("total_views","desc");k.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:R,error:F}=await U.rpc("get_admin_content_engagement");if(F)throw F;t(R||[])}catch(R){console.error("Error loading content engagement:",R)}finally{n(!1)}},f=R=>{i(F=>{const O=F===R?null:R;return requestAnimationFrame(()=>{var B;(B=l.current)==null||B.scrollIntoView({behavior:"smooth",block:"start"})}),O})};if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-4",children:[...Array(4)].map((R,F)=>e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(dr,{className:"h-4 w-20"})}),e.jsx(Pe,{children:e.jsx(dr,{className:"h-8 w-16"})})]},F))}),e.jsx(ke,{children:e.jsx(Pe,{className:"py-8",children:e.jsx(dr,{className:"h-64 w-full"})})})]});const x=s.reduce((R,F)=>R+F.total_views,0),y=s.reduce((R,F)=>R+F.total_clicks,0),_=s.reduce((R,F)=>R+F.total_downloads,0),b=s.length,j=s.reduce((R,F)=>(R[F.resource_type]||(R[F.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),R[F.resource_type].views+=F.total_views,R[F.resource_type].clicks+=F.total_clicks,R[F.resource_type].downloads+=F.total_downloads,R[F.resource_type].assets+=1,R[F.resource_type].uniqueUsers+=F.unique_users,R),{}),N=a?s.filter(R=>R.resource_type===a):s,C=u(N,{asset:R=>{var F;return((F=R.resource_title)==null?void 0:F.toLowerCase())||""},type:R=>R.resource_type,views:R=>R.total_views,actions:R=>PUe(R),unique_users:R=>R.unique_users,last_activity:R=>R.last_engaged_at?new Date(R.last_engaged_at).getTime():0}),A=a?wwe[a]||{label:a,icon:Nn,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:dm}: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(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(dm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(Wo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(dm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[x>0?Math.round((y+_)/x*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Ur,{children:"Click a category to see individual asset performance"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(j).map(([R,F])=>{const O=wwe[R]||{label:R,icon:Nn,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:dm},B=O.icon,K=a===R;return e.jsxs("button",{type:"button",onClick:()=>f(R),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${K?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${O.color}`,children:e.jsx(B,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:O.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(Nn,{className:"h-3 w-3"})," ",F.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(O.actionIcon,{className:"h-3 w-3"})," ",t0s(R,F)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Dr,{className:"h-3 w-3"})," ",F.uniqueUsers]})]})]}),e.jsxs(Xe,{variant:"secondary",className:"text-[10px]",children:[F.assets," items"]})]},R)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{className:"text-sm font-medium flex items-center gap-2",children:A&&E?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-4 w-4"}),A.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Ur,{children:a?`${N.length} ${((D=A==null?void 0:A.label)==null?void 0:D.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(Aa,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Pe,{children:N.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(ui,{className:"h-[400px]",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-[40px]",children:"#"}),e.jsx(mc,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(mc,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(mc,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(mc,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:A?A.actionLabel:"Actions"}),e.jsx(mc,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(mc,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(ha,{children:C.map((R,F)=>{const O=wwe[R.resource_type]||{label:R.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:dm};return e.jsxs(Ws,{children:[e.jsx(xt,{className:"text-muted-foreground text-xs",children:F+1}),e.jsx(xt,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:R.resource_title})}),!a&&e.jsx(xt,{children:e.jsx(Xe,{className:`text-[10px] ${O.color}`,children:O.label})}),e.jsx(xt,{className:"text-right font-medium",children:R.total_views}),e.jsx(xt,{className:"text-right font-medium",children:PUe(R)}),e.jsx(xt,{className:"text-right",children:R.unique_users}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:R.last_engaged_at?Nl(new Date(R.last_engaged_at),{addSuffix:!0}):"—"})]},`${R.resource_type}-${R.resource_id}`)})})]})})})]})})]})}var r0s=Array.isArray,Mg=r0s,n0s=typeof lh=="object"&&lh&&lh.Object===Object&&lh,Gft=n0s,a0s=Gft,i0s=typeof self=="object"&&self&&self.Object===Object&&self,o0s=a0s||i0s||Function("return this")(),lw=o0s,l0s=lw,c0s=l0s.Symbol,HB=c0s,LUe=HB,Wft=Object.prototype,d0s=Wft.hasOwnProperty,u0s=Wft.toString,sO=LUe?LUe.toStringTag:void 0;function h0s(s){var t=d0s.call(s,sO),r=s[sO];try{s[sO]=void 0;var n=!0}catch{}var a=u0s.call(s);return n&&(t?s[sO]=r:delete s[sO]),a}var m0s=h0s,f0s=Object.prototype,p0s=f0s.toString;function x0s(s){return p0s.call(s)}var g0s=x0s,DUe=HB,y0s=m0s,v0s=g0s,b0s="[object Null]",_0s="[object Undefined]",RUe=DUe?DUe.toStringTag:void 0;function w0s(s){return s==null?s===void 0?_0s:b0s:RUe&&RUe in Object(s)?y0s(s):v0s(s)}var $2=w0s;function j0s(s){return s!=null&&typeof s=="object"}var U2=j0s,N0s=$2,k0s=U2,S0s="[object Symbol]";function C0s(s){return typeof s=="symbol"||k0s(s)&&N0s(s)==S0s}var $8=C0s,T0s=Mg,E0s=$8,A0s=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,M0s=/^\w*$/;function I0s(s,t){if(T0s(s))return!1;var r=typeof s;return r=="number"||r=="symbol"||r=="boolean"||s==null||E0s(s)?!0:M0s.test(s)||!A0s.test(s)||t!=null&&s in Object(t)}var QAe=I0s;function P0s(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var f4=P0s;const U8=gl(f4);var L0s=$2,D0s=f4,R0s="[object AsyncFunction]",O0s="[object Function]",F0s="[object GeneratorFunction]",z0s="[object Proxy]";function B0s(s){if(!D0s(s))return!1;var t=L0s(s);return t==O0s||t==F0s||t==R0s||t==z0s}var JAe=B0s;const oo=gl(JAe);var $0s=lw,U0s=$0s["__core-js_shared__"],q0s=U0s,jwe=q0s,OUe=function(){var s=/[^.]+$/.exec(jwe&&jwe.keys&&jwe.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function V0s(s){return!!OUe&&OUe in s}var H0s=V0s,G0s=Function.prototype,W0s=G0s.toString;function K0s(s){if(s!=null){try{return W0s.call(s)}catch{}try{return s+""}catch{}}return""}var Kft=K0s,Y0s=JAe,Z0s=H0s,X0s=f4,Q0s=Kft,J0s=/[\\^$.*+?()[\]{}|]/g,eys=/^\[object .+?Constructor\]$/,tys=Function.prototype,sys=Object.prototype,rys=tys.toString,nys=sys.hasOwnProperty,ays=RegExp("^"+rys.call(nys).replace(J0s,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function iys(s){if(!X0s(s)||Z0s(s))return!1;var t=Y0s(s)?ays:eys;return t.test(Q0s(s))}var oys=iys;function lys(s,t){return s==null?void 0:s[t]}var cys=lys,dys=oys,uys=cys;function hys(s,t){var r=uys(s,t);return dys(r)?r:void 0}var iM=hys,mys=iM,fys=mys(Object,"create"),j0e=fys,FUe=j0e;function pys(){this.__data__=FUe?FUe(null):{},this.size=0}var xys=pys;function gys(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var yys=gys,vys=j0e,bys="__lodash_hash_undefined__",_ys=Object.prototype,wys=_ys.hasOwnProperty;function jys(s){var t=this.__data__;if(vys){var r=t[s];return r===bys?void 0:r}return wys.call(t,s)?t[s]:void 0}var Nys=jys,kys=j0e,Sys=Object.prototype,Cys=Sys.hasOwnProperty;function Tys(s){var t=this.__data__;return kys?t[s]!==void 0:Cys.call(t,s)}var Eys=Tys,Ays=j0e,Mys="__lodash_hash_undefined__";function Iys(s,t){var r=this.__data__;return this.size+=this.has(s)?0:1,r[s]=Ays&&t===void 0?Mys:t,this}var Pys=Iys,Lys=xys,Dys=yys,Rys=Nys,Oys=Eys,Fys=Pys;function q8(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t-1}var tvs=evs,svs=N0e;function rvs(s,t){var r=this.__data__,n=svs(r,s);return n<0?(++this.size,r.push([s,t])):r[n][1]=t,this}var nvs=rvs,avs=$ys,ivs=Yys,ovs=Qys,lvs=tvs,cvs=nvs;function V8(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t0?1:-1},nE=function(t){return IA(t)&&t.indexOf("%")===t.length-1},Jn=function(t){return M1s(t)&&!GB(t)},D1s=function(t){return yo(t)},fm=function(t){return Jn(t)||IA(t)},R1s=0,G8=function(t){var r=++R1s;return"".concat(t||"").concat(r)},kx=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!Jn(t)&&!IA(t))return n;var i;if(nE(t)){var l=t.indexOf("%");i=r*parseFloat(t.slice(0,l))/100}else i=+t;return GB(i)&&(i=n),a&&i>r&&(i=r),i},wk=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},O1s=function(t){if(!Array.isArray(t))return!1;for(var r=t.length,n={},a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function V1s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function FSe(s){"@babel/helpers - typeof";return FSe=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},FSe(s)}var HUe={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":""},GUe=null,kwe=null,cMe=function s(t){if(t===GUe&&Array.isArray(kwe))return kwe;var r=[];return k.Children.forEach(t,function(n){yo(n)||(S1s.isFragment(n)?r=r.concat(s(n.props.children)):r.push(n))}),kwe=r,GUe=t,r};function L0(s,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(a){return x2(a)}):n=[x2(t)],cMe(s).forEach(function(a){var i=P0(a,"type.displayName")||P0(a,"type.name");n.indexOf(i)!==-1&&r.push(a)}),r}function h0(s,t){var r=L0(s,t);return r&&r[0]}var WUe=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,a=r.height;return!(!Jn(n)||n<=0||!Jn(a)||a<=0)},H1s=["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"],G1s=function(t){return t&&t.type&&IA(t.type)&&H1s.indexOf(t.type)>=0},W1s=function(t){return t&&FSe(t)==="object"&&"clipDot"in t},K1s=function(t,r,n,a){var i,l=(i=Nwe==null?void 0:Nwe[a])!==null&&i!==void 0?i:[];return r.startsWith("data-")||!oo(t)&&(a&&l.includes(r)||B1s.includes(r))||n&&lMe.includes(r)},Li=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(k.isValidElement(t)&&(a=t.props),!U8(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;K1s((o=a)===null||o===void 0?void 0:o[l],l,r,n)&&(i[l]=a[l])}),i},zSe=function s(t,r){if(t===r)return!0;var n=k.Children.count(t);if(n!==k.Children.count(r))return!1;if(n===0)return!0;if(n===1)return KUe(Array.isArray(t)?t[0]:t,Array.isArray(r)?r[0]:r);for(var a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function J1s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function $Se(s){var t=s.children,r=s.width,n=s.height,a=s.viewBox,i=s.className,l=s.style,o=s.title,c=s.desc,d=Q1s(s,X1s),u=a||{width:r,height:n,x:0,y:0},m=_o("recharts-surface",i);return Ct.createElement("svg",BSe({},Li(d,!0,"svg"),{className:m,width:r,height:n,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 ebs=["children","className"];function USe(){return USe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function sbs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var Bl=Ct.forwardRef(function(s,t){var r=s.children,n=s.className,a=tbs(s,ebs),i=_o("recharts-layer",n);return Ct.createElement("g",USe({className:i},Li(a,!0),{ref:t}),r)}),P1=function(t,r){for(var n=arguments.length,a=new Array(n>2?n-2:0),i=2;ia?0:a+t),r=r>a?a:r,r<0&&(r+=a),a=t>r?0:r-t>>>0,t>>>=0;for(var i=Array(a);++n=n?s:abs(s,t,r)}var obs=ibs,lbs="\\ud800-\\udfff",cbs="\\u0300-\\u036f",dbs="\\ufe20-\\ufe2f",ubs="\\u20d0-\\u20ff",hbs=cbs+dbs+ubs,mbs="\\ufe0e\\ufe0f",fbs="\\u200d",pbs=RegExp("["+fbs+lbs+hbs+mbs+"]");function xbs(s){return pbs.test(s)}var npt=xbs;function gbs(s){return s.split("")}var ybs=gbs,apt="\\ud800-\\udfff",vbs="\\u0300-\\u036f",bbs="\\ufe20-\\ufe2f",_bs="\\u20d0-\\u20ff",wbs=vbs+bbs+_bs,jbs="\\ufe0e\\ufe0f",Nbs="["+apt+"]",qSe="["+wbs+"]",VSe="\\ud83c[\\udffb-\\udfff]",kbs="(?:"+qSe+"|"+VSe+")",ipt="[^"+apt+"]",opt="(?:\\ud83c[\\udde6-\\uddff]){2}",lpt="[\\ud800-\\udbff][\\udc00-\\udfff]",Sbs="\\u200d",cpt=kbs+"?",dpt="["+jbs+"]?",Cbs="(?:"+Sbs+"(?:"+[ipt,opt,lpt].join("|")+")"+dpt+cpt+")*",Tbs=dpt+cpt+Cbs,Ebs="(?:"+[ipt+qSe+"?",qSe,opt,lpt,Nbs].join("|")+")",Abs=RegExp(VSe+"(?="+VSe+")|"+Ebs+Tbs,"g");function Mbs(s){return s.match(Abs)||[]}var Ibs=Mbs,Pbs=ybs,Lbs=npt,Dbs=Ibs;function Rbs(s){return Lbs(s)?Dbs(s):Pbs(s)}var Obs=Rbs,Fbs=obs,zbs=npt,Bbs=Obs,$bs=Qft;function Ubs(s){return function(t){t=$bs(t);var r=zbs(t)?Bbs(t):void 0,n=r?r[0]:t.charAt(0),a=r?Fbs(r,1).join(""):t.slice(1);return n[s]()+a}}var qbs=Ubs,Vbs=qbs,Hbs=Vbs("toUpperCase"),Gbs=Hbs;const F0e=gl(Gbs);function rd(s){return function(){return s}}const upt=Math.cos,Dfe=Math.sin,W1=Math.sqrt,Rfe=Math.PI,z0e=2*Rfe,HSe=Math.PI,GSe=2*HSe,RT=1e-6,Wbs=GSe-RT;function hpt(s){this._+=s[0];for(let t=1,r=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return hpt;const r=10**t;return function(n){this._+=n[0];for(let a=1,i=n.length;aRT)if(!(Math.abs(m*c-d*u)>RT)||!i)this._append`L${this._x1=t},${this._y1=r}`;else{let x=n-l,y=a-o,_=c*c+d*d,b=x*x+y*y,j=Math.sqrt(_),N=Math.sqrt(f),C=i*Math.tan((HSe-Math.acos((_+f-b)/(2*j*N)))/2),A=C/N,E=C/j;Math.abs(A-1)>RT&&this._append`L${t+A*u},${r+A*m}`,this._append`A${i},${i},0,0,${+(m*x>u*y)},${this._x1=t+E*c},${this._y1=r+E*d}`}}arc(t,r,n,a,i,l){if(t=+t,r=+r,n=+n,l=!!l,n<0)throw new Error(`negative radius: ${n}`);let o=n*Math.cos(a),c=n*Math.sin(a),d=t+o,u=r+c,m=1^l,f=l?a-i:i-a;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>RT||Math.abs(this._y1-u)>RT)&&this._append`L${d},${u}`,n&&(f<0&&(f=f%GSe+GSe),f>Wbs?this._append`A${n},${n},0,1,${m},${t-o},${r-c}A${n},${n},0,1,${m},${this._x1=d},${this._y1=u}`:f>RT&&this._append`A${n},${n},0,${+(f>=HSe)},${m},${this._x1=t+n*Math.cos(i)},${this._y1=r+n*Math.sin(i)}`)}rect(t,r,n,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+a}h${-n}Z`}toString(){return this._}}function dMe(s){let t=3;return s.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return s},()=>new Ybs(t)}function uMe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function mpt(s){this._context=s}mpt.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 B0e(s){return new mpt(s)}function fpt(s){return s[0]}function ppt(s){return s[1]}function xpt(s,t){var r=rd(!0),n=null,a=B0e,i=null,l=dMe(o);s=typeof s=="function"?s:s===void 0?fpt:rd(s),t=typeof t=="function"?t:t===void 0?ppt:rd(t);function o(c){var d,u=(c=uMe(c)).length,m,f=!1,x;for(n==null&&(i=a(x=l())),d=0;d<=u;++d)!(d=x;--y)o.point(C[y],A[y]);o.lineEnd(),o.areaEnd()}j&&(C[f]=+s(b,f,m),A[f]=+t(b,f,m),o.point(n?+n(b,f,m):C[f],r?+r(b,f,m):A[f]))}if(N)return o=null,N+""||null}function u(){return xpt().defined(a).curve(l).context(i)}return d.x=function(m){return arguments.length?(s=typeof m=="function"?m:rd(+m),n=null,d):s},d.x0=function(m){return arguments.length?(s=typeof m=="function"?m:rd(+m),d):s},d.x1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:rd(+m),d):n},d.y=function(m){return arguments.length?(t=typeof m=="function"?m:rd(+m),r=null,d):t},d.y0=function(m){return arguments.length?(t=typeof m=="function"?m:rd(+m),d):t},d.y1=function(m){return arguments.length?(r=m==null?null:typeof m=="function"?m:rd(+m),d):r},d.lineX0=d.lineY0=function(){return u().x(s).y(t)},d.lineY1=function(){return u().x(s).y(r)},d.lineX1=function(){return u().x(n).y(t)},d.defined=function(m){return arguments.length?(a=typeof m=="function"?m:rd(!!m),d):a},d.curve=function(m){return arguments.length?(l=m,i!=null&&(o=l(i)),d):l},d.context=function(m){return arguments.length?(m==null?i=o=null:o=l(i=m),d):i},d}class gpt{constructor(t,r){this._context=t,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function Zbs(s){return new gpt(s,!0)}function Xbs(s){return new gpt(s,!1)}const hMe={draw(s,t){const r=W1(t/Rfe);s.moveTo(r,0),s.arc(0,0,r,0,z0e)}},Qbs={draw(s,t){const r=W1(t/5)/2;s.moveTo(-3*r,-r),s.lineTo(-r,-r),s.lineTo(-r,-3*r),s.lineTo(r,-3*r),s.lineTo(r,-r),s.lineTo(3*r,-r),s.lineTo(3*r,r),s.lineTo(r,r),s.lineTo(r,3*r),s.lineTo(-r,3*r),s.lineTo(-r,r),s.lineTo(-3*r,r),s.closePath()}},ypt=W1(1/3),Jbs=ypt*2,e_s={draw(s,t){const r=W1(t/Jbs),n=r*ypt;s.moveTo(0,-r),s.lineTo(n,0),s.lineTo(0,r),s.lineTo(-n,0),s.closePath()}},t_s={draw(s,t){const r=W1(t),n=-r/2;s.rect(n,n,r,r)}},s_s=.8908130915292852,vpt=Dfe(Rfe/10)/Dfe(7*Rfe/10),r_s=Dfe(z0e/10)*vpt,n_s=-upt(z0e/10)*vpt,a_s={draw(s,t){const r=W1(t*s_s),n=r_s*r,a=n_s*r;s.moveTo(0,-r),s.lineTo(n,a);for(let i=1;i<5;++i){const l=z0e*i/5,o=upt(l),c=Dfe(l);s.lineTo(c*r,-o*r),s.lineTo(o*n-c*a,c*n+o*a)}s.closePath()}},Swe=W1(3),i_s={draw(s,t){const r=-W1(t/(Swe*3));s.moveTo(0,r*2),s.lineTo(-Swe*r,-r),s.lineTo(Swe*r,-r),s.closePath()}},wy=-.5,jy=W1(3)/2,WSe=1/W1(12),o_s=(WSe/2+1)*3,l_s={draw(s,t){const r=W1(t/o_s),n=r/2,a=r*WSe,i=n,l=r*WSe+r,o=-i,c=l;s.moveTo(n,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(wy*n-jy*a,jy*n+wy*a),s.lineTo(wy*i-jy*l,jy*i+wy*l),s.lineTo(wy*o-jy*c,jy*o+wy*c),s.lineTo(wy*n+jy*a,wy*a-jy*n),s.lineTo(wy*i+jy*l,wy*l-jy*i),s.lineTo(wy*o+jy*c,wy*c-jy*o),s.closePath()}};function c_s(s,t){let r=null,n=dMe(a);s=typeof s=="function"?s:rd(s||hMe),t=typeof t=="function"?t:rd(t===void 0?64:+t);function a(){let i;if(r||(r=i=n()),s.apply(this,arguments).draw(r,+t.apply(this,arguments)),i)return r=null,i+""||null}return a.type=function(i){return arguments.length?(s=typeof i=="function"?i:rd(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:rd(+i),a):t},a.context=function(i){return arguments.length?(r=i??null,a):r},a}function Ofe(){}function Ffe(s,t,r){s._context.bezierCurveTo((2*s._x0+s._x1)/3,(2*s._y0+s._y1)/3,(s._x0+2*s._x1)/3,(s._y0+2*s._y1)/3,(s._x0+4*s._x1+t)/6,(s._y0+4*s._y1+r)/6)}function bpt(s){this._context=s}bpt.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:Ffe(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:Ffe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function d_s(s){return new bpt(s)}function _pt(s){this._context=s}_pt.prototype={areaStart:Ofe,areaEnd:Ofe,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:Ffe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function u_s(s){return new _pt(s)}function wpt(s){this._context=s}wpt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+s)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:Ffe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function h_s(s){return new wpt(s)}function jpt(s){this._context=s}jpt.prototype={areaStart:Ofe,areaEnd:Ofe,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 m_s(s){return new jpt(s)}function ZUe(s){return s<0?-1:1}function XUe(s,t,r){var n=s._x1-s._x0,a=t-s._x1,i=(s._y1-s._y0)/(n||a<0&&-0),l=(r-s._y1)/(a||n<0&&-0),o=(i*a+l*n)/(n+a);return(ZUe(i)+ZUe(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function QUe(s,t){var r=s._x1-s._x0;return r?(3*(s._y1-s._y0)/r-t)/2:t}function Cwe(s,t,r){var n=s._x0,a=s._y0,i=s._x1,l=s._y1,o=(i-n)/3;s._context.bezierCurveTo(n+o,a+o*t,i-o,l-o*r,i,l)}function zfe(s){this._context=s}zfe.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:Cwe(this,this._t0,QUe(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){var r=NaN;if(s=+s,t=+t,!(s===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;break;case 2:this._point=3,Cwe(this,QUe(this,r=XUe(this,s,t)),r);break;default:Cwe(this,this._t0,r=XUe(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=r}}};function Npt(s){this._context=new kpt(s)}(Npt.prototype=Object.create(zfe.prototype)).point=function(s,t){zfe.prototype.point.call(this,t,s)};function kpt(s){this._context=s}kpt.prototype={moveTo:function(s,t){this._context.moveTo(t,s)},closePath:function(){this._context.closePath()},lineTo:function(s,t){this._context.lineTo(t,s)},bezierCurveTo:function(s,t,r,n,a,i){this._context.bezierCurveTo(t,s,n,r,i,a)}};function f_s(s){return new zfe(s)}function p_s(s){return new Npt(s)}function Spt(s){this._context=s}Spt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var s=this._x,t=this._y,r=s.length;if(r)if(this._line?this._context.lineTo(s[0],t[0]):this._context.moveTo(s[0],t[0]),r===2)this._context.lineTo(s[1],t[1]);else for(var n=JUe(s),a=JUe(t),i=0,l=1;l=0;--t)a[t]=(l[t]-a[t+1])/i[t];for(i[r-1]=(s[r]+a[r-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(s,t);else{var r=this._x*(1-this._t)+s*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=s,this._y=t}};function g_s(s){return new $0e(s,.5)}function y_s(s){return new $0e(s,0)}function v_s(s){return new $0e(s,1)}function kL(s,t){if((l=s.length)>1)for(var r=1,n,a,i=s[t[0]],l,o=i.length;r=0;)r[t]=t;return r}function b_s(s,t){return s[t]}function __s(s){const t=[];return t.key=s,t}function w_s(){var s=rd([]),t=KSe,r=kL,n=b_s;function a(i){var l=Array.from(s.apply(this,arguments),__s),o,c=l.length,d=-1,u;for(const m of i)for(o=0,++d;o0){for(var r,n,a=0,i=s[0].length,l;a0){for(var r=0,n=s[t[0]],a,i=n.length;r0)||!((i=(a=s[t[0]]).length)>0))){for(var r=0,n=1,a,i,l;n=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function M_s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var Cpt={symbolCircle:hMe,symbolCross:Qbs,symbolDiamond:e_s,symbolSquare:t_s,symbolStar:a_s,symbolTriangle:i_s,symbolWye:l_s},I_s=Math.PI/180,P_s=function(t){var r="symbol".concat(F0e(t));return Cpt[r]||hMe},L_s=function(t,r,n){if(r==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var a=18*I_s;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}},D_s=function(t,r){Cpt["symbol".concat(F0e(t))]=r},mMe=function(t){var r=t.type,n=r===void 0?"circle":r,a=t.size,i=a===void 0?64:a,l=t.sizeType,o=l===void 0?"area":l,c=A_s(t,S_s),d=tqe(tqe({},c),{},{type:n,size:i,sizeType:o}),u=function(){var b=P_s(n),j=c_s().type(b).size(L_s(i,o,n));return j()},m=d.className,f=d.cx,x=d.cy,y=Li(d,!0);return f===+f&&x===+x&&i===+i?Ct.createElement("path",YSe({},y,{className:_o("recharts-symbols",m),transform:"translate(".concat(f,", ").concat(x,")"),d:u()})):null};mMe.registerSymbol=D_s;function SL(s){"@babel/helpers - typeof";return SL=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},SL(s)}function ZSe(){return ZSe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var N=x.inactive?d:x.color;return Ct.createElement("li",ZSe({className:b,style:m,key:"legend-item-".concat(y)},PA(n.props,x,y)),Ct.createElement($Se,{width:l,height:l,viewBox:u,style:f},n.renderIcon(x)),Ct.createElement("span",{className:"recharts-legend-item-text",style:{color:N}},_?_(j,x,y):j))})}},{key:"render",value:function(){var n=this.props,a=n.payload,i=n.layout,l=n.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return Ct.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(k.PureComponent);ez(fMe,"displayName","Legend");ez(fMe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var H_s=k0e;function G_s(){this.__data__=new H_s,this.size=0}var W_s=G_s;function K_s(s){var t=this.__data__,r=t.delete(s);return this.size=t.size,r}var Y_s=K_s;function Z_s(s){return this.__data__.get(s)}var X_s=Z_s;function Q_s(s){return this.__data__.has(s)}var J_s=Q_s,ews=k0e,tws=tMe,sws=sMe,rws=200;function nws(s,t){var r=this.__data__;if(r instanceof ews){var n=r.__data__;if(!tws||n.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var m=-1,f=!0,x=r&Sws?new wws:void 0;for(i.set(s,t),i.set(t,s);++m-1&&s%1==0&&s-1&&s%1==0&&s<=Ajs}var yMe=Mjs,Ijs=$2,Pjs=yMe,Ljs=U2,Djs="[object Arguments]",Rjs="[object Array]",Ojs="[object Boolean]",Fjs="[object Date]",zjs="[object Error]",Bjs="[object Function]",$js="[object Map]",Ujs="[object Number]",qjs="[object Object]",Vjs="[object RegExp]",Hjs="[object Set]",Gjs="[object String]",Wjs="[object WeakMap]",Kjs="[object ArrayBuffer]",Yjs="[object DataView]",Zjs="[object Float32Array]",Xjs="[object Float64Array]",Qjs="[object Int8Array]",Jjs="[object Int16Array]",e2s="[object Int32Array]",t2s="[object Uint8Array]",s2s="[object Uint8ClampedArray]",r2s="[object Uint16Array]",n2s="[object Uint32Array]",_d={};_d[Zjs]=_d[Xjs]=_d[Qjs]=_d[Jjs]=_d[e2s]=_d[t2s]=_d[s2s]=_d[r2s]=_d[n2s]=!0;_d[Djs]=_d[Rjs]=_d[Kjs]=_d[Ojs]=_d[Yjs]=_d[Fjs]=_d[zjs]=_d[Bjs]=_d[$js]=_d[Ujs]=_d[qjs]=_d[Vjs]=_d[Hjs]=_d[Gjs]=_d[Wjs]=!1;function a2s(s){return Ljs(s)&&Pjs(s.length)&&!!_d[Ijs(s)]}var i2s=a2s;function o2s(s){return function(t){return s(t)}}var Fpt=o2s,qfe={exports:{}};qfe.exports;(function(s,t){var r=Gft,n=t&&!t.nodeType&&t,a=n&&!0&&s&&!s.nodeType&&s,i=a&&a.exports===n,l=i&&r.process,o=function(){try{var c=a&&a.require&&a.require("util").types;return c||l&&l.binding&&l.binding("util")}catch{}}();s.exports=o})(qfe,qfe.exports);var l2s=qfe.exports,c2s=i2s,d2s=Fpt,lqe=l2s,cqe=lqe&&lqe.isTypedArray,u2s=cqe?d2s(cqe):c2s,zpt=u2s,h2s=pjs,m2s=xMe,f2s=Mg,p2s=Opt,x2s=gMe,g2s=zpt,y2s=Object.prototype,v2s=y2s.hasOwnProperty;function b2s(s,t){var r=f2s(s),n=!r&&m2s(s),a=!r&&!n&&p2s(s),i=!r&&!n&&!a&&g2s(s),l=r||n||a||i,o=l?h2s(s.length,String):[],c=o.length;for(var d in s)(t||v2s.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||x2s(d,c)))&&o.push(d);return o}var _2s=b2s,w2s=Object.prototype;function j2s(s){var t=s&&s.constructor,r=typeof t=="function"&&t.prototype||w2s;return s===r}var N2s=j2s;function k2s(s,t){return function(r){return s(t(r))}}var Bpt=k2s,S2s=Bpt,C2s=S2s(Object.keys,Object),T2s=C2s,E2s=N2s,A2s=T2s,M2s=Object.prototype,I2s=M2s.hasOwnProperty;function P2s(s){if(!E2s(s))return A2s(s);var t=[];for(var r in Object(s))I2s.call(s,r)&&r!="constructor"&&t.push(r);return t}var L2s=P2s,D2s=JAe,R2s=yMe;function O2s(s){return s!=null&&R2s(s.length)&&!D2s(s)}var WB=O2s,F2s=_2s,z2s=L2s,B2s=WB;function $2s(s){return B2s(s)?F2s(s):z2s(s)}var U0e=$2s,U2s=rjs,q2s=mjs,V2s=U0e;function H2s(s){return U2s(s,V2s,q2s)}var G2s=H2s,dqe=G2s,W2s=1,K2s=Object.prototype,Y2s=K2s.hasOwnProperty;function Z2s(s,t,r,n,a,i){var l=r&W2s,o=dqe(s),c=o.length,d=dqe(t),u=d.length;if(c!=u&&!l)return!1;for(var m=c;m--;){var f=o[m];if(!(l?f in t:Y2s.call(t,f)))return!1}var x=i.get(s),y=i.get(t);if(x&&y)return x==t&&y==s;var _=!0;i.set(s,t),i.set(t,s);for(var b=l;++m-1}var Kks=Wks;function Yks(s,t,r){for(var n=-1,a=s==null?0:s.length;++n=dSs){var d=t?null:lSs(s);if(d)return cSs(d);l=!1,a=oSs,c=new nSs}else c=t?[]:o;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function SSs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function CSs(s){return s.value}function TSs(s,t){if(Ct.isValidElement(s))return Ct.cloneElement(s,t);if(typeof s=="function")return Ct.createElement(s,t);t.ref;var r=kSs(t,gSs);return Ct.createElement(fMe,r)}var Sqe=1,EP=function(s){function t(){var r;ySs(this,t);for(var n=arguments.length,a=new Array(n),i=0;iSqe||Math.abs(a.height-this.lastBoundingBox.height)>Sqe)&&(this.lastBoundingBox.width=a.width,this.lastBoundingBox.height=a.height,n&&n(a)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?yj({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,m,f;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(l==="center"&&i==="vertical"){var x=this.getBBoxSnapshot();m={left:((d||0)-x.width)/2}}else m=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(o==="middle"){var y=this.getBBoxSnapshot();f={top:((u||0)-y.height)/2}}else f=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return yj(yj({},m),f)}},{key:"render",value:function(){var n=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,u=a.payload,m=yj(yj({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Ct.createElement("div",{className:"recharts-legend-wrapper",style:m,ref:function(x){n.wrapperNode=x}},TSs(i,yj(yj({},this.props),{},{payload:Wpt(u,d,CSs)})))}}],[{key:"getWithHeight",value:function(n,a){var i=yj(yj({},this.defaultProps),n.props),l=i.layout;return l==="vertical"&&Jn(n.props.height)?{height:n.props.height}:l==="horizontal"?{width:n.props.width||a}:null}}])}(k.PureComponent);q0e(EP,"displayName","Legend");q0e(EP,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Cqe=HB,ESs=xMe,ASs=Mg,Tqe=Cqe?Cqe.isConcatSpreadable:void 0;function MSs(s){return ASs(s)||ESs(s)||!!(Tqe&&s&&s[Tqe])}var ISs=MSs,PSs=Dpt,LSs=ISs;function Zpt(s,t,r,n,a){var i=-1,l=s.length;for(r||(r=LSs),a||(a=[]);++i0&&r(o)?t>1?Zpt(o,t-1,r,n,a):PSs(a,o):n||(a[a.length]=o)}return a}var Xpt=Zpt;function DSs(s){return function(t,r,n){for(var a=-1,i=Object(t),l=n(t),o=l.length;o--;){var c=l[s?o:++a];if(r(i[c],c,i)===!1)break}return t}}var RSs=DSs,OSs=RSs,FSs=OSs(),zSs=FSs,BSs=zSs,$Ss=U0e;function USs(s,t){return s&&BSs(s,t,$Ss)}var Qpt=USs,qSs=WB;function VSs(s,t){return function(r,n){if(r==null)return r;if(!qSs(r))return s(r,n);for(var a=r.length,i=t?a:-1,l=Object(r);(t?i--:++it||i&&l&&c&&!o&&!d||n&&l&&c||!r&&c||!a)return 1;if(!n&&!i&&!d&&s=o)return c;var d=r[n];return c*(d=="desc"?-1:1)}}return s.index-t.index}var n4s=r4s,Mwe=nMe,a4s=aMe,i4s=cw,o4s=Jpt,l4s=JSs,c4s=Fpt,d4s=n4s,u4s=Y8,h4s=Mg;function m4s(s,t,r){t.length?t=Mwe(t,function(i){return h4s(i)?function(l){return a4s(l,i.length===1?i[0]:i)}:i}):t=[u4s];var n=-1;t=Mwe(t,c4s(i4s));var a=o4s(s,function(i,l,o){var c=Mwe(t,function(d){return d(i)});return{criteria:c,index:++n,value:i}});return l4s(a,function(i,l){return d4s(i,l,r)})}var f4s=m4s;function p4s(s,t,r){switch(r.length){case 0:return s.call(t);case 1:return s.call(t,r[0]);case 2:return s.call(t,r[0],r[1]);case 3:return s.call(t,r[0],r[1],r[2])}return s.apply(t,r)}var x4s=p4s,g4s=x4s,Aqe=Math.max;function y4s(s,t,r){return t=Aqe(t===void 0?s.length-1:t,0),function(){for(var n=arguments,a=-1,i=Aqe(n.length-t,0),l=Array(i);++a0){if(++t>=T4s)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var I4s=M4s,P4s=C4s,L4s=I4s,D4s=L4s(P4s),R4s=D4s,O4s=Y8,F4s=v4s,z4s=R4s;function B4s(s,t){return z4s(F4s(s,t,O4s),s+"")}var $4s=B4s,U4s=eMe,q4s=WB,V4s=gMe,H4s=f4;function G4s(s,t,r){if(!H4s(r))return!1;var n=typeof t;return(n=="number"?q4s(r)&&V4s(t,r.length):n=="string"&&t in r)?U4s(r[t],s):!1}var V0e=G4s,W4s=Xpt,K4s=f4s,Y4s=$4s,Iqe=V0e,Z4s=Y4s(function(s,t){if(s==null)return[];var r=t.length;return r>1&&Iqe(s,t[0],t[1])?t=[]:r>2&&Iqe(t[0],t[1],t[2])&&(t=[t[0]]),K4s(s,W4s(t,1),[])}),X4s=Z4s;const _Me=gl(X4s);function tz(s){"@babel/helpers - typeof";return tz=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tz(s)}function n4e(){return n4e=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=t.x),"".concat(rO,"-left"),Jn(r)&&t&&Jn(t.x)&&r=t.y),"".concat(rO,"-top"),Jn(n)&&t&&Jn(t.y)&&n_?Math.max(u,c[n]):Math.max(m,c[n])}function hCs(s){var t=s.translateX,r=s.translateY,n=s.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function mCs(s){var t=s.allowEscapeViewBox,r=s.coordinate,n=s.offsetTopLeft,a=s.position,i=s.reverseDirection,l=s.tooltipBox,o=s.useTranslate3d,c=s.viewBox,d,u,m;return l.height>0&&l.width>0&&r?(u=Dqe({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),m=Dqe({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=hCs({translateX:u,translateY:m,useTranslate3d:o})):d=dCs,{cssProperties:d,cssClasses:uCs({translateX:u,translateY:m,coordinate:r})}}function TL(s){"@babel/helpers - typeof";return TL=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},TL(s)}function Rqe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function Oqe(s){for(var t=1;tFqe||Math.abs(n.height-this.state.lastBoundingBox.height)>Fqe)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,m=a.hasPayload,f=a.isAnimationActive,x=a.offset,y=a.position,_=a.reverseDirection,b=a.useTranslate3d,j=a.viewBox,N=a.wrapperStyle,C=mCs({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:x,position:y,reverseDirection:_,tooltipBox:this.state.lastBoundingBox,useTranslate3d:b,viewBox:j}),A=C.cssClasses,E=C.cssProperties,D=Oqe(Oqe({transition:f&&i?"transform ".concat(o,"ms ").concat(c):void 0},E),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&m?"visible":"hidden",position:"absolute",top:0,left:0},N);return Ct.createElement("div",{tabIndex:-1,className:A,style:D,ref:function(F){n.wrapperNode=F}},d)}}])}(k.PureComponent),jCs=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},P_={isSsr:jCs(),get:function(t){return P_[t]},set:function(t,r){if(typeof t=="string")P_[t]=r;else{var n=Object.keys(t);n&&n.length&&n.forEach(function(a){P_[a]=t[a]})}}};function EL(s){"@babel/helpers - typeof";return EL=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},EL(s)}function zqe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function Bqe(s){for(var t=1;t0;return Ct.createElement(wCs,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:f,active:i,coordinate:u,hasPayload:D,offset:x,position:b,reverseDirection:j,useTranslate3d:N,viewBox:C,wrapperStyle:A},PCs(d,Bqe(Bqe({},this.props),{},{payload:E})))}}])}(k.PureComponent);wMe(rg,"displayName","Tooltip");wMe(rg,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!P_.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 LCs=lw,DCs=function(){return LCs.Date.now()},RCs=DCs,OCs=/\s/;function FCs(s){for(var t=s.length;t--&&OCs.test(s.charAt(t)););return t}var zCs=FCs,BCs=zCs,$Cs=/^\s+/;function UCs(s){return s&&s.slice(0,BCs(s)+1).replace($Cs,"")}var qCs=UCs,VCs=qCs,$qe=f4,HCs=$8,Uqe=NaN,GCs=/^[-+]0x[0-9a-f]+$/i,WCs=/^0b[01]+$/i,KCs=/^0o[0-7]+$/i,YCs=parseInt;function ZCs(s){if(typeof s=="number")return s;if(HCs(s))return Uqe;if($qe(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=$qe(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=VCs(s);var r=WCs.test(s);return r||KCs.test(s)?YCs(s.slice(2),r?2:8):GCs.test(s)?Uqe:+s}var axt=ZCs,XCs=f4,Pwe=RCs,qqe=axt,QCs="Expected a function",JCs=Math.max,e3s=Math.min;function t3s(s,t,r){var n,a,i,l,o,c,d=0,u=!1,m=!1,f=!0;if(typeof s!="function")throw new TypeError(QCs);t=qqe(t)||0,XCs(r)&&(u=!!r.leading,m="maxWait"in r,i=m?JCs(qqe(r.maxWait)||0,t):i,f="trailing"in r?!!r.trailing:f);function x(D){var R=n,F=a;return n=a=void 0,d=D,l=s.apply(F,R),l}function y(D){return d=D,o=setTimeout(j,t),u?x(D):l}function _(D){var R=D-c,F=D-d,O=t-R;return m?e3s(O,i-F):O}function b(D){var R=D-c,F=D-d;return c===void 0||R>=t||R<0||m&&F>=i}function j(){var D=Pwe();if(b(D))return N(D);o=setTimeout(j,_(D))}function N(D){return o=void 0,f&&n?x(D):(n=a=void 0,l)}function C(){o!==void 0&&clearTimeout(o),d=0,n=c=a=o=void 0}function A(){return o===void 0?l:N(Pwe())}function E(){var D=Pwe(),R=b(D);if(n=arguments,a=this,c=D,R){if(o===void 0)return y(c);if(m)return clearTimeout(o),o=setTimeout(j,t),x(c)}return o===void 0&&(o=setTimeout(j,t)),l}return E.cancel=C,E.flush=A,E}var s3s=t3s,r3s=s3s,n3s=f4,a3s="Expected a function";function i3s(s,t,r){var n=!0,a=!0;if(typeof s!="function")throw new TypeError(a3s);return n3s(r)&&(n="leading"in r?!!r.leading:n,a="trailing"in r?!!r.trailing:a),r3s(s,t,{leading:n,maxWait:t,trailing:a})}var o3s=i3s;const ixt=gl(o3s);function rz(s){"@babel/helpers - typeof";return rz=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rz(s)}function Vqe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function aV(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&(Q=ixt(Q,_,{trailing:!0,leading:!1}));var W=new ResizeObserver(Q),te=E.current.getBoundingClientRect(),ne=te.width,ae=te.height;return K(ne,ae),W.observe(E.current),function(){W.disconnect()}},[K,_]);var Z=k.useMemo(function(){var Q=O.containerWidth,W=O.containerHeight;if(Q<0||W<0)return null;P1(nE(l)||nE(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),P1(!r||r>0,"The aspect(%s) must be greater than zero.",r);var te=nE(l)?Q:l,ne=nE(c)?W:c;r&&r>0&&(te?ne=te/r:ne&&(te=ne*r),f&&ne>f&&(ne=f)),P1(te>0||ne>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,te,ne,l,c,u,m,r);var ae=!Array.isArray(x)&&x2(x.type).endsWith("Chart");return Ct.Children.map(x,function(ue){return Ct.isValidElement(ue)?k.cloneElement(ue,aV({width:te,height:ne},ae?{style:aV({height:"100%",width:"100%",maxHeight:ne,maxWidth:te},ue.props.style)}:{})):ue})},[r,x,c,f,m,u,O,l]);return Ct.createElement("div",{id:b?"".concat(b):void 0,className:_o("recharts-responsive-container",j),style:aV(aV({},A),{},{width:l,height:c,minWidth:u,minHeight:m,maxHeight:f}),ref:E},Z)}),KB=function(t){return null};KB.displayName="Cell";function nz(s){"@babel/helpers - typeof";return nz=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},nz(s)}function Gqe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function l4e(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||P_.isSsr)return{width:0,height:0};var n=_3s(r),a=JSON.stringify({text:t,copyStyle:n});if(R6.widthCache[a])return R6.widthCache[a];try{var i=document.getElementById(Wqe);i||(i=document.createElement("span"),i.setAttribute("id",Wqe),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=l4e(l4e({},b3s),n);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return R6.widthCache[a]=c,++R6.cacheCount>v3s&&(R6.cacheCount=0,R6.widthCache={}),c}catch{return{width:0,height:0}}},w3s=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function az(s){"@babel/helpers - typeof";return az=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},az(s)}function Wfe(s,t){return S3s(s)||k3s(s,t)||N3s(s,t)||j3s()}function j3s(){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 N3s(s,t){if(s){if(typeof s=="string")return Kqe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Kqe(s,t)}}function Kqe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function B3s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function eVe(s,t){return V3s(s)||q3s(s,t)||U3s(s,t)||$3s()}function $3s(){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 U3s(s,t){if(s){if(typeof s=="string")return tVe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return tVe(s,t)}}function tVe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&arguments[0]!==void 0?arguments[0]:[];return te.reduce(function(ne,ae){var ue=ae.word,me=ae.width,de=ne[ne.length-1];if(de&&(a==null||i||de.width+me+nae.width?ne:ae})};if(!u)return x;for(var _="…",b=function(te){var ne=m.slice(0,te),ae=dxt({breakAll:d,style:c,children:ne+_}).wordsWithComputedWidth,ue=f(ae),me=ue.length>l||y(ue).width>Number(a);return[me,ue]},j=0,N=m.length-1,C=0,A;j<=N&&C<=m.length-1;){var E=Math.floor((j+N)/2),D=E-1,R=b(D),F=eVe(R,2),O=F[0],B=F[1],K=b(E),Z=eVe(K,1),Q=Z[0];if(!O&&!Q&&(j=E+1),O&&Q&&(N=E-1),!O&&Q){A=B;break}C++}return A||x},sVe=function(t){var r=yo(t)?[]:t.toString().split(cxt);return[{words:r}]},G3s=function(t){var r=t.width,n=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((r||n)&&!P_.isSsr){var c,d,u=dxt({breakAll:l,children:a,style:i});if(u){var m=u.wordsWithComputedWidth,f=u.spaceWidth;c=m,d=f}else return sVe(a);return H3s({breakAll:l,children:a,maxLines:o,style:i},c,d,r,n)}return sVe(a)},rVe="#808080",LA=function(t){var r=t.x,n=r===void 0?0:r,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,m=u===void 0?!1:u,f=t.textAnchor,x=f===void 0?"start":f,y=t.verticalAnchor,_=y===void 0?"end":y,b=t.fill,j=b===void 0?rVe:b,N=Jqe(t,F3s),C=k.useMemo(function(){return G3s({breakAll:N.breakAll,children:N.children,maxLines:N.maxLines,scaleToFit:m,style:N.style,width:N.width})},[N.breakAll,N.children,N.maxLines,m,N.style,N.width]),A=N.dx,E=N.dy,D=N.angle,R=N.className,F=N.breakAll,O=Jqe(N,z3s);if(!fm(n)||!fm(i))return null;var B=n+(Jn(A)?A:0),K=i+(Jn(E)?E:0),Z;switch(_){case"start":Z=Lwe("calc(".concat(d,")"));break;case"middle":Z=Lwe("calc(".concat((C.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:Z=Lwe("calc(".concat(C.length-1," * -").concat(o,")"));break}var Q=[];if(m){var W=C[0].width,te=N.width;Q.push("scale(".concat((Jn(te)?te/W:1)/W,")"))}return D&&Q.push("rotate(".concat(D,", ").concat(B,", ").concat(K,")")),Q.length&&(O.transform=Q.join(" ")),Ct.createElement("text",c4e({},Li(O,!0),{x:B,y:K,className:_o("recharts-text",R),textAnchor:x,fill:j.includes("url")?rVe:j}),C.map(function(ne,ae){var ue=ne.words.join(F?"":" ");return Ct.createElement("tspan",{x:B,dy:ae===0?Z:o,key:"".concat(ue,"-").concat(ae)},ue)}))};function NS(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function W3s(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function jMe(s){let t,r,n;s.length!==2?(t=NS,r=(o,c)=>NS(s(o),c),n=(o,c)=>s(o)-c):(t=s===NS||s===W3s?s:K3s,r=s,n=s);function a(o,c,d=0,u=o.length){if(d>>1;r(o[m],c)<0?d=m+1:u=m}while(d>>1;r(o[m],c)<=0?d=m+1:u=m}while(dd&&n(o[m-1],c)>-n(o[m],c)?m-1:m}return{left:a,center:l,right:i}}function K3s(){return 0}function uxt(s){return s===null?NaN:+s}function*Y3s(s,t){for(let r of s)r!=null&&(r=+r)>=r&&(yield r)}const Z3s=jMe(NS),YB=Z3s.right;jMe(uxt).center;class nVe extends Map{constructor(t,r=J3s){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,a]of t)this.set(n,a)}get(t){return super.get(aVe(this,t))}has(t){return super.has(aVe(this,t))}set(t,r){return super.set(X3s(this,t),r)}delete(t){return super.delete(Q3s(this,t))}}function aVe({_intern:s,_key:t},r){const n=t(r);return s.has(n)?s.get(n):r}function X3s({_intern:s,_key:t},r){const n=t(r);return s.has(n)?s.get(n):(s.set(n,r),r)}function Q3s({_intern:s,_key:t},r){const n=t(r);return s.has(n)&&(r=s.get(n),s.delete(n)),r}function J3s(s){return s!==null&&typeof s=="object"?s.valueOf():s}function e5s(s=NS){if(s===NS)return hxt;if(typeof s!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=s(t,r);return n||n===0?n:(s(r,r)===0)-(s(t,t)===0)}}function hxt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const t5s=Math.sqrt(50),s5s=Math.sqrt(10),r5s=Math.sqrt(2);function Kfe(s,t,r){const n=(t-s)/Math.max(0,r),a=Math.floor(Math.log10(n)),i=n/Math.pow(10,a),l=i>=t5s?10:i>=s5s?5:i>=r5s?2:1;let o,c,d;return a<0?(d=Math.pow(10,-a)/l,o=Math.round(s*d),c=Math.round(t*d),o/dt&&--c,d=-d):(d=Math.pow(10,a)*l,o=Math.round(s/d),c=Math.round(t/d),o*dt&&--c),c0))return[];if(s===t)return[s];const n=t=a))return[];const o=i-a+1,c=new Array(o);if(n)if(l<0)for(let d=0;d=n)&&(r=n);return r}function oVe(s,t){let r;for(const n of s)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function mxt(s,t,r=0,n=1/0,a){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(s.length-1,n)),!(r<=t&&t<=n))return s;for(a=a===void 0?hxt:e5s(a);n>r;){if(n-r>600){const c=n-r+1,d=t-r+1,u=Math.log(c),m=.5*Math.exp(2*u/3),f=.5*Math.sqrt(u*m*(c-m)/c)*(d-c/2<0?-1:1),x=Math.max(r,Math.floor(t-d*m/c+f)),y=Math.min(n,Math.floor(t+(c-d)*m/c+f));mxt(s,t,x,y,a)}const i=s[t];let l=r,o=n;for(nO(s,r,t),a(s[n],i)>0&&nO(s,r,n);l0;)--o}a(s[r],i)===0?nO(s,r,o):(++o,nO(s,o,n)),o<=t&&(r=o+1),t<=o&&(n=o-1)}return s}function nO(s,t,r){const n=s[t];s[t]=s[r],s[r]=n}function n5s(s,t,r){if(s=Float64Array.from(Y3s(s)),!(!(n=s.length)||isNaN(t=+t))){if(t<=0||n<2)return oVe(s);if(t>=1)return iVe(s);var n,a=(n-1)*t,i=Math.floor(a),l=iVe(mxt(s,i).subarray(0,i+1)),o=oVe(s.subarray(i+1));return l+(o-l)*(a-i)}}function a5s(s,t,r=uxt){if(!(!(n=s.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(s[0],0,s);if(t>=1)return+r(s[n-1],n-1,s);var n,a=(n-1)*t,i=Math.floor(a),l=+r(s[i],i,s),o=+r(s[i+1],i+1,s);return l+(o-l)*(a-i)}}function i5s(s,t,r){s=+s,t=+t,r=(a=arguments.length)<2?(t=s,s=0,1):a<3?1:+r;for(var n=-1,a=Math.max(0,Math.ceil((t-s)/r))|0,i=new Array(a);++n>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?oV(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?oV(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=l5s.exec(s))?new dg(t[1],t[2],t[3],1):(t=c5s.exec(s))?new dg(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=d5s.exec(s))?oV(t[1],t[2],t[3],t[4]):(t=u5s.exec(s))?oV(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=h5s.exec(s))?fVe(t[1],t[2]/100,t[3]/100,1):(t=m5s.exec(s))?fVe(t[1],t[2]/100,t[3]/100,t[4]):lVe.hasOwnProperty(s)?uVe(lVe[s]):s==="transparent"?new dg(NaN,NaN,NaN,0):null}function uVe(s){return new dg(s>>16&255,s>>8&255,s&255,1)}function oV(s,t,r,n){return n<=0&&(s=t=r=NaN),new dg(s,t,r,n)}function x5s(s){return s instanceof ZB||(s=cz(s)),s?(s=s.rgb(),new dg(s.r,s.g,s.b,s.opacity)):new dg}function f4e(s,t,r,n){return arguments.length===1?x5s(s):new dg(s,t,r,n??1)}function dg(s,t,r,n){this.r=+s,this.g=+t,this.b=+r,this.opacity=+n}kMe(dg,f4e,pxt(ZB,{brighter(s){return s=s==null?Yfe:Math.pow(Yfe,s),new dg(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?oz:Math.pow(oz,s),new dg(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new dg(sA(this.r),sA(this.g),sA(this.b),Zfe(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:hVe,formatHex:hVe,formatHex8:g5s,formatRgb:mVe,toString:mVe}));function hVe(){return`#${aE(this.r)}${aE(this.g)}${aE(this.b)}`}function g5s(){return`#${aE(this.r)}${aE(this.g)}${aE(this.b)}${aE((isNaN(this.opacity)?1:this.opacity)*255)}`}function mVe(){const s=Zfe(this.opacity);return`${s===1?"rgb(":"rgba("}${sA(this.r)}, ${sA(this.g)}, ${sA(this.b)}${s===1?")":`, ${s})`}`}function Zfe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function sA(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function aE(s){return s=sA(s),(s<16?"0":"")+s.toString(16)}function fVe(s,t,r,n){return n<=0?s=t=r=NaN:r<=0||r>=1?s=t=NaN:t<=0&&(s=NaN),new v1(s,t,r,n)}function xxt(s){if(s instanceof v1)return new v1(s.h,s.s,s.l,s.opacity);if(s instanceof ZB||(s=cz(s)),!s)return new v1;if(s instanceof v1)return s;s=s.rgb();var t=s.r/255,r=s.g/255,n=s.b/255,a=Math.min(t,r,n),i=Math.max(t,r,n),l=NaN,o=i-a,c=(i+a)/2;return o?(t===i?l=(r-n)/o+(r0&&c<1?0:l,new v1(l,o,c,s.opacity)}function y5s(s,t,r,n){return arguments.length===1?xxt(s):new v1(s,t,r,n??1)}function v1(s,t,r,n){this.h=+s,this.s=+t,this.l=+r,this.opacity=+n}kMe(v1,y5s,pxt(ZB,{brighter(s){return s=s==null?Yfe:Math.pow(Yfe,s),new v1(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?oz:Math.pow(oz,s),new v1(this.h,this.s,this.l*s,this.opacity)},rgb(){var s=this.h%360+(this.h<0)*360,t=isNaN(s)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,a=2*r-n;return new dg(Dwe(s>=240?s-240:s+120,a,n),Dwe(s,a,n),Dwe(s<120?s+240:s-120,a,n),this.opacity)},clamp(){return new v1(pVe(this.h),lV(this.s),lV(this.l),Zfe(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=Zfe(this.opacity);return`${s===1?"hsl(":"hsla("}${pVe(this.h)}, ${lV(this.s)*100}%, ${lV(this.l)*100}%${s===1?")":`, ${s})`}`}}));function pVe(s){return s=(s||0)%360,s<0?s+360:s}function lV(s){return Math.max(0,Math.min(1,s||0))}function Dwe(s,t,r){return(s<60?t+(r-t)*s/60:s<180?r:s<240?t+(r-t)*(240-s)/60:t)*255}const SMe=s=>()=>s;function v5s(s,t){return function(r){return s+r*t}}function b5s(s,t,r){return s=Math.pow(s,r),t=Math.pow(t,r)-s,r=1/r,function(n){return Math.pow(s+n*t,r)}}function _5s(s){return(s=+s)==1?gxt:function(t,r){return r-t?b5s(t,r,s):SMe(isNaN(t)?r:t)}}function gxt(s,t){var r=t-s;return r?v5s(s,r):SMe(isNaN(s)?t:s)}const xVe=function s(t){var r=_5s(t);function n(a,i){var l=r((a=f4e(a)).r,(i=f4e(i)).r),o=r(a.g,i.g),c=r(a.b,i.b),d=gxt(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 n.gamma=s,n}(1);function w5s(s,t){t||(t=[]);var r=s?Math.min(t.length,s.length):0,n=t.slice(),a;return function(i){for(a=0;ar&&(i=t.slice(r,i),o[l]?o[l]+=i:o[++l]=i),(n=n[0])===(a=a[0])?o[l]?o[l]+=a:o[++l]=a:(o[++l]=null,c.push({i:l,x:Xfe(n,a)})),r=Rwe.lastIndex;return rt&&(r=s,s=t,t=r),function(n){return Math.max(s,Math.min(t,n))}}function P5s(s,t,r){var n=s[0],a=s[1],i=t[0],l=t[1];return a2?L5s:P5s,c=d=null,m}function m(f){return f==null||isNaN(f=+f)?i:(c||(c=o(s.map(n),t,r)))(n(l(f)))}return m.invert=function(f){return l(a((d||(d=o(t,s.map(n),Xfe)))(f)))},m.domain=function(f){return arguments.length?(s=Array.from(f,Qfe),u()):s.slice()},m.range=function(f){return arguments.length?(t=Array.from(f),u()):t.slice()},m.rangeRound=function(f){return t=Array.from(f),r=CMe,u()},m.clamp=function(f){return arguments.length?(l=f?!0:Sx,u()):l!==Sx},m.interpolate=function(f){return arguments.length?(r=f,u()):r},m.unknown=function(f){return arguments.length?(i=f,m):i},function(f,x){return n=f,a=x,u()}}function TMe(){return H0e()(Sx,Sx)}function D5s(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function Jfe(s,t){if((r=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"))<0)return null;var r,n=s.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+s.slice(r+1)]}function AL(s){return s=Jfe(Math.abs(s)),s?s[1]:NaN}function R5s(s,t){return function(r,n){for(var a=r.length,i=[],l=0,o=s[0],c=0;a>0&&o>0&&(c+o+1>n&&(o=Math.max(1,n-c)),i.push(r.substring(a-=o,a+o)),!((c+=o+1)>n));)o=s[l=(l+1)%s.length];return i.reverse().join(t)}}function O5s(s){return function(t){return t.replace(/[0-9]/g,function(r){return s[+r]})}}var F5s=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function dz(s){if(!(t=F5s.exec(s)))throw new Error("invalid format: "+s);var t;return new EMe({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}dz.prototype=EMe.prototype;function EMe(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+""}EMe.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 z5s(s){e:for(var t=s.length,r=1,n=-1,a;r0&&(n=0);break}return n>0?s.slice(0,n)+s.slice(a+1):s}var yxt;function B5s(s,t){var r=Jfe(s,t);if(!r)return s+"";var n=r[0],a=r[1],i=a-(yxt=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,l=n.length;return i===l?n:i>l?n+new Array(i-l+1).join("0"):i>0?n.slice(0,i)+"."+n.slice(i):"0."+new Array(1-i).join("0")+Jfe(s,Math.max(0,t+i-1))[0]}function yVe(s,t){var r=Jfe(s,t);if(!r)return s+"";var n=r[0],a=r[1];return a<0?"0."+new Array(-a).join("0")+n:n.length>a+1?n.slice(0,a+1)+"."+n.slice(a+1):n+new Array(a-n.length+2).join("0")}const vVe={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:D5s,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)=>yVe(s*100,t),r:yVe,s:B5s,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function bVe(s){return s}var _Ve=Array.prototype.map,wVe=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function $5s(s){var t=s.grouping===void 0||s.thousands===void 0?bVe:R5s(_Ve.call(s.grouping,Number),s.thousands+""),r=s.currency===void 0?"":s.currency[0]+"",n=s.currency===void 0?"":s.currency[1]+"",a=s.decimal===void 0?".":s.decimal+"",i=s.numerals===void 0?bVe:O5s(_Ve.call(s.numerals,String)),l=s.percent===void 0?"%":s.percent+"",o=s.minus===void 0?"−":s.minus+"",c=s.nan===void 0?"NaN":s.nan+"";function d(m){m=dz(m);var f=m.fill,x=m.align,y=m.sign,_=m.symbol,b=m.zero,j=m.width,N=m.comma,C=m.precision,A=m.trim,E=m.type;E==="n"?(N=!0,E="g"):vVe[E]||(C===void 0&&(C=12),A=!0,E="g"),(b||f==="0"&&x==="=")&&(b=!0,f="0",x="=");var D=_==="$"?r:_==="#"&&/[boxX]/.test(E)?"0"+E.toLowerCase():"",R=_==="$"?n:/[%p]/.test(E)?l:"",F=vVe[E],O=/[defgprs%]/.test(E);C=C===void 0?6:/[gprs]/.test(E)?Math.max(1,Math.min(21,C)):Math.max(0,Math.min(20,C));function B(K){var Z=D,Q=R,W,te,ne;if(E==="c")Q=F(K)+Q,K="";else{K=+K;var ae=K<0||1/K<0;if(K=isNaN(K)?c:F(Math.abs(K),C),A&&(K=z5s(K)),ae&&+K==0&&y!=="+"&&(ae=!1),Z=(ae?y==="("?y:o:y==="-"||y==="("?"":y)+Z,Q=(E==="s"?wVe[8+yxt/3]:"")+Q+(ae&&y==="("?")":""),O){for(W=-1,te=K.length;++Wne||ne>57){Q=(ne===46?a+K.slice(W+1):K.slice(W))+Q,K=K.slice(0,W);break}}}N&&!b&&(K=t(K,1/0));var ue=Z.length+K.length+Q.length,me=ue>1)+Z+K+Q+me.slice(ue);break;default:K=me+Z+K+Q;break}return i(K)}return B.toString=function(){return m+""},B}function u(m,f){var x=d((m=dz(m),m.type="f",m)),y=Math.max(-8,Math.min(8,Math.floor(AL(f)/3)))*3,_=Math.pow(10,-y),b=wVe[8+y/3];return function(j){return x(_*j)+b}}return{format:d,formatPrefix:u}}var cV,AMe,vxt;U5s({thousands:",",grouping:[3],currency:["$",""]});function U5s(s){return cV=$5s(s),AMe=cV.format,vxt=cV.formatPrefix,cV}function q5s(s){return Math.max(0,-AL(Math.abs(s)))}function V5s(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(AL(t)/3)))*3-AL(Math.abs(s)))}function H5s(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,AL(t)-AL(s))+1}function bxt(s,t,r,n){var a=h4e(s,t,r),i;switch(n=dz(n??",f"),n.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return n.precision==null&&!isNaN(i=V5s(a,l))&&(n.precision=i),vxt(n,l)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(i=H5s(a,Math.max(Math.abs(s),Math.abs(t))))&&(n.precision=i-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(i=q5s(a))&&(n.precision=i-(n.type==="%")*2);break}}return AMe(n)}function p4(s){var t=s.domain;return s.ticks=function(r){var n=t();return d4e(n[0],n[n.length-1],r??10)},s.tickFormat=function(r,n){var a=t();return bxt(a[0],a[a.length-1],r??10,n)},s.nice=function(r){r==null&&(r=10);var n=t(),a=0,i=n.length-1,l=n[a],o=n[i],c,d,u=10;for(o0;){if(d=u4e(l,o,r),d===c)return n[a]=l,n[i]=o,t(n);if(d>0)l=Math.floor(l/d)*d,o=Math.ceil(o/d)*d;else if(d<0)l=Math.ceil(l*d)/d,o=Math.floor(o*d)/d;else break;c=d}return s},s}function epe(){var s=TMe();return s.copy=function(){return XB(s,epe())},pv.apply(s,arguments),p4(s)}function _xt(s){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(s=Array.from(n,Qfe),r):s.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return _xt(s).unknown(t)},s=arguments.length?Array.from(s,Qfe):[0,1],p4(r)}function wxt(s,t){s=s.slice();var r=0,n=s.length-1,a=s[r],i=s[n],l;return iMath.pow(s,t)}function Z5s(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 kVe(s){return(t,r)=>-s(-t,r)}function MMe(s){const t=s(jVe,NVe),r=t.domain;let n=10,a,i;function l(){return a=Z5s(n),i=Y5s(n),r()[0]<0?(a=kVe(a),i=kVe(i),s(G5s,W5s)):s(jVe,NVe),t}return t.base=function(o){return arguments.length?(n=+o,l()):n},t.domain=function(o){return arguments.length?(r(o),l()):r()},t.ticks=o=>{const c=r();let d=c[0],u=c[c.length-1];const m=u0){for(;f<=x;++f)for(y=1;yu)break;j.push(_)}}else for(;f<=x;++f)for(y=n-1;y>=1;--y)if(_=f>0?y/i(-f):y*i(f),!(_u)break;j.push(_)}j.length*2{if(o==null&&(o=10),c==null&&(c=n===10?"s":","),typeof c!="function"&&(!(n%1)&&(c=dz(c)).precision==null&&(c.trim=!0),c=AMe(c)),o===1/0)return c;const d=Math.max(1,n*o/t.ticks().length);return u=>{let m=u/i(Math.round(a(u)));return m*nr(wxt(r(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function jxt(){const s=MMe(H0e()).domain([1,10]);return s.copy=()=>XB(s,jxt()).base(s.base()),pv.apply(s,arguments),s}function SVe(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function CVe(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function IMe(s){var t=1,r=s(SVe(t),CVe(t));return r.constant=function(n){return arguments.length?s(SVe(t=+n),CVe(t)):t},p4(r)}function Nxt(){var s=IMe(H0e());return s.copy=function(){return XB(s,Nxt()).constant(s.constant())},pv.apply(s,arguments)}function TVe(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function X5s(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function Q5s(s){return s<0?-s*s:s*s}function PMe(s){var t=s(Sx,Sx),r=1;function n(){return r===1?s(Sx,Sx):r===.5?s(X5s,Q5s):s(TVe(r),TVe(1/r))}return t.exponent=function(a){return arguments.length?(r=+a,n()):r},p4(t)}function LMe(){var s=PMe(H0e());return s.copy=function(){return XB(s,LMe()).exponent(s.exponent())},pv.apply(s,arguments),s}function J5s(){return LMe.apply(null,arguments).exponent(.5)}function EVe(s){return Math.sign(s)*s*s}function eTs(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function kxt(){var s=TMe(),t=[0,1],r=!1,n;function a(i){var l=eTs(s(i));return isNaN(l)?n:r?Math.round(l):l}return a.invert=function(i){return s.invert(EVe(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,Qfe)).map(EVe)),a):t.slice()},a.rangeRound=function(i){return a.range(i).round(!0)},a.round=function(i){return arguments.length?(r=!!i,a):r},a.clamp=function(i){return arguments.length?(s.clamp(i),a):s.clamp()},a.unknown=function(i){return arguments.length?(n=i,a):n},a.copy=function(){return kxt(s.domain(),t).round(r).clamp(s.clamp()).unknown(n)},pv.apply(a,arguments),p4(a)}function Sxt(){var s=[],t=[],r=[],n;function a(){var l=0,o=Math.max(1,t.length);for(r=new Array(o-1);++l0?r[o-1]:s[0],o=r?[n[r-1],t]:[n[d-1],n[d]]},l.unknown=function(c){return arguments.length&&(i=c),l},l.thresholds=function(){return n.slice()},l.copy=function(){return Cxt().domain([s,t]).range(a).unknown(i)},pv.apply(p4(l),arguments)}function Txt(){var s=[.5],t=[0,1],r,n=1;function a(i){return i!=null&&i<=i?t[YB(s,i,0,n)]:r}return a.domain=function(i){return arguments.length?(s=Array.from(i),n=Math.min(s.length,t.length-1),a):s.slice()},a.range=function(i){return arguments.length?(t=Array.from(i),n=Math.min(s.length,t.length-1),a):t.slice()},a.invertExtent=function(i){var l=t.indexOf(i);return[s[l-1],s[l]]},a.unknown=function(i){return arguments.length?(r=i,a):r},a.copy=function(){return Txt().domain(s).range(t).unknown(r)},pv.apply(a,arguments)}const Owe=new Date,Fwe=new Date;function Am(s,t,r,n){function a(i){return s(i=arguments.length===0?new Date:new Date(+i)),i}return a.floor=i=>(s(i=new Date(+i)),i),a.ceil=i=>(s(i=new Date(i-1)),t(i,1),s(i),i),a.round=i=>{const l=a(i),o=a.ceil(i);return i-l(t(i=new Date(+i),l==null?1:Math.floor(l)),i),a.range=(i,l,o)=>{const c=[];if(i=a.ceil(i),o=o==null?1:Math.floor(o),!(i0))return c;let d;do c.push(d=new Date(+i)),t(i,o),s(i);while(dAm(l=>{if(l>=l)for(;s(l),!i(l);)l.setTime(l-1)},(l,o)=>{if(l>=l)if(o<0)for(;++o<=0;)for(;t(l,-1),!i(l););else for(;--o>=0;)for(;t(l,1),!i(l););}),r&&(a.count=(i,l)=>(Owe.setTime(+i),Fwe.setTime(+l),s(Owe),s(Fwe),Math.floor(r(Owe,Fwe))),a.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?a.filter(n?l=>n(l)%i===0:l=>a.count(0,l)%i===0):a)),a}const tpe=Am(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);tpe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?Am(t=>{t.setTime(Math.floor(t/s)*s)},(t,r)=>{t.setTime(+t+r*s)},(t,r)=>(r-t)/s):tpe);tpe.range;const Yj=1e3,Wy=Yj*60,Zj=Wy*60,T2=Zj*24,DMe=T2*7,AVe=T2*30,zwe=T2*365,iE=Am(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*Yj)},(s,t)=>(t-s)/Yj,s=>s.getUTCSeconds());iE.range;const RMe=Am(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*Yj)},(s,t)=>{s.setTime(+s+t*Wy)},(s,t)=>(t-s)/Wy,s=>s.getMinutes());RMe.range;const OMe=Am(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*Wy)},(s,t)=>(t-s)/Wy,s=>s.getUTCMinutes());OMe.range;const FMe=Am(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*Yj-s.getMinutes()*Wy)},(s,t)=>{s.setTime(+s+t*Zj)},(s,t)=>(t-s)/Zj,s=>s.getHours());FMe.range;const zMe=Am(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*Zj)},(s,t)=>(t-s)/Zj,s=>s.getUTCHours());zMe.range;const QB=Am(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*Wy)/T2,s=>s.getDate()-1);QB.range;const G0e=Am(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/T2,s=>s.getUTCDate()-1);G0e.range;const Ext=Am(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/T2,s=>Math.floor(s/T2));Ext.range;function oM(s){return Am(t=>{t.setDate(t.getDate()-(t.getDay()+7-s)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*Wy)/DMe)}const W0e=oM(0),spe=oM(1),tTs=oM(2),sTs=oM(3),ML=oM(4),rTs=oM(5),nTs=oM(6);W0e.range;spe.range;tTs.range;sTs.range;ML.range;rTs.range;nTs.range;function lM(s){return Am(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/DMe)}const K0e=lM(0),rpe=lM(1),aTs=lM(2),iTs=lM(3),IL=lM(4),oTs=lM(5),lTs=lM(6);K0e.range;rpe.range;aTs.range;iTs.range;IL.range;oTs.range;lTs.range;const BMe=Am(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());BMe.range;const $Me=Am(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());$Me.range;const E2=Am(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());E2.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Am(t=>{t.setFullYear(Math.floor(t.getFullYear()/s)*s),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*s)});E2.range;const A2=Am(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());A2.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Am(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/s)*s),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*s)});A2.range;function Axt(s,t,r,n,a,i){const l=[[iE,1,Yj],[iE,5,5*Yj],[iE,15,15*Yj],[iE,30,30*Yj],[i,1,Wy],[i,5,5*Wy],[i,15,15*Wy],[i,30,30*Wy],[a,1,Zj],[a,3,3*Zj],[a,6,6*Zj],[a,12,12*Zj],[n,1,T2],[n,2,2*T2],[r,1,DMe],[t,1,AVe],[t,3,3*AVe],[s,1,zwe]];function o(d,u,m){const f=ub).right(l,f);if(x===l.length)return s.every(h4e(d/zwe,u/zwe,m));if(x===0)return tpe.every(Math.max(h4e(d,u,m),1));const[y,_]=l[f/l[x-1][2]53)return null;"w"in ve||(ve.w=1),"Z"in ve?(we=$we(aO(ve.y,0,1)),nt=we.getUTCDay(),we=nt>4||nt===0?rpe.ceil(we):rpe(we),we=G0e.offset(we,(ve.V-1)*7),ve.y=we.getUTCFullYear(),ve.m=we.getUTCMonth(),ve.d=we.getUTCDate()+(ve.w+6)%7):(we=Bwe(aO(ve.y,0,1)),nt=we.getDay(),we=nt>4||nt===0?spe.ceil(we):spe(we),we=QB.offset(we,(ve.V-1)*7),ve.y=we.getFullYear(),ve.m=we.getMonth(),ve.d=we.getDate()+(ve.w+6)%7)}else("W"in ve||"U"in ve)&&("w"in ve||(ve.w="u"in ve?ve.u%7:"W"in ve?1:0),nt="Z"in ve?$we(aO(ve.y,0,1)).getUTCDay():Bwe(aO(ve.y,0,1)).getDay(),ve.m=0,ve.d="W"in ve?(ve.w+6)%7+ve.W*7-(nt+5)%7:ve.w+ve.U*7-(nt+6)%7);return"Z"in ve?(ve.H+=ve.Z/100|0,ve.M+=ve.Z%100,$we(ve)):Bwe(ve)}}function F(Ve,Le,$e,ve){for(var Qe=0,we=Le.length,nt=$e.length,Se,Ge;Qe=nt)return-1;if(Se=Le.charCodeAt(Qe++),Se===37){if(Se=Le.charAt(Qe++),Ge=E[Se in MVe?Le.charAt(Qe++):Se],!Ge||(ve=Ge(Ve,$e,ve))<0)return-1}else if(Se!=$e.charCodeAt(ve++))return-1}return ve}function O(Ve,Le,$e){var ve=d.exec(Le.slice($e));return ve?(Ve.p=u.get(ve[0].toLowerCase()),$e+ve[0].length):-1}function B(Ve,Le,$e){var ve=x.exec(Le.slice($e));return ve?(Ve.w=y.get(ve[0].toLowerCase()),$e+ve[0].length):-1}function K(Ve,Le,$e){var ve=m.exec(Le.slice($e));return ve?(Ve.w=f.get(ve[0].toLowerCase()),$e+ve[0].length):-1}function Z(Ve,Le,$e){var ve=j.exec(Le.slice($e));return ve?(Ve.m=N.get(ve[0].toLowerCase()),$e+ve[0].length):-1}function Q(Ve,Le,$e){var ve=_.exec(Le.slice($e));return ve?(Ve.m=b.get(ve[0].toLowerCase()),$e+ve[0].length):-1}function W(Ve,Le,$e){return F(Ve,t,Le,$e)}function te(Ve,Le,$e){return F(Ve,r,Le,$e)}function ne(Ve,Le,$e){return F(Ve,n,Le,$e)}function ae(Ve){return l[Ve.getDay()]}function ue(Ve){return i[Ve.getDay()]}function me(Ve){return c[Ve.getMonth()]}function de(Ve){return o[Ve.getMonth()]}function fe(Ve){return a[+(Ve.getHours()>=12)]}function je(Ve){return 1+~~(Ve.getMonth()/3)}function xe(Ve){return l[Ve.getUTCDay()]}function Ee(Ve){return i[Ve.getUTCDay()]}function Me(Ve){return c[Ve.getUTCMonth()]}function Oe(Ve){return o[Ve.getUTCMonth()]}function Ie(Ve){return a[+(Ve.getUTCHours()>=12)]}function ze(Ve){return 1+~~(Ve.getUTCMonth()/3)}return{format:function(Ve){var Le=D(Ve+="",C);return Le.toString=function(){return Ve},Le},parse:function(Ve){var Le=R(Ve+="",!1);return Le.toString=function(){return Ve},Le},utcFormat:function(Ve){var Le=D(Ve+="",A);return Le.toString=function(){return Ve},Le},utcParse:function(Ve){var Le=R(Ve+="",!0);return Le.toString=function(){return Ve},Le}}}var MVe={"-":"",_:" ",0:"0"},mf=/^\s*\d+/,fTs=/^%/,pTs=/[\\^$*+?|[\]().{}]/g;function ql(s,t,r){var n=s<0?"-":"",a=(n?-s:s)+"",i=a.length;return n+(i[t.toLowerCase(),r]))}function gTs(s,t,r){var n=mf.exec(t.slice(r,r+1));return n?(s.w=+n[0],r+n[0].length):-1}function yTs(s,t,r){var n=mf.exec(t.slice(r,r+1));return n?(s.u=+n[0],r+n[0].length):-1}function vTs(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.U=+n[0],r+n[0].length):-1}function bTs(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.V=+n[0],r+n[0].length):-1}function _Ts(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.W=+n[0],r+n[0].length):-1}function IVe(s,t,r){var n=mf.exec(t.slice(r,r+4));return n?(s.y=+n[0],r+n[0].length):-1}function PVe(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function wTs(s,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(s.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function jTs(s,t,r){var n=mf.exec(t.slice(r,r+1));return n?(s.q=n[0]*3-3,r+n[0].length):-1}function NTs(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.m=n[0]-1,r+n[0].length):-1}function LVe(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.d=+n[0],r+n[0].length):-1}function kTs(s,t,r){var n=mf.exec(t.slice(r,r+3));return n?(s.m=0,s.d=+n[0],r+n[0].length):-1}function DVe(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.H=+n[0],r+n[0].length):-1}function STs(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.M=+n[0],r+n[0].length):-1}function CTs(s,t,r){var n=mf.exec(t.slice(r,r+2));return n?(s.S=+n[0],r+n[0].length):-1}function TTs(s,t,r){var n=mf.exec(t.slice(r,r+3));return n?(s.L=+n[0],r+n[0].length):-1}function ETs(s,t,r){var n=mf.exec(t.slice(r,r+6));return n?(s.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function ATs(s,t,r){var n=fTs.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function MTs(s,t,r){var n=mf.exec(t.slice(r));return n?(s.Q=+n[0],r+n[0].length):-1}function ITs(s,t,r){var n=mf.exec(t.slice(r));return n?(s.s=+n[0],r+n[0].length):-1}function RVe(s,t){return ql(s.getDate(),t,2)}function PTs(s,t){return ql(s.getHours(),t,2)}function LTs(s,t){return ql(s.getHours()%12||12,t,2)}function DTs(s,t){return ql(1+QB.count(E2(s),s),t,3)}function Mxt(s,t){return ql(s.getMilliseconds(),t,3)}function RTs(s,t){return Mxt(s,t)+"000"}function OTs(s,t){return ql(s.getMonth()+1,t,2)}function FTs(s,t){return ql(s.getMinutes(),t,2)}function zTs(s,t){return ql(s.getSeconds(),t,2)}function BTs(s){var t=s.getDay();return t===0?7:t}function $Ts(s,t){return ql(W0e.count(E2(s)-1,s),t,2)}function Ixt(s){var t=s.getDay();return t>=4||t===0?ML(s):ML.ceil(s)}function UTs(s,t){return s=Ixt(s),ql(ML.count(E2(s),s)+(E2(s).getDay()===4),t,2)}function qTs(s){return s.getDay()}function VTs(s,t){return ql(spe.count(E2(s)-1,s),t,2)}function HTs(s,t){return ql(s.getFullYear()%100,t,2)}function GTs(s,t){return s=Ixt(s),ql(s.getFullYear()%100,t,2)}function WTs(s,t){return ql(s.getFullYear()%1e4,t,4)}function KTs(s,t){var r=s.getDay();return s=r>=4||r===0?ML(s):ML.ceil(s),ql(s.getFullYear()%1e4,t,4)}function YTs(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+ql(t/60|0,"0",2)+ql(t%60,"0",2)}function OVe(s,t){return ql(s.getUTCDate(),t,2)}function ZTs(s,t){return ql(s.getUTCHours(),t,2)}function XTs(s,t){return ql(s.getUTCHours()%12||12,t,2)}function QTs(s,t){return ql(1+G0e.count(A2(s),s),t,3)}function Pxt(s,t){return ql(s.getUTCMilliseconds(),t,3)}function JTs(s,t){return Pxt(s,t)+"000"}function eEs(s,t){return ql(s.getUTCMonth()+1,t,2)}function tEs(s,t){return ql(s.getUTCMinutes(),t,2)}function sEs(s,t){return ql(s.getUTCSeconds(),t,2)}function rEs(s){var t=s.getUTCDay();return t===0?7:t}function nEs(s,t){return ql(K0e.count(A2(s)-1,s),t,2)}function Lxt(s){var t=s.getUTCDay();return t>=4||t===0?IL(s):IL.ceil(s)}function aEs(s,t){return s=Lxt(s),ql(IL.count(A2(s),s)+(A2(s).getUTCDay()===4),t,2)}function iEs(s){return s.getUTCDay()}function oEs(s,t){return ql(rpe.count(A2(s)-1,s),t,2)}function lEs(s,t){return ql(s.getUTCFullYear()%100,t,2)}function cEs(s,t){return s=Lxt(s),ql(s.getUTCFullYear()%100,t,2)}function dEs(s,t){return ql(s.getUTCFullYear()%1e4,t,4)}function uEs(s,t){var r=s.getUTCDay();return s=r>=4||r===0?IL(s):IL.ceil(s),ql(s.getUTCFullYear()%1e4,t,4)}function hEs(){return"+0000"}function FVe(){return"%"}function zVe(s){return+s}function BVe(s){return Math.floor(+s/1e3)}var O6,Dxt,Rxt;mEs({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 mEs(s){return O6=mTs(s),Dxt=O6.format,O6.parse,Rxt=O6.utcFormat,O6.utcParse,O6}function fEs(s){return new Date(s)}function pEs(s){return s instanceof Date?+s:+new Date(+s)}function UMe(s,t,r,n,a,i,l,o,c,d){var u=TMe(),m=u.invert,f=u.domain,x=d(".%L"),y=d(":%S"),_=d("%I:%M"),b=d("%I %p"),j=d("%a %d"),N=d("%b %d"),C=d("%B"),A=d("%Y");function E(D){return(c(D)t(a/(s.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(a,i)=>n5s(s,i/n))},r.copy=function(){return Bxt(t).domain(s)},q2.apply(r,arguments)}function Z0e(){var s=0,t=.5,r=1,n=1,a,i,l,o,c,d=Sx,u,m=!1,f;function x(_){return isNaN(_=+_)?f:(_=.5+((_=+u(_))-i)*(n*_t}var Vxt=wEs,jEs=X0e,NEs=Vxt,kEs=Y8;function SEs(s){return s&&s.length?jEs(s,kEs,NEs):void 0}var CEs=SEs;const Q0e=gl(CEs);function TEs(s,t){return ss.e^i.s<0?1:-1;for(n=i.d.length,a=s.d.length,t=0,r=ns.d[t]^i.s<0?1:-1;return n===a?0:n>a^i.s<0?1:-1};Za.decimalPlaces=Za.dp=function(){var s=this,t=s.d.length-1,r=(t-s.e)*jd;if(t=s.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};Za.dividedBy=Za.div=function(s){return g2(this,new this.constructor(s))};Za.dividedToIntegerBy=Za.idiv=function(s){var t=this,r=t.constructor;return Vc(g2(t,new r(s),0,1),r.precision)};Za.equals=Za.eq=function(s){return!this.cmp(s)};Za.exponent=function(){return Bh(this)};Za.greaterThan=Za.gt=function(s){return this.cmp(s)>0};Za.greaterThanOrEqualTo=Za.gte=function(s){return this.cmp(s)>=0};Za.isInteger=Za.isint=function(){return this.e>this.d.length-2};Za.isNegative=Za.isneg=function(){return this.s<0};Za.isPositive=Za.ispos=function(){return this.s>0};Za.isZero=function(){return this.s===0};Za.lessThan=Za.lt=function(s){return this.cmp(s)<0};Za.lessThanOrEqualTo=Za.lte=function(s){return this.cmp(s)<1};Za.logarithm=Za.log=function(s){var t,r=this,n=r.constructor,a=n.precision,i=a+5;if(s===void 0)s=new n(10);else if(s=new n(s),s.s<1||s.eq(w0))throw Error(cv+"NaN");if(r.s<1)throw Error(cv+(r.s?"NaN":"-Infinity"));return r.eq(w0)?new n(0):(Hd=!1,t=g2(uz(r,i),uz(s,i),i),Hd=!0,Vc(t,a))};Za.minus=Za.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?Yxt(t,s):Wxt(t,(s.s=-s.s,s))};Za.modulo=Za.mod=function(s){var t,r=this,n=r.constructor,a=n.precision;if(s=new n(s),!s.s)throw Error(cv+"NaN");return r.s?(Hd=!1,t=g2(r,s,0,1).times(s),Hd=!0,r.minus(t)):Vc(new n(r),a)};Za.naturalExponential=Za.exp=function(){return Kxt(this)};Za.naturalLogarithm=Za.ln=function(){return uz(this)};Za.negated=Za.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};Za.plus=Za.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?Wxt(t,s):Yxt(t,(s.s=-s.s,s))};Za.precision=Za.sd=function(s){var t,r,n,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(rA+s);if(t=Bh(a)+1,n=a.d.length-1,r=n*jd+1,n=a.d[n],n){for(;n%10==0;n/=10)r--;for(n=a.d[0];n>=10;n/=10)r++}return s&&t>r?t:r};Za.squareRoot=Za.sqrt=function(){var s,t,r,n,a,i,l,o=this,c=o.constructor;if(o.s<1){if(!o.s)return new c(0);throw Error(cv+"NaN")}for(s=Bh(o),Hd=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=m_(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=Q8((s+1)/2)-(s<0||s%2),a==1/0?t="5e"+s:(t=a.toExponential(),t=t.slice(0,t.indexOf("e")+1)+s),n=new c(t)):n=new c(a.toString()),r=c.precision,a=l=r+3;;)if(i=n,n=i.plus(g2(o,i,l+2)).times(.5),m_(i.d).slice(0,l)===(t=m_(n.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(Vc(i,r+1,0),i.times(i).eq(o)){n=i;break}}else if(t!="9999")break;l+=4}return Hd=!0,Vc(n,r)};Za.times=Za.mul=function(s){var t,r,n,a,i,l,o,c,d,u=this,m=u.constructor,f=u.d,x=(s=new m(s)).d;if(!u.s||!s.s)return new m(0);for(s.s*=u.s,r=u.e+s.e,c=f.length,d=x.length,c=0;){for(t=0,a=c+n;a>n;)o=i[a]+x[n]*f[a-n-1]+t,i[a--]=o%Xm|0,t=o/Xm|0;i[a]=(i[a]+t)%Xm|0}for(;!i[--l];)i.pop();return t?++r:i.shift(),s.d=i,s.e=r,Hd?Vc(s,m.precision):s};Za.toDecimalPlaces=Za.todp=function(s,t){var r=this,n=r.constructor;return r=new n(r),s===void 0?r:(H_(s,0,X8),t===void 0?t=n.rounding:H_(t,0,8),Vc(r,s+Bh(r)+1,t))};Za.toExponential=function(s,t){var r,n=this,a=n.constructor;return s===void 0?r=DA(n,!0):(H_(s,0,X8),t===void 0?t=a.rounding:H_(t,0,8),n=Vc(new a(n),s+1,t),r=DA(n,!0,s+1)),r};Za.toFixed=function(s,t){var r,n,a=this,i=a.constructor;return s===void 0?DA(a):(H_(s,0,X8),t===void 0?t=i.rounding:H_(t,0,8),n=Vc(new i(a),s+Bh(a)+1,t),r=DA(n.abs(),!1,s+Bh(n)+1),a.isneg()&&!a.isZero()?"-"+r:r)};Za.toInteger=Za.toint=function(){var s=this,t=s.constructor;return Vc(new t(s),Bh(s)+1,t.rounding)};Za.toNumber=function(){return+this};Za.toPower=Za.pow=function(s){var t,r,n,a,i,l,o=this,c=o.constructor,d=12,u=+(s=new c(s));if(!s.s)return new c(w0);if(o=new c(o),!o.s){if(s.s<1)throw Error(cv+"Infinity");return o}if(o.eq(w0))return o;if(n=c.precision,s.eq(w0))return Vc(o,n);if(t=s.e,r=s.d.length-1,l=t>=r,i=o.s,l){if((r=u<0?-u:u)<=Gxt){for(a=new c(w0),t=Math.ceil(n/jd+4),Hd=!1;r%2&&(a=a.times(o),qVe(a.d,t)),r=Q8(r/2),r!==0;)o=o.times(o),qVe(o.d,t);return Hd=!0,s.s<0?new c(w0).div(a):Vc(a,n)}}else if(i<0)throw Error(cv+"NaN");return i=i<0&&s.d[Math.max(t,r)]&1?-1:1,o.s=1,Hd=!1,a=s.times(uz(o,n+d)),Hd=!0,a=Kxt(a),a.s=i,a};Za.toPrecision=function(s,t){var r,n,a=this,i=a.constructor;return s===void 0?(r=Bh(a),n=DA(a,r<=i.toExpNeg||r>=i.toExpPos)):(H_(s,1,X8),t===void 0?t=i.rounding:H_(t,0,8),a=Vc(new i(a),s,t),r=Bh(a),n=DA(a,s<=r||r<=i.toExpNeg,s)),n};Za.toSignificantDigits=Za.tosd=function(s,t){var r=this,n=r.constructor;return s===void 0?(s=n.precision,t=n.rounding):(H_(s,1,X8),t===void 0?t=n.rounding:H_(t,0,8)),Vc(new n(r),s,t)};Za.toString=Za.valueOf=Za.val=Za.toJSON=Za[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=Bh(s),r=s.constructor;return DA(s,t<=r.toExpNeg||t>=r.toExpPos)};function Wxt(s,t){var r,n,a,i,l,o,c,d,u=s.constructor,m=u.precision;if(!s.s||!t.s)return t.s||(t=new u(s)),Hd?Vc(t,m):t;if(c=s.d,d=t.d,l=s.e,a=t.e,c=c.slice(),i=l-a,i){for(i<0?(n=c,i=-i,o=d.length):(n=d,a=l,o=c.length),l=Math.ceil(m/jd),o=l>o?l+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=c.length,i=d.length,o-i<0&&(i=o,n=d,d=c,c=n),r=0;i;)r=(c[--i]=c[i]+d[i]+r)/Xm|0,c[i]%=Xm;for(r&&(c.unshift(r),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Hd?Vc(t,m):t}function H_(s,t,r){if(s!==~~s||sr)throw Error(rA+s)}function m_(s){var t,r,n,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function r(n,a,i){for(var l=0;i--;)n[i]-=l,l=n[i]1;)n.shift()}return function(n,a,i,l){var o,c,d,u,m,f,x,y,_,b,j,N,C,A,E,D,R,F,O=n.constructor,B=n.s==a.s?1:-1,K=n.d,Z=a.d;if(!n.s)return new O(n);if(!a.s)throw Error(cv+"Division by zero");for(c=n.e-a.e,R=Z.length,E=K.length,x=new O(B),y=x.d=[],d=0;Z[d]==(K[d]||0);)++d;if(Z[d]>(K[d]||0)&&--c,i==null?N=i=O.precision:l?N=i+(Bh(n)-Bh(a))+1:N=i,N<0)return new O(0);if(N=N/jd+2|0,d=0,R==1)for(u=0,Z=Z[0],N++;(d1&&(Z=s(Z,u),K=s(K,u),R=Z.length,E=K.length),A=R,_=K.slice(0,R),b=_.length;b=Xm/2&&++D;do u=0,o=t(Z,_,R,b),o<0?(j=_[0],R!=b&&(j=j*Xm+(_[1]||0)),u=j/D|0,u>1?(u>=Xm&&(u=Xm-1),m=s(Z,u),f=m.length,b=_.length,o=t(m,_,f,b),o==1&&(u--,r(m,R16)throw Error(HMe+Bh(s));if(!s.s)return new u(w0);for(t==null?(Hd=!1,o=m):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(n=Math.log(FT(2,d))/Math.LN10*2+5|0,o+=n,r=a=i=new u(w0),u.precision=o;;){if(a=Vc(a.times(s),o),r=r.times(++c),l=i.plus(g2(a,r,o)),m_(l.d).slice(0,o)===m_(i.d).slice(0,o)){for(;d--;)i=Vc(i.times(i),o);return u.precision=m,t==null?(Hd=!0,Vc(i,m)):i}i=l}}function Bh(s){for(var t=s.e*jd,r=s.d[0];r>=10;r/=10)t++;return t}function Uwe(s,t,r){if(t>s.LN10.sd())throw Hd=!0,r&&(s.precision=r),Error(cv+"LN10 precision limit exceeded");return Vc(new s(s.LN10),t)}function dk(s){for(var t="";s--;)t+="0";return t}function uz(s,t){var r,n,a,i,l,o,c,d,u,m=1,f=10,x=s,y=x.d,_=x.constructor,b=_.precision;if(x.s<1)throw Error(cv+(x.s?"NaN":"-Infinity"));if(x.eq(w0))return new _(0);if(t==null?(Hd=!1,d=b):d=t,x.eq(10))return t==null&&(Hd=!0),Uwe(_,d);if(d+=f,_.precision=d,r=m_(y),n=r.charAt(0),i=Bh(x),Math.abs(i)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)x=x.times(s),r=m_(x.d),n=r.charAt(0),m++;i=Bh(x),n>1?(x=new _("0."+r),i++):x=new _(n+"."+r.slice(1))}else return c=Uwe(_,d+2,b).times(i+""),x=uz(new _(n+"."+r.slice(1)),d-f).plus(c),_.precision=b,t==null?(Hd=!0,Vc(x,b)):x;for(o=l=x=g2(x.minus(w0),x.plus(w0),d),u=Vc(x.times(x),d),a=3;;){if(l=Vc(l.times(u),d),c=o.plus(g2(l,new _(a),d)),m_(c.d).slice(0,d)===m_(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(Uwe(_,d+2,b).times(i+""))),o=g2(o,new _(m),d),_.precision=b,t==null?(Hd=!0,Vc(o,b)):o;o=c,a+=2}}function UVe(s,t){var r,n,a;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(n,a),t){if(a-=n,r=r-n-1,s.e=Q8(r/jd),s.d=[],n=(r+1)%jd,r<0&&(n+=jd),nnpe||s.e<-npe))throw Error(HMe+r)}else s.s=0,s.e=0,s.d=[0];return s}function Vc(s,t,r){var n,a,i,l,o,c,d,u,m=s.d;for(l=1,i=m[0];i>=10;i/=10)l++;if(n=t-l,n<0)n+=jd,a=t,d=m[u=0];else{if(u=Math.ceil((n+1)/jd),i=m.length,u>=i)return s;for(d=i=m[u],l=1;i>=10;i/=10)l++;n%=jd,a=n-jd+l}if(r!==void 0&&(i=FT(10,l-a-1),o=d/i%10|0,c=t<0||m[u+1]!==void 0||d%i,c=r<4?(o||c)&&(r==0||r==(s.s<0?3:2)):o>5||o==5&&(r==4||c||r==6&&(n>0?a>0?d/FT(10,l-a):0:m[u-1])%10&1||r==(s.s<0?8:7))),t<1||!m[0])return c?(i=Bh(s),m.length=1,t=t-i-1,m[0]=FT(10,(jd-t%jd)%jd),s.e=Q8(-t/jd)||0):(m.length=1,m[0]=s.e=s.s=0),s;if(n==0?(m.length=u,i=1,u--):(m.length=u+1,i=FT(10,jd-n),m[u]=a>0?(d/FT(10,l-a)%FT(10,a)|0)*i:0),c)for(;;)if(u==0){(m[0]+=i)==Xm&&(m[0]=1,++s.e);break}else{if(m[u]+=i,m[u]!=Xm)break;m[u--]=0,i=1}for(n=m.length;m[--n]===0;)m.pop();if(Hd&&(s.e>npe||s.e<-npe))throw Error(HMe+Bh(s));return s}function Yxt(s,t){var r,n,a,i,l,o,c,d,u,m,f=s.constructor,x=f.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new f(s),Hd?Vc(t,x):t;if(c=s.d,m=t.d,n=t.e,d=s.e,c=c.slice(),l=d-n,l){for(u=l<0,u?(r=c,l=-l,o=m.length):(r=m,n=d,o=c.length),a=Math.max(Math.ceil(x/jd),o)+2,l>a&&(l=a,r.length=1),r.reverse(),a=l;a--;)r.push(0);r.reverse()}else{for(a=c.length,o=m.length,u=a0;--a)c[o++]=0;for(a=m.length;a>l;){if(c[--a]0?i=i.charAt(0)+"."+i.slice(1)+dk(n):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+dk(-a-1)+i,r&&(n=r-l)>0&&(i+=dk(n))):a>=l?(i+=dk(a+1-l),r&&(n=r-a-1)>0&&(i=i+"."+dk(n))):((n=a+1)0&&(a+1===l&&(i+="."),i+=dk(n))),s.s<0?"-"+i:i}function qVe(s,t){if(s.length>t)return s.length=t,!0}function Zxt(s){var t,r,n;function a(i){var l=this;if(!(l instanceof a))return new a(i);if(l.constructor=a,i instanceof a){l.s=i.s,l.e=i.e,l.d=(i=i.d)?i.slice():i;return}if(typeof i=="number"){if(i*0!==0)throw Error(rA+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 UVe(l,i.toString())}else if(typeof i!="string")throw Error(rA+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,YEs.test(i))UVe(l,i);else throw Error(rA+i)}if(a.prototype=Za,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=Zxt,a.config=a.set=ZEs,s===void 0&&(s={}),s)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t=a[t+1]&&n<=a[t+2])this[r]=n;else throw Error(rA+r+": "+n);if((n=s[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(rA+r+": "+n);return this}var GMe=Zxt(KEs);w0=new GMe(1);const kc=GMe;function XEs(s){return tAs(s)||eAs(s)||JEs(s)||QEs()}function QEs(){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 JEs(s,t){if(s){if(typeof s=="string")return g4e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return g4e(s,t)}}function eAs(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function tAs(s){if(Array.isArray(s))return g4e(s)}function g4e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=t?r.apply(void 0,a):s(t-l,VVe(function(){for(var o=arguments.length,c=new Array(o),d=0;ds.length)&&(t=s.length);for(var r=0,n=new Array(t);r"u"||!(Symbol.iterator in Object(s)))){var r=[],n=!0,a=!1,i=void 0;try{for(var l=s[Symbol.iterator](),o;!(n=(o=l.next()).done)&&(r.push(o.value),!(t&&r.length===t));n=!0);}catch(c){a=!0,i=c}finally{try{!n&&l.return!=null&&l.return()}finally{if(a)throw i}}return r}}function xAs(s){if(Array.isArray(s))return s}function tgt(s){var t=hz(s,2),r=t[0],n=t[1],a=r,i=n;return r>n&&(a=n,i=r),[a,i]}function sgt(s,t,r){if(s.lte(0))return new kc(0);var n=tye.getDigitCount(s.toNumber()),a=new kc(10).pow(n),i=s.div(a),l=n!==1?.05:.1,o=new kc(Math.ceil(i.div(l).toNumber())).add(r).mul(l),c=o.mul(a);return t?c:new kc(Math.ceil(c))}function gAs(s,t,r){var n=1,a=new kc(s);if(!a.isint()&&r){var i=Math.abs(s);i<1?(n=new kc(10).pow(tye.getDigitCount(s)-1),a=new kc(Math.floor(a.div(n).toNumber())).mul(n)):i>1&&(a=new kc(Math.floor(s)))}else s===0?a=new kc(Math.floor((t-1)/2)):r||(a=new kc(Math.floor(s)));var l=Math.floor((t-1)/2),o=aAs(nAs(function(c){return a.add(new kc(c-l).mul(n)).toNumber()}),y4e);return o(0,t)}function rgt(s,t,r,n){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-s)/(r-1)))return{step:new kc(0),tickMin:new kc(0),tickMax:new kc(0)};var i=sgt(new kc(t).sub(s).div(r-1),n,a),l;s<=0&&t>=0?l=new kc(0):(l=new kc(s).add(t).div(2),l=l.sub(new kc(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new kc(t).sub(l).div(i).toNumber()),d=o+c+1;return d>r?rgt(s,t,r,n,a+1):(d0?c+(r-d):c,o=t>0?o:o+(r-d)),{step:i,tickMin:l.sub(new kc(o).mul(i)),tickMax:l.add(new kc(c).mul(i))})}function yAs(s){var t=hz(s,2),r=t[0],n=t[1],a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=Math.max(a,2),o=tgt([r,n]),c=hz(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var m=u===1/0?[d].concat(b4e(y4e(0,a-1).map(function(){return 1/0}))):[].concat(b4e(y4e(0,a-1).map(function(){return-1/0})),[u]);return r>n?v4e(m):m}if(d===u)return gAs(d,a,i);var f=rgt(d,u,l,i),x=f.step,y=f.tickMin,_=f.tickMax,b=tye.rangeStep(y,_.add(new kc(.1).mul(x)),x);return r>n?v4e(b):b}function vAs(s,t){var r=hz(s,2),n=r[0],a=r[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=tgt([n,a]),o=hz(l,2),c=o[0],d=o[1];if(c===-1/0||d===1/0)return[n,a];if(c===d)return[c];var u=Math.max(t,2),m=sgt(new kc(d).sub(c).div(u-1),i,0),f=[].concat(b4e(tye.rangeStep(new kc(c),new kc(d).sub(new kc(.99).mul(m)),m)),[d]);return n>a?v4e(f):f}var bAs=Jxt(yAs),_As=Jxt(vAs),wAs="Invariant failed";function RA(s,t){throw new Error(wAs)}var jAs=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function PL(s){"@babel/helpers - typeof";return PL=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},PL(s)}function ape(){return ape=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function AAs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function MAs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function IAs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,m=a[d].coordinate,f=d>=o-1?a[0].coordinate:a[d+1].coordinate,x=void 0;if(Nx(m-u)!==Nx(f-m)){var y=[];if(Nx(f-m)===Nx(c[1]-c[0])){x=f;var _=m+c[1]-c[0];y[0]=Math.min(_,(_+u)/2),y[1]=Math.max(_,(_+u)/2)}else{x=u;var b=f+c[1]-c[0];y[0]=Math.min(m,(b+m)/2),y[1]=Math.max(m,(b+m)/2)}var j=[Math.min(m,(x+m)/2),Math.max(m,(x+m)/2)];if(t>j[0]&&t<=j[1]||t>=y[0]&&t<=y[1]){l=a[d].index;break}}else{var N=Math.min(u,f),C=Math.max(u,f);if(t>(N+m)/2&&t<=(C+m)/2){l=a[d].index;break}}}else for(var A=0;A0&&A(n[A].coordinate+n[A-1].coordinate)/2&&t<=(n[A].coordinate+n[A+1].coordinate)/2||A===o-1&&t>(n[A].coordinate+n[A-1].coordinate)/2){l=n[A].index;break}return l},WMe=function(t){var r,n=t,a=n.type.displayName,i=(r=t.type)!==null&&r!==void 0&&r.defaultProps?Ou(Ou({},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},YAs=function(t){var r=t.barSize,n=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var l={},o=Object.keys(i),c=0,d=o.length;c=0});if(j&&j.length){var N=j[0].type.defaultProps,C=N!==void 0?Ou(Ou({},N),j[0].props):j[0].props,A=C.barSize,E=C[b];l[E]||(l[E]=[]);var D=yo(A)?r:A;l[E].push({item:j[0],stackList:j.slice(1),barSize:yo(D)?void 0:kx(D,n,0)})}}return l},ZAs=function(t){var r=t.barGap,n=t.barCategoryGap,a=t.bandSize,i=t.sizeList,l=i===void 0?[]:i,o=t.maxBarSize,c=l.length;if(c<1)return null;var d=kx(r,a,0,!0),u,m=[];if(l[0].barSize===+l[0].barSize){var f=!1,x=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&&x>0&&(f=!0,x*=.9,y=c*x);var _=(a-y)/2>>0,b={offset:_-d,size:0};u=l.reduce(function(A,E){var D={item:E.item,position:{offset:b.offset+b.size+d,size:f?x:E.barSize}},R=[].concat(WVe(A),[D]);return b=R[R.length-1].position,E.stackList&&E.stackList.length&&E.stackList.forEach(function(F){R.push({item:F,position:b})}),R},m)}else{var j=kx(n,a,0,!0);a-2*j-(c-1)*d<=0&&(d=0);var N=(a-2*j-(c-1)*d)/c;N>1&&(N>>=0);var C=o===+o?Math.min(N,o):N;u=l.reduce(function(A,E,D){var R=[].concat(WVe(A),[{item:E.item,position:{offset:j+(N+d)*D+(N-C)/2,size:C}}]);return E.stackList&&E.stackList.length&&E.stackList.forEach(function(F){R.push({item:F,position:R[R.length-1].position})}),R},m)}return u},XAs=function(t,r,n,a){var i=n.children,l=n.width,o=n.margin,c=l-(o.left||0)-(o.right||0),d=ogt({children:i,legendWidth:c});if(d){var u=a||{},m=u.width,f=u.height,x=d.align,y=d.verticalAlign,_=d.layout;if((_==="vertical"||_==="horizontal"&&y==="middle")&&x!=="center"&&Jn(t[x]))return Ou(Ou({},t),{},IP({},x,t[x]+(m||0)));if((_==="horizontal"||_==="vertical"&&x==="center")&&y!=="middle"&&Jn(t[y]))return Ou(Ou({},t),{},IP({},y,t[y]+(f||0)))}return t},QAs=function(t,r,n){return yo(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},lgt=function(t,r,n,a,i){var l=r.props.children,o=L0(l,e$).filter(function(d){return QAs(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 m=hm(u,n);if(yo(m))return d;var f=Array.isArray(m)?[J0e(m),Q0e(m)]:[m,m],x=c.reduce(function(y,_){var b=hm(u,_,0),j=f[0]-Math.abs(Array.isArray(b)?b[0]:b),N=f[1]+Math.abs(Array.isArray(b)?b[1]:b);return[Math.min(j,y[0]),Math.max(N,y[1])]},[1/0,-1/0]);return[Math.min(x[0],d[0]),Math.max(x[1],d[1])]},[1/0,-1/0])}return null},JAs=function(t,r,n,a,i){var l=r.map(function(o){return lgt(t,o,n,i,a)}).filter(function(o){return!yo(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},cgt=function(t,r,n,a,i){var l=r.map(function(c){var d=c.props.dataKey;return n==="number"&&d&&lgt(t,c,d,a)||$7(t,d,n,i)});if(n==="number")return l.reduce(function(c,d){return[Math.min(c[0],d[0]),Math.max(c[1],d[1])]},[1/0,-1/0]);var o={};return l.reduce(function(c,d){for(var u=0,m=d.length;u=2?Nx(o[0]-o[1])*2*d:d,r&&(t.ticks||t.niceTicks)){var u=(t.ticks||t.niceTicks).map(function(m){var f=i?i.indexOf(m):m;return{coordinate:a(f)+d,value:m,offset:d}});return u.filter(function(m){return!GB(m.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(m,f){return{coordinate:a(m)+d,value:m,index:f,offset:d}}):a.ticks&&!n?a.ticks(t.tickCount).map(function(m){return{coordinate:a(m)+d,value:m,offset:d}}):a.domain().map(function(m,f){return{coordinate:a(m)+d,value:i?i[m]:m,index:f,offset:d}})},qwe=new WeakMap,dV=function(t,r){if(typeof r!="function")return t;qwe.has(t)||qwe.set(t,new WeakMap);var n=qwe.get(t);if(n.has(r))return n.get(r);var a=function(){t.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,a),a},hgt=function(t,r,n){var a=t.scale,i=t.type,l=t.layout,o=t.axisType;if(a==="auto")return l==="radial"&&o==="radiusAxis"?{scale:iz(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:epe(),realScaleType:"linear"}:i==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:B7(),realScaleType:"point"}:i==="category"?{scale:iz(),realScaleType:"band"}:{scale:epe(),realScaleType:"linear"};if(IA(a)){var c="scale".concat(F0e(a));return{scale:($Ve[c]||B7)(),realScaleType:$Ve[c]?c:"point"}}return oo(a)?{scale:a}:{scale:B7(),realScaleType:"point"}},YVe=1e-4,mgt=function(t){var r=t.domain();if(!(!r||r.length<=2)){var n=r.length,a=t.range(),i=Math.min(a[0],a[1])-YVe,l=Math.max(a[0],a[1])+YVe,o=t(r[0]),c=t(r[n-1]);(ol||cl)&&t.domain([r[0],r[n-1]])}},eMs=function(t,r){if(!t)return null;for(var n=0,a=t.length;na)&&(i[1]=a),i[0]>a&&(i[0]=a),i[1]=0?(t[o][n][0]=i,t[o][n][1]=i+c,i=t[o][n][1]):(t[o][n][0]=l,t[o][n][1]=l+c,l=t[o][n][1])}},rMs=function(t){var r=t.length;if(!(r<=0))for(var n=0,a=t[0].length;n=0?(t[l][n][0]=i,t[l][n][1]=i+o,i=t[l][n][1]):(t[l][n][0]=0,t[l][n][1]=0)}},nMs={sign:sMs,expand:j_s,none:kL,silhouette:N_s,wiggle:k_s,positive:rMs},aMs=function(t,r,n){var a=r.map(function(o){return o.props.dataKey}),i=nMs[n],l=w_s().keys(a).value(function(o,c){return+hm(o,c,0)}).order(KSe).offset(i);return l(t)},iMs=function(t,r,n,a,i,l){if(!t)return null;var o=l?r.reverse():r,c={},d=o.reduce(function(m,f){var x,y=(x=f.type)!==null&&x!==void 0&&x.defaultProps?Ou(Ou({},f.type.defaultProps),f.props):f.props,_=y.stackId,b=y.hide;if(b)return m;var j=y[n],N=m[j]||{hasStack:!1,stackGroups:{}};if(fm(_)){var C=N.stackGroups[_]||{numericAxisId:n,cateAxisId:a,items:[]};C.items.push(f),N.hasStack=!0,N.stackGroups[_]=C}else N.stackGroups[G8("_stackId_")]={numericAxisId:n,cateAxisId:a,items:[f]};return Ou(Ou({},m),{},IP({},j,N))},c),u={};return Object.keys(d).reduce(function(m,f){var x=d[f];if(x.hasStack){var y={};x.stackGroups=Object.keys(x.stackGroups).reduce(function(_,b){var j=x.stackGroups[b];return Ou(Ou({},_),{},IP({},b,{numericAxisId:n,cateAxisId:a,items:j.items,stackedData:aMs(t,j.items,i)}))},y)}return Ou(Ou({},m),{},IP({},f,x))},u)},fgt=function(t,r){var n=r.realScaleType,a=r.type,i=r.tickCount,l=r.originalDomain,o=r.allowDecimals,c=n||r.scale;if(c!=="auto"&&c!=="linear")return null;if(i&&a==="number"&&l&&(l[0]==="auto"||l[1]==="auto")){var d=t.domain();if(!d.length)return null;var u=bAs(d,i,o);return t.domain([J0e(u),Q0e(u)]),{niceTicks:u}}if(i&&a==="number"){var m=t.domain(),f=_As(m,i,o);return{niceTicks:f}}return null};function ZVe(s){var t=s.axis,r=s.ticks,n=s.bandSize,a=s.entry,i=s.index,l=s.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!yo(a[t.dataKey])){var o=Pfe(r,"value",a[t.dataKey]);if(o)return o.coordinate+n/2}return r[i]?r[i].coordinate+n/2:null}var c=hm(a,yo(l)?t.dataKey:l);return yo(c)?null:t.scale(c)}var XVe=function(t){var r=t.axis,n=t.ticks,a=t.offset,i=t.bandSize,l=t.entry,o=t.index;if(r.type==="category")return n[o]?n[o].coordinate+a:null;var c=hm(l,r.dataKey,r.domain[o]);return yo(c)?null:r.scale(c)-i/2+a},oMs=function(t){var r=t.numericAxis,n=r.scale.domain();if(r.type==="number"){var a=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return a<=0&&i>=0?0:i<0?i:a}return n[0]},lMs=function(t,r){var n,a=(n=t.type)!==null&&n!==void 0&&n.defaultProps?Ou(Ou({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(fm(i)){var l=r[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},cMs=function(t){return t.reduce(function(r,n){return[J0e(n.concat([r[0]]).filter(Jn)),Q0e(n.concat([r[1]]).filter(Jn))]},[1/0,-1/0])},pgt=function(t,r,n){return Object.keys(t).reduce(function(a,i){var l=t[i],o=l.stackedData,c=o.reduce(function(d,u){var m=cMs(u.slice(r,n+1));return[Math.min(d[0],m[0]),Math.max(d[1],m[1])]},[1/0,-1/0]);return[Math.min(c[0],a[0]),Math.max(c[1],a[1])]},[1/0,-1/0]).map(function(a){return a===1/0||a===-1/0?0:a})},QVe=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,JVe=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,N4e=function(t,r,n){if(oo(t))return t(r,n);if(!Array.isArray(t))return r;var a=[];if(Jn(t[0]))a[0]=n?t[0]:Math.min(t[0],r[0]);else if(QVe.test(t[0])){var i=+QVe.exec(t[0])[1];a[0]=r[0]-i}else oo(t[0])?a[0]=t[0](r[0]):a[0]=r[0];if(Jn(t[1]))a[1]=n?t[1]:Math.max(t[1],r[1]);else if(JVe.test(t[1])){var l=+JVe.exec(t[1])[1];a[1]=r[1]+l}else oo(t[1])?a[1]=t[1](r[1]):a[1]=r[1];return a},ope=function(t,r,n){if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!n||a>0)return a}if(t&&r&&r.length>=2){for(var i=_Me(r,function(m){return m.coordinate}),l=1/0,o=1,c=i.length;os.length)&&(t=s.length);for(var r=0,n=new Array(t);r2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},yMs=function(t,r,n,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=kx(t.cx,l,l/2),m=kx(t.cy,o,o/2),f=ygt(l,o,n),x=kx(t.innerRadius,f,0),y=kx(t.outerRadius,f,f*.8),_=Object.keys(r);return _.reduce(function(b,j){var N=r[j],C=N.domain,A=N.reversed,E;if(yo(N.range))a==="angleAxis"?E=[c,d]:a==="radiusAxis"&&(E=[x,y]),A&&(E=[E[1],E[0]]);else{E=N.range;var D=E,R=hMs(D,2);c=R[0],d=R[1]}var F=hgt(N,i),O=F.realScaleType,B=F.scale;B.domain(C).range(E),mgt(B);var K=fgt(B,Ij(Ij({},N),{},{realScaleType:O})),Z=Ij(Ij(Ij({},N),K),{},{range:E,radius:y,realScaleType:O,scale:B,cx:u,cy:m,innerRadius:x,outerRadius:y,startAngle:c,endAngle:d});return Ij(Ij({},b),{},ggt({},j,Z))},{})},vMs=function(t,r){var n=t.x,a=t.y,i=r.x,l=r.y;return Math.sqrt(Math.pow(n-i,2)+Math.pow(a-l,2))},bMs=function(t,r){var n=t.x,a=t.y,i=r.cx,l=r.cy,o=vMs({x:n,y:a},{x:i,y:l});if(o<=0)return{radius:o};var c=(n-i)/o,d=Math.acos(c);return a>l&&(d=2*Math.PI-d),{radius:o,angle:gMs(d),angleInRadian:d}},_Ms=function(t){var r=t.startAngle,n=t.endAngle,a=Math.floor(r/360),i=Math.floor(n/360),l=Math.min(a,i);return{startAngle:r-l*360,endAngle:n-l*360}},wMs=function(t,r){var n=r.startAngle,a=r.endAngle,i=Math.floor(n/360),l=Math.floor(a/360),o=Math.min(i,l);return t+o*360},rHe=function(t,r){var n=t.x,a=t.y,i=bMs({x:n,y:a},r),l=i.radius,o=i.angle,c=r.innerRadius,d=r.outerRadius;if(ld)return!1;if(l===0)return!0;var u=_Ms(r),m=u.startAngle,f=u.endAngle,x=o,y;if(m<=f){for(;x>f;)x-=360;for(;x=m&&x<=f}else{for(;x>m;)x-=360;for(;x=f&&x<=m}return y?Ij(Ij({},r),{},{radius:l,angle:wMs(x,r)}):null},vgt=function(t){return!k.isValidElement(t)&&!oo(t)&&typeof t!="boolean"?t.className:""};function xz(s){"@babel/helpers - typeof";return xz=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xz(s)}var jMs=["offset"];function NMs(s){return TMs(s)||CMs(s)||SMs(s)||kMs()}function kMs(){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 SMs(s,t){if(s){if(typeof s=="string")return k4e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return k4e(s,t)}}function CMs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function TMs(s){if(Array.isArray(s))return k4e(s)}function k4e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function AMs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function nHe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function sm(s){for(var t=1;t=0?1:-1,C,A;a==="insideStart"?(C=x+N*l,A=_):a==="insideEnd"?(C=y-N*l,A=!_):a==="end"&&(C=y+N*l,A=_),A=j<=0?A:!A;var E=od(d,u,b,C),D=od(d,u,b,C+(A?1:-1)*359),R="M".concat(E.x,",").concat(E.y,` A`).concat(b,",").concat(b,",0,1,").concat(A?0:1,`, `).concat(D.x,",").concat(D.y),F=yo(t.id)?G8("recharts-radial-line-"):t.id;return Ct.createElement("text",gz({},n,{dominantBaseline:"central",className:_o("recharts-radial-bar-label",o)}),Ct.createElement("defs",null,Ct.createElement("path",{id:F,d:R})),Ct.createElement("textPath",{xlinkHref:"#".concat(F)},r))},OMs=function(t){var r=t.viewBox,n=t.offset,a=t.position,i=r,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,m=i.endAngle,f=(u+m)/2;if(a==="outside"){var x=od(l,o,d+n,f),y=x.x,_=x.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 b=(c+d)/2,j=od(l,o,b,f),N=j.x,C=j.y;return{x:N,y:C,textAnchor:"middle",verticalAnchor:"middle"}},FMs=function(t){var r=t.viewBox,n=t.parentViewBox,a=t.offset,i=t.position,l=r,o=l.x,c=l.y,d=l.width,u=l.height,m=u>=0?1:-1,f=m*a,x=m>0?"end":"start",y=m>0?"start":"end",_=d>=0?1:-1,b=_*a,j=_>0?"end":"start",N=_>0?"start":"end";if(i==="top"){var C={x:o+d/2,y:c-m*a,textAnchor:"middle",verticalAnchor:x};return sm(sm({},C),n?{height:Math.max(c-n.y,0),width:d}:{})}if(i==="bottom"){var A={x:o+d/2,y:c+u+f,textAnchor:"middle",verticalAnchor:y};return sm(sm({},A),n?{height:Math.max(n.y+n.height-(c+u),0),width:d}:{})}if(i==="left"){var E={x:o-b,y:c+u/2,textAnchor:j,verticalAnchor:"middle"};return sm(sm({},E),n?{width:Math.max(E.x-n.x,0),height:u}:{})}if(i==="right"){var D={x:o+d+b,y:c+u/2,textAnchor:N,verticalAnchor:"middle"};return sm(sm({},D),n?{width:Math.max(n.x+n.width-D.x,0),height:u}:{})}var R=n?{width:d,height:u}:{};return i==="insideLeft"?sm({x:o+b,y:c+u/2,textAnchor:N,verticalAnchor:"middle"},R):i==="insideRight"?sm({x:o+d-b,y:c+u/2,textAnchor:j,verticalAnchor:"middle"},R):i==="insideTop"?sm({x:o+d/2,y:c+f,textAnchor:"middle",verticalAnchor:y},R):i==="insideBottom"?sm({x:o+d/2,y:c+u-f,textAnchor:"middle",verticalAnchor:x},R):i==="insideTopLeft"?sm({x:o+b,y:c+f,textAnchor:N,verticalAnchor:y},R):i==="insideTopRight"?sm({x:o+d-b,y:c+f,textAnchor:j,verticalAnchor:y},R):i==="insideBottomLeft"?sm({x:o+b,y:c+u-f,textAnchor:N,verticalAnchor:x},R):i==="insideBottomRight"?sm({x:o+d-b,y:c+u-f,textAnchor:j,verticalAnchor:x},R):U8(i)&&(Jn(i.x)||nE(i.x))&&(Jn(i.y)||nE(i.y))?sm({x:o+kx(i.x,d),y:c+kx(i.y,u),textAnchor:"end",verticalAnchor:"end"},R):sm({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},R)},zMs=function(t){return"cx"in t&&Jn(t.cx)};function sf(s){var t=s.offset,r=t===void 0?5:t,n=EMs(s,jMs),a=sm({offset:r},n),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,u=a.className,m=u===void 0?"":u,f=a.textBreakAll;if(!i||yo(o)&&yo(c)&&!k.isValidElement(d)&&!oo(d))return null;if(k.isValidElement(d))return k.cloneElement(d,a);var x;if(oo(d)){if(x=k.createElement(d,a),k.isValidElement(x))return x}else x=LMs(a);var y=zMs(i),_=Li(a,!0);if(y&&(l==="insideStart"||l==="insideEnd"||l==="end"))return RMs(a,x,_);var b=y?OMs(a):FMs(a);return Ct.createElement(LA,gz({className:_o("recharts-label",m)},_,b,{breakAll:f}),x)}sf.displayName="Label";var bgt=function(t){var r=t.cx,n=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,m=t.x,f=t.y,x=t.top,y=t.left,_=t.width,b=t.height,j=t.clockWise,N=t.labelViewBox;if(N)return N;if(Jn(_)&&Jn(b)){if(Jn(m)&&Jn(f))return{x:m,y:f,width:_,height:b};if(Jn(x)&&Jn(y))return{x,y,width:_,height:b}}return Jn(m)&&Jn(f)?{x:m,y:f,width:0,height:0}:Jn(r)&&Jn(n)?{cx:r,cy:n,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:j}:t.viewBox?t.viewBox:{}},BMs=function(t,r){return t?t===!0?Ct.createElement(sf,{key:"label-implicit",viewBox:r}):fm(t)?Ct.createElement(sf,{key:"label-implicit",viewBox:r,value:t}):k.isValidElement(t)?t.type===sf?k.cloneElement(t,{key:"label-implicit",viewBox:r}):Ct.createElement(sf,{key:"label-implicit",content:t,viewBox:r}):oo(t)?Ct.createElement(sf,{key:"label-implicit",content:t,viewBox:r}):U8(t)?Ct.createElement(sf,gz({viewBox:r},t,{key:"label-implicit"})):null:null},$Ms=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&n&&!t.label)return null;var a=t.children,i=bgt(t),l=L0(a,sf).map(function(c,d){return k.cloneElement(c,{viewBox:r||i,key:"label-".concat(d)})});if(!n)return l;var o=BMs(t.label,r||i);return[o].concat(NMs(l))};sf.parseViewBox=bgt;sf.renderCallByParent=$Ms;function UMs(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var qMs=UMs;const VMs=gl(qMs);function yz(s){"@babel/helpers - typeof";return yz=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},yz(s)}var HMs=["valueAccessor"],GMs=["data","dataKey","clockWise","id","textBreakAll"];function WMs(s){return XMs(s)||ZMs(s)||YMs(s)||KMs()}function KMs(){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 YMs(s,t){if(s){if(typeof s=="string")return S4e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return S4e(s,t)}}function ZMs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function XMs(s){if(Array.isArray(s))return S4e(s)}function S4e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function t6s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var s6s=function(t){return Array.isArray(t.value)?VMs(t.value):t.value};function y2(s){var t=s.valueAccessor,r=t===void 0?s6s:t,n=oHe(s,HMs),a=n.data,i=n.dataKey,l=n.clockWise,o=n.id,c=n.textBreakAll,d=oHe(n,GMs);return!a||!a.length?null:Ct.createElement(Bl,{className:"recharts-label-list"},a.map(function(u,m){var f=yo(i)?r(u,m):hm(u&&u.payload,i),x=yo(o)?{}:{id:"".concat(o,"-").concat(m)};return Ct.createElement(sf,cpe({},Li(u,!0),d,x,{parentViewBox:u.parentViewBox,value:f,textBreakAll:c,viewBox:sf.parseViewBox(yo(l)?u:iHe(iHe({},u),{},{clockWise:l})),key:"label-".concat(m),index:m}))}))}y2.displayName="LabelList";function r6s(s,t){return s?s===!0?Ct.createElement(y2,{key:"labelList-implicit",data:t}):Ct.isValidElement(s)||oo(s)?Ct.createElement(y2,{key:"labelList-implicit",data:t,content:s}):U8(s)?Ct.createElement(y2,cpe({data:t},s,{key:"labelList-implicit"})):null:null}function n6s(s,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!s||!s.children&&r&&!s.label)return null;var n=s.children,a=L0(n,y2).map(function(l,o){return k.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!r)return a;var i=r6s(s.label,t);return[i].concat(WMs(a))}y2.renderCallByParent=n6s;function vz(s){"@babel/helpers - typeof";return vz=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},vz(s)}function C4e(){return C4e=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(m.x,",").concat(m.y,` `);if(a>0){var x=od(r,n,a,l),y=od(r,n,a,d);f+="L ".concat(y.x,",").concat(y.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(x.x,",").concat(x.y," Z")}else f+="L ".concat(r,",").concat(n," Z");return f},c6s=function(t){var r=t.cx,n=t.cy,a=t.innerRadius,i=t.outerRadius,l=t.cornerRadius,o=t.forceCornerRadius,c=t.cornerIsExternal,d=t.startAngle,u=t.endAngle,m=Nx(u-d),f=uV({cx:r,cy:n,radius:i,angle:d,sign:m,cornerRadius:l,cornerIsExternal:c}),x=f.circleTangency,y=f.lineTangency,_=f.theta,b=uV({cx:r,cy:n,radius:i,angle:u,sign:-m,cornerRadius:l,cornerIsExternal:c}),j=b.circleTangency,N=b.lineTangency,C=b.theta,A=c?Math.abs(d-u):Math.abs(d-u)-_-C;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 `):_gt({cx:r,cy:n,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(+(m<0),",").concat(x.x,",").concat(x.y,` A`).concat(i,",").concat(i,",0,").concat(+(A>180),",").concat(+(m<0),",").concat(j.x,",").concat(j.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(N.x,",").concat(N.y,` `);if(a>0){var D=uV({cx:r,cy:n,radius:a,angle:d,sign:m,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),R=D.circleTangency,F=D.lineTangency,O=D.theta,B=uV({cx:r,cy:n,radius:a,angle:u,sign:-m,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),K=B.circleTangency,Z=B.lineTangency,Q=B.theta,W=c?Math.abs(d-u):Math.abs(d-u)-O-Q;if(W<0&&l===0)return"".concat(E,"L").concat(r,",").concat(n,"Z");E+="L".concat(Z.x,",").concat(Z.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(K.x,",").concat(K.y,` A`).concat(a,",").concat(a,",0,").concat(+(W>180),",").concat(+(m>0),",").concat(R.x,",").concat(R.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(F.x,",").concat(F.y,"Z")}else E+="L".concat(r,",").concat(n,"Z");return E},d6s={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},wgt=function(t){var r=cHe(cHe({},d6s),t),n=r.cx,a=r.cy,i=r.innerRadius,l=r.outerRadius,o=r.cornerRadius,c=r.forceCornerRadius,d=r.cornerIsExternal,u=r.startAngle,m=r.endAngle,f=r.className;if(l0&&Math.abs(u-m)<360?b=c6s({cx:n,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(_,y/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:m}):b=_gt({cx:n,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:m}),Ct.createElement("path",C4e({},Li(r,!0),{className:x,d:b,role:"img"}))};function bz(s){"@babel/helpers - typeof";return bz=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},bz(s)}function T4e(){return T4e=Object.assign?Object.assign.bind():function(s){for(var t=1;t0;)if(!r.equals(s[n],t[n],n,n,s,t,r))return!1;return!0}function k6s(s,t){return J8(s.getTime(),t.getTime())}function gHe(s,t,r){if(s.size!==t.size)return!1;for(var n={},a=s.entries(),i=0,l,o;(l=a.next())&&!l.done;){for(var c=t.entries(),d=!1,u=0;(o=c.next())&&!o.done;){var m=l.value,f=m[0],x=m[1],y=o.value,_=y[0],b=y[1];!d&&!n[u]&&(d=r.equals(f,_,i,u,s,t,r)&&r.equals(x,b,f,_,s,t,r))&&(n[u]=!0),u++}if(!d)return!1;i++}return!0}function S6s(s,t,r){var n=xHe(s),a=n.length;if(xHe(t).length!==a)return!1;for(var i;a-- >0;)if(i=n[a],i===Cgt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!Sgt(t,i)||!r.equals(s[i],t[i],i,i,s,t,r))return!1;return!0}function dO(s,t,r){var n=fHe(s),a=n.length;if(fHe(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=n[a],i===Cgt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!Sgt(t,i)||!r.equals(s[i],t[i],i,i,s,t,r)||(l=pHe(s,i),o=pHe(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function C6s(s,t){return J8(s.valueOf(),t.valueOf())}function T6s(s,t){return s.source===t.source&&s.flags===t.flags}function yHe(s,t,r){if(s.size!==t.size)return!1;for(var n={},a=s.values(),i,l;(i=a.next())&&!i.done;){for(var o=t.values(),c=!1,d=0;(l=o.next())&&!l.done;)!c&&!n[d]&&(c=r.equals(i.value,l.value,i.value,l.value,s,t,r))&&(n[d]=!0),d++;if(!c)return!1}return!0}function E6s(s,t){var r=s.length;if(t.length!==r)return!1;for(;r-- >0;)if(s[r]!==t[r])return!1;return!0}var A6s="[object Arguments]",M6s="[object Boolean]",I6s="[object Date]",P6s="[object Map]",L6s="[object Number]",D6s="[object Object]",R6s="[object RegExp]",O6s="[object Set]",F6s="[object String]",z6s=Array.isArray,vHe=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,bHe=Object.assign,B6s=Object.prototype.toString.call.bind(Object.prototype.toString);function $6s(s){var t=s.areArraysEqual,r=s.areDatesEqual,n=s.areMapsEqual,a=s.areObjectsEqual,i=s.arePrimitiveWrappersEqual,l=s.areRegExpsEqual,o=s.areSetsEqual,c=s.areTypedArraysEqual;return function(u,m,f){if(u===m)return!0;if(u==null||m==null||typeof u!="object"||typeof m!="object")return u!==u&&m!==m;var x=u.constructor;if(x!==m.constructor)return!1;if(x===Object)return a(u,m,f);if(z6s(u))return t(u,m,f);if(vHe!=null&&vHe(u))return c(u,m,f);if(x===Date)return r(u,m,f);if(x===RegExp)return l(u,m,f);if(x===Map)return n(u,m,f);if(x===Set)return o(u,m,f);var y=B6s(u);return y===I6s?r(u,m,f):y===R6s?l(u,m,f):y===P6s?n(u,m,f):y===O6s?o(u,m,f):y===D6s?typeof u.then!="function"&&typeof m.then!="function"&&a(u,m,f):y===A6s?a(u,m,f):y===M6s||y===L6s||y===F6s?i(u,m,f):!1}}function U6s(s){var t=s.circular,r=s.createCustomConfig,n=s.strict,a={areArraysEqual:n?dO:N6s,areDatesEqual:k6s,areMapsEqual:n?mHe(gHe,dO):gHe,areObjectsEqual:n?dO:S6s,arePrimitiveWrappersEqual:C6s,areRegExpsEqual:T6s,areSetsEqual:n?mHe(yHe,dO):yHe,areTypedArraysEqual:n?dO:E6s};if(r&&(a=bHe({},a,r(a))),t){var i=mV(a.areArraysEqual),l=mV(a.areMapsEqual),o=mV(a.areObjectsEqual),c=mV(a.areSetsEqual);a=bHe({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function q6s(s){return function(t,r,n,a,i,l,o){return s(t,r,o)}}function V6s(s){var t=s.circular,r=s.comparator,n=s.createState,a=s.equals,i=s.strict;if(n)return function(c,d){var u=n(),m=u.cache,f=m===void 0?t?new WeakMap:void 0:m,x=u.meta;return r(c,d,{cache:f,equals:a,meta:x,strict:i})};if(t)return function(c,d){return r(c,d,{cache:new WeakMap,equals:a,meta:void 0,strict:i})};var l={cache:void 0,equals:a,meta:void 0,strict:i};return function(c,d){return r(c,d,l)}}var H6s=g4();g4({strict:!0});g4({circular:!0});g4({circular:!0,strict:!0});g4({createInternalComparator:function(){return J8}});g4({strict:!0,createInternalComparator:function(){return J8}});g4({circular:!0,createInternalComparator:function(){return J8}});g4({circular:!0,createInternalComparator:function(){return J8},strict:!0});function g4(s){s===void 0&&(s={});var t=s.circular,r=t===void 0?!1:t,n=s.createInternalComparator,a=s.createState,i=s.strict,l=i===void 0?!1:i,o=U6s(s),c=$6s(o),d=n?n(c):q6s(c);return V6s({circular:r,comparator:c,createState:a,equals:d,strict:l})}function G6s(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function _He(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function a(i){r<0&&(r=i),i-r>t?(s(i),r=-1):G6s(a)};requestAnimationFrame(n)}function E4e(s){"@babel/helpers - typeof";return E4e=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},E4e(s)}function W6s(s){return X6s(s)||Z6s(s)||Y6s(s)||K6s()}function K6s(){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 Y6s(s,t){if(s){if(typeof s=="string")return wHe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return wHe(s,t)}}function wHe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r1?1:j<0?0:j},_=function(j){for(var N=j>1?1:j,C=N,A=0;A<8;++A){var E=m(C)-N,D=x(C);if(Math.abs(E-N)0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,m,f){var x=-(u-m)*n,y=f*i,_=f+(x-y)*o/1e3,b=f*o/1e3+u;return Math.abs(b-m)s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function TIs(s,t){if(s==null)return{};var r={},n=Object.keys(s),a,i;for(i=0;i=0)&&(r[a]=s[a]);return r}function Vwe(s){return IIs(s)||MIs(s)||AIs(s)||EIs()}function EIs(){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 AIs(s,t){if(s){if(typeof s=="string")return L4e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return L4e(s,t)}}function MIs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function IIs(s){if(Array.isArray(s))return L4e(s)}function L4e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function mpe(s){return mpe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},mpe(s)}var G_=function(s){OIs(r,s);var t=FIs(r);function r(n,a){var i;PIs(this,r),i=t.call(this,n,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,u=l.to,m=l.steps,f=l.children,x=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(O4e(i)),i.changeStyle=i.changeStyle.bind(O4e(i)),!o||x<=0)return i.state={style:{}},typeof f=="function"&&(i.state={style:u}),R4e(i);if(m&&m.length)i.state={style:m[0].style};else if(d){if(typeof f=="function")return i.state={style:d},R4e(i);i.state={style:c?VO({},c,d):d}}else i.state={style:{}};return i}return DIs(r,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,u=i.to,m=i.from,f=this.state.style;if(o){if(!l){var x={style:c?VO({},c,u):u};this.state&&f&&(c&&f[c]!==u||!c&&f!==u)&&this.setState(x);return}if(!(H6s(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?m:a.to;if(this.state&&f){var b={style:c?VO({},c,_):_};(c&&f[c]!==_||!c&&f!==_)&&this.setState(b)}this.runAnimation(Jv(Jv({},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,m=a.onAnimationEnd,f=a.onAnimationStart,x=kIs(l,o,fIs(d),c,this.changeStyle),y=function(){i.stopJSAnimation=x()};this.manager.start([f,u,y,c,m])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,m=d.duration,f=m===void 0?0:m,x=function(_,b,j){if(j===0)return _;var N=b.duration,C=b.easing,A=C===void 0?"ease":C,E=b.style,D=b.properties,R=b.onAnimationEnd,F=j>0?l[j-1]:b,O=D||Object.keys(E);if(typeof A=="function"||A==="spring")return[].concat(Vwe(_),[i.runJSAnimation.bind(i,{from:F.style,to:E,duration:N,easing:A}),N]);var B=kHe(O,N,A),K=Jv(Jv(Jv({},F.style),E),{},{transition:B});return[].concat(Vwe(_),[K,N,R]).filter(sIs)};return this.manager.start([c].concat(Vwe(l.reduce(x,[u,Math.max(f,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=Q6s());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,m=a.onAnimationEnd,f=a.steps,x=a.children,y=this.manager;if(this.unSubscribe=y.subscribe(this.handleStyleChange),typeof d=="function"||typeof x=="function"||d==="spring"){this.runJSAnimation(a);return}if(f.length>1){this.runStepAnimation(a);return}var _=o?VO({},o,c):c,b=kHe(Object.keys(_),l,d);y.start([u,i,Jv(Jv({},_),{},{transition:b}),l,m])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var l=a.duration;a.attributeName,a.easing;var o=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=CIs(a,SIs),d=k.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var m=function(x){var y=x.props,_=y.style,b=_===void 0?{}:_,j=y.className,N=k.cloneElement(x,Jv(Jv({},c),{},{style:Jv(Jv({},b),u),className:j}));return N};return d===1?m(k.Children.only(i)):Ct.createElement("div",null,k.Children.map(i,function(f){return m(f)}))}}]),r}(k.PureComponent);G_.displayName="Animate";G_.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};G_.propTypes={from:nc.oneOfType([nc.object,nc.string]),to:nc.oneOfType([nc.object,nc.string]),attributeName:nc.string,duration:nc.number,begin:nc.number,easing:nc.oneOfType([nc.string,nc.func]),steps:nc.arrayOf(nc.shape({duration:nc.number.isRequired,style:nc.object.isRequired,easing:nc.oneOfType([nc.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),nc.func]),properties:nc.arrayOf("string"),onAnimationEnd:nc.func})),children:nc.oneOfType([nc.node,nc.func]),isActive:nc.bool,canBegin:nc.bool,onAnimationEnd:nc.func,shouldReAnimate:nc.bool,onAnimationStart:nc.func,onAnimationReStart:nc.func};function jz(s){"@babel/helpers - typeof";return jz=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},jz(s)}function fpe(){return fpe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0?1:-1,c=n>=0?1:-1,d=a>=0&&n>=0||a<0&&n<0?1:0,u;if(l>0&&i instanceof Array){for(var m=[0,0,0,0],f=0,x=4;fl?l:i[f];u="M".concat(t,",").concat(r+o*m[0]),m[0]>0&&(u+="A ".concat(m[0],",").concat(m[0],",0,0,").concat(d,",").concat(t+c*m[0],",").concat(r)),u+="L ".concat(t+n-c*m[1],",").concat(r),m[1]>0&&(u+="A ".concat(m[1],",").concat(m[1],",0,0,").concat(d,`, `).concat(t+n,",").concat(r+o*m[1])),u+="L ".concat(t+n,",").concat(r+a-o*m[2]),m[2]>0&&(u+="A ".concat(m[2],",").concat(m[2],",0,0,").concat(d,`, `).concat(t+n-c*m[2],",").concat(r+a)),u+="L ".concat(t+c*m[3],",").concat(r+a),m[3]>0&&(u+="A ".concat(m[3],",").concat(m[3],",0,0,").concat(d,`, `).concat(t,",").concat(r+a-o*m[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var y=Math.min(l,i);u="M ".concat(t,",").concat(r+o*y,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+c*y,",").concat(r,` L `).concat(t+n-c*y,",").concat(r,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+n,",").concat(r+o*y,` L `).concat(t+n,",").concat(r+a-o*y,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+n-c*y,",").concat(r+a,` L `).concat(t+c*y,",").concat(r+a,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t,",").concat(r+a-o*y," Z")}else u="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(a," h ").concat(-n," Z");return u},KIs=function(t,r){if(!t||!r)return!1;var n=t.x,a=t.y,i=r.x,l=r.y,o=r.width,c=r.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),u=Math.max(i,i+o),m=Math.min(l,l+c),f=Math.max(l,l+c);return n>=d&&n<=u&&a>=m&&a<=f}return!1},YIs={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},KMe=function(t){var r=PHe(PHe({},YIs),t),n=k.useRef(),a=k.useState(-1),i=BIs(a,2),l=i[0],o=i[1];k.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var A=n.current.getTotalLength();A&&o(A)}catch{}},[]);var c=r.x,d=r.y,u=r.width,m=r.height,f=r.radius,x=r.className,y=r.animationEasing,_=r.animationDuration,b=r.animationBegin,j=r.isAnimationActive,N=r.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||m!==+m||u===0||m===0)return null;var C=_o("recharts-rectangle",x);return N?Ct.createElement(G_,{canBegin:l>0,from:{width:u,height:m,x:c,y:d},to:{width:u,height:m,x:c,y:d},duration:_,animationEasing:y,isActive:N},function(A){var E=A.width,D=A.height,R=A.x,F=A.y;return Ct.createElement(G_,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:_,isActive:j,easing:y},Ct.createElement("path",fpe({},Li(r,!0),{className:C,d:LHe(R,F,E,D,f),ref:n})))}):Ct.createElement("path",fpe({},Li(r,!0),{className:C,d:LHe(c,d,u,m,f)}))},ZIs=["points","className","baseLinePoints","connectNulls"];function EI(){return EI=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function QIs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function DHe(s){return sPs(s)||tPs(s)||ePs(s)||JIs()}function JIs(){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 ePs(s,t){if(s){if(typeof s=="string")return F4e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return F4e(s,t)}}function tPs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function sPs(s){if(Array.isArray(s))return F4e(s)}function F4e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return t.forEach(function(n){RHe(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),RHe(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},q7=function(t,r){var n=rPs(t);r&&(n=[n.reduce(function(i,l){return[].concat(DHe(i),DHe(l))},[])]);var a=n.map(function(i){return i.reduce(function(l,o,c){return"".concat(l).concat(c===0?"M":"L").concat(o.x,",").concat(o.y)},"")}).join("");return n.length===1?"".concat(a,"Z"):a},nPs=function(t,r,n){var a=q7(t,n);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(q7(r.reverse(),n).slice(1))},aPs=function(t){var r=t.points,n=t.className,a=t.baseLinePoints,i=t.connectNulls,l=XIs(t,ZIs);if(!r||!r.length)return null;var o=_o("recharts-polygon",n);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=nPs(r,a,i);return Ct.createElement("g",{className:o},Ct.createElement("path",EI({},Li(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Ct.createElement("path",EI({},Li(l,!0),{fill:"none",d:q7(r,i)})):null,c?Ct.createElement("path",EI({},Li(l,!0),{fill:"none",d:q7(a,i)})):null)}var u=q7(r,i);return Ct.createElement("path",EI({},Li(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function z4e(){return z4e=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function hPs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var mPs=function(t,r,n,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(r,"h").concat(n)},fPs=function(t){var r=t.x,n=r===void 0?0:r,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,u=t.width,m=u===void 0?0:u,f=t.height,x=f===void 0?0:f,y=t.className,_=uPs(t,iPs),b=oPs({x:n,y:i,top:o,left:d,width:m,height:x},_);return!Jn(n)||!Jn(i)||!Jn(m)||!Jn(x)||!Jn(o)||!Jn(d)?null:Ct.createElement("path",B4e({},Li(b,!0),{className:_o("recharts-cross",y),d:mPs(n,i,m,x,o,d)}))},pPs=X0e,xPs=Vxt,gPs=cw;function yPs(s,t){return s&&s.length?pPs(s,gPs(t),xPs):void 0}var vPs=yPs;const bPs=gl(vPs);var _Ps=X0e,wPs=cw,jPs=Hxt;function NPs(s,t){return s&&s.length?_Ps(s,wPs(t),jPs):void 0}var kPs=NPs;const SPs=gl(kPs);var CPs=["cx","cy","angle","ticks","axisLine"],TPs=["ticks","tick","angle","tickFormatter","stroke"];function DL(s){"@babel/helpers - typeof";return DL=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},DL(s)}function V7(){return V7=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function EPs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function APs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function BHe(s,t){for(var r=0;rqHe?l=a==="outer"?"start":"end":i<-qHe?l=a==="outer"?"end":"start":l="middle",l}},{key:"renderAxisLine",value:function(){var n=this.props,a=n.cx,i=n.cy,l=n.radius,o=n.axisLine,c=n.axisLineType,d=yC(yC({},Li(this.props,!1)),{},{fill:"none"},Li(o,!1));if(c==="circle")return Ct.createElement(sye,VT({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,m=u.map(function(f){return od(a,i,l,f.coordinate)});return Ct.createElement(aPs,VT({className:"recharts-polar-angle-axis-line"},d,{points:m}))}},{key:"renderTicks",value:function(){var n=this,a=this.props,i=a.ticks,l=a.tick,o=a.tickLine,c=a.tickFormatter,d=a.stroke,u=Li(this.props,!1),m=Li(l,!1),f=yC(yC({},u),{},{fill:"none"},Li(o,!1)),x=i.map(function(y,_){var b=n.getTickLineCoord(y),j=n.getTickTextAnchor(y),N=yC(yC(yC({textAnchor:j},u),{},{stroke:"none",fill:d},m),{},{index:_,payload:y,x:b.x2,y:b.y2});return Ct.createElement(Bl,VT({className:_o("recharts-polar-angle-axis-tick",vgt(l)),key:"tick-".concat(y.coordinate)},PA(n.props,y,_)),o&&Ct.createElement("line",VT({className:"recharts-polar-angle-axis-tick-line"},f,b)),l&&t.renderTickItem(l,N,c?c(y.value,_):y.value))});return Ct.createElement(Bl,{className:"recharts-polar-angle-axis-ticks"},x)}},{key:"render",value:function(){var n=this.props,a=n.ticks,i=n.radius,l=n.axisLine;return i<=0||!a||!a.length?null:Ct.createElement(Bl,{className:_o("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,a,i){var l;return Ct.isValidElement(n)?l=Ct.cloneElement(n,a):oo(n)?l=n(a):l=Ct.createElement(LA,VT({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(k.PureComponent);aye(iye,"displayName","PolarAngleAxis");aye(iye,"axisType","angleAxis");aye(iye,"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 HPs=Bpt,GPs=HPs(Object.getPrototypeOf,Object),WPs=GPs,KPs=$2,YPs=WPs,ZPs=U2,XPs="[object Object]",QPs=Function.prototype,JPs=Object.prototype,Fgt=QPs.toString,eLs=JPs.hasOwnProperty,tLs=Fgt.call(Object);function sLs(s){if(!ZPs(s)||KPs(s)!=XPs)return!1;var t=YPs(s);if(t===null)return!0;var r=eLs.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&Fgt.call(r)==tLs}var rLs=sLs;const nLs=gl(rLs);var aLs=$2,iLs=U2,oLs="[object Boolean]";function lLs(s){return s===!0||s===!1||iLs(s)&&aLs(s)==oLs}var cLs=lLs;const dLs=gl(cLs);function kz(s){"@babel/helpers - typeof";return kz=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},kz(s)}function gpe(){return gpe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r0,from:{upperWidth:0,lowerWidth:0,height:f,x:c,y:d},to:{upperWidth:u,lowerWidth:m,height:f,x:c,y:d},duration:_,animationEasing:y,isActive:j},function(C){var A=C.upperWidth,E=C.lowerWidth,D=C.height,R=C.x,F=C.y;return Ct.createElement(G_,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:_,easing:y},Ct.createElement("path",gpe({},Li(r,!0),{className:N,d:WHe(R,F,A,E,D),ref:n})))}):Ct.createElement("g",null,Ct.createElement("path",gpe({},Li(r,!0),{className:N,d:WHe(c,d,u,m,f)})))},_Ls=["option","shapeType","propTransformer","activeClassName","isActive"];function Sz(s){"@babel/helpers - typeof";return Sz=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Sz(s)}function wLs(s,t){if(s==null)return{};var r=jLs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function jLs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function KHe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function ype(s){for(var t=1;t0?P0(C,"paddingAngle",0):0;if(E){var R=g0(E.endAngle-E.startAngle,C.endAngle-C.startAngle),F=sd(sd({},C),{},{startAngle:N+D,endAngle:N+R(_)+D});b.push(F),N=F.endAngle}else{var O=C.endAngle,B=C.startAngle,K=g0(0,O-B),Z=K(_),Q=sd(sd({},C),{},{startAngle:N+D,endAngle:N+Z+D});b.push(Q),N=Q.endAngle}}),Ct.createElement(Bl,null,n.renderSectorsStatically(b))})}},{key:"attachKeyboardHandlers",value:function(n){var a=this;n.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var l=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"ArrowRight":{var o=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,a=n.sectors,i=n.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!JB(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,m=a.innerRadius,f=a.outerRadius,x=a.isAnimationActive,y=this.state.isAnimationFinished;if(i||!l||!l.length||!Jn(d)||!Jn(u)||!Jn(m)||!Jn(f))return null;var _=_o("recharts-pie",o);return Ct.createElement(Bl,{tabIndex:this.props.rootTabIndex,className:_,ref:function(j){n.pieRef=j}},this.renderSectors(),c&&this.renderLabels(l),sf.renderCallByParent(this.props,null,!1),(!x||y)&&y2.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return a.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:n.sectors!==a.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,a){return n>a?"start":n=360?N:N-1)*c,A=b-N*x-C,E=a.reduce(function(F,O){var B=hm(O,j,0);return F+(Jn(B)?B:0)},0),D;if(E>0){var R;D=a.map(function(F,O){var B=hm(F,j,0),K=hm(F,u,O),Z=(Jn(B)?B:0)/E,Q;O?Q=R.endAngle+Nx(_)*c*(B!==0?1:0):Q=l;var W=Q+Nx(_)*((B!==0?x:0)+Z*A),te=(Q+W)/2,ne=(y.innerRadius+y.outerRadius)/2,ae=[{name:K,value:B,payload:F,dataKey:j,type:f}],ue=od(y.cx,y.cy,ne,te);return R=sd(sd(sd({percent:Z,cornerRadius:i,name:K,tooltipPayload:ae,midAngle:te,middleRadius:ne,tooltipPosition:ue},F),y),{},{value:hm(F,j),startAngle:Q,endAngle:W,payload:F,paddingAngle:Nx(_)*c}),R})}return sd(sd({},y),{},{sectors:D,data:a})});var VLs=Math.ceil,HLs=Math.max;function GLs(s,t,r,n){for(var a=-1,i=HLs(VLs((t-s)/(r||1)),0),l=Array(i);i--;)l[n?i:++a]=s,s+=r;return l}var WLs=GLs,KLs=axt,QHe=1/0,YLs=17976931348623157e292;function ZLs(s){if(!s)return s===0?s:0;if(s=KLs(s),s===QHe||s===-QHe){var t=s<0?-1:1;return t*YLs}return s===s?s:0}var Ugt=ZLs,XLs=WLs,QLs=V0e,Hwe=Ugt;function JLs(s){return function(t,r,n){return n&&typeof n!="number"&&QLs(t,r,n)&&(r=n=void 0),t=Hwe(t),r===void 0?(r=t,t=0):r=Hwe(r),n=n===void 0?t0&&n.handleDrag(a.changedTouches[0])}),l0(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var a=n.props,i=a.endIndex,l=a.onDragEnd,o=a.startIndex;l==null||l({endIndex:i,startIndex:o})}),n.detachDragEndListener()}),l0(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),l0(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),l0(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),l0(n,"handleSlideDragStart",function(a){var i=rGe(a)?a.changedTouches[0]:a;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:i.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return m8s(t,s),c8s(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var a=n.startX,i=n.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,m=Math.min(a,i),f=Math.max(a,i),x=t.getIndexInRange(l,m),y=t.getIndexInRange(l,f);return{startIndex:x-x%c,endIndex:y===u?u:y-y%c}}},{key:"getTextOfTick",value:function(n){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=hm(i[n],o,n);return oo(l)?l(c,n):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,m=c.travellerWidth,f=c.startIndex,x=c.endIndex,y=c.onChange,_=n.pageX-i;_>0?_=Math.min(_,d+u-m-o,d+u-m-l):_<0&&(_=Math.max(_,d-l,d-o));var b=this.getIndex({startX:l+_,endX:o+_});(b.startIndex!==f||b.endIndex!==x)&&y&&y(b),this.setState({startX:l+_,endX:o+_,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,a){var i=rGe(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,m=u.x,f=u.width,x=u.travellerWidth,y=u.onChange,_=u.gap,b=u.data,j={startX:this.state.startX,endX:this.state.endX},N=n.pageX-i;N>0?N=Math.min(N,m+f-x-d):N<0&&(N=Math.max(N,m-d)),j[l]=d+N;var C=this.getIndex(j),A=C.startIndex,E=C.endIndex,D=function(){var F=b.length-1;return l==="startX"&&(o>c?A%_===0:E%_===0)||oc?E%_===0:A%_===0)||o>c&&E===F};this.setState(l0(l0({},l,d+N),"brushMoveStartX",n.pageX),function(){y&&D()&&y(C)})}},{key:"handleTravellerMoveKeyboard",value:function(n,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,u=this.state[a],m=o.indexOf(u);if(m!==-1){var f=m+n;if(!(f===-1||f>=o.length)){var x=o[f];a==="startX"&&x>=d||a==="endX"&&x<=c||this.setState(l0({},a,x),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,a=n.x,i=n.y,l=n.width,o=n.height,c=n.fill,d=n.stroke;return Ct.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var n=this.props,a=n.x,i=n.y,l=n.width,o=n.height,c=n.data,d=n.children,u=n.padding,m=k.Children.only(d);return m?Ct.cloneElement(m,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(n,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,m=c.height,f=c.traveller,x=c.ariaLabel,y=c.data,_=c.startIndex,b=c.endIndex,j=Math.max(n,this.props.x),N=Gwe(Gwe({},Li(this.props,!1)),{},{x:j,y:d,width:u,height:m}),C=x||"Min value: ".concat((i=y[_])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=y[b])===null||l===void 0?void 0:l.name);return Ct.createElement(Bl,{tabIndex:0,role:"slider","aria-label":C,"aria-valuenow":n,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(f,N))}},{key:"renderSlide",value:function(n,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,u=Math.min(n,a)+d,m=Math.max(Math.abs(a-n)-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:m,height:o})}},{key:"renderText",value:function(){var n=this.props,a=n.startIndex,i=n.endIndex,l=n.y,o=n.height,c=n.travellerWidth,d=n.stroke,u=this.state,m=u.startX,f=u.endX,x=5,y={pointerEvents:"none",fill:d};return Ct.createElement(Bl,{className:"recharts-brush-texts"},Ct.createElement(LA,_pe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(m,f)-x,y:l+o/2},y),this.getTextOfTick(a)),Ct.createElement(LA,_pe({textAnchor:"start",verticalAnchor:"middle",x:Math.max(m,f)+c+x,y:l+o/2},y),this.getTextOfTick(i)))}},{key:"render",value:function(){var n=this.props,a=n.data,i=n.className,l=n.children,o=n.x,c=n.y,d=n.width,u=n.height,m=n.alwaysShowText,f=this.state,x=f.startX,y=f.endX,_=f.isTextActive,b=f.isSlideMoving,j=f.isTravellerMoving,N=f.isTravellerFocused;if(!a||!a.length||!Jn(o)||!Jn(c)||!Jn(d)||!Jn(u)||d<=0||u<=0)return null;var C=_o("recharts-brush",i),A=Ct.Children.count(l)===1,E=o8s("userSelect","none");return Ct.createElement(Bl,{className:C,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:E},this.renderBackground(),A&&this.renderPanorama(),this.renderSlide(x,y),this.renderTravellerLayer(x,"startX"),this.renderTravellerLayer(y,"endX"),(_||b||j||N||m)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var a=n.x,i=n.y,l=n.width,o=n.height,c=n.stroke,d=Math.floor(i+o/2)-1;return 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(n,a){var i;return Ct.isValidElement(n)?i=Ct.cloneElement(n,a):oo(n)?i=n(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(n,a){var i=n.data,l=n.width,o=n.x,c=n.travellerWidth,d=n.updateId,u=n.startIndex,m=n.endIndex;if(i!==a.prevData||d!==a.prevUpdateId)return Gwe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?p8s({data:i,width:l,x:o,travellerWidth:c,startIndex:u,endIndex:m}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var f=a.scale.domain().map(function(x){return a.scale(x)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(n.startIndex),endX:a.scale(n.endIndex),scaleValues:f}}return null}},{key:"getIndexInRange",value:function(n,a){for(var i=n.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);n[c]>a?o=c:l=c}return a>=n[o]?o:l}}])}(k.PureComponent);l0(zL,"displayName","Brush");l0(zL,"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 x8s=bMe;function g8s(s,t){var r;return x8s(s,function(n,a,i){return r=t(n,a,i),!r}),!!r}var y8s=g8s,v8s=Ipt,b8s=cw,_8s=y8s,w8s=Mg,j8s=V0e;function N8s(s,t,r){var n=w8s(s)?v8s:_8s;return r&&j8s(s,t,r)&&(t=void 0),n(s,b8s(t))}var k8s=N8s;const S8s=gl(k8s);var D_=function(t,r){var n=t.alwaysShow,a=t.ifOverflow;return n&&(a="extendDomain"),a===r},nGe=ext;function C8s(s,t,r){t=="__proto__"&&nGe?nGe(s,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):s[t]=r}var T8s=C8s,E8s=T8s,A8s=Qpt,M8s=cw;function I8s(s,t){var r={};return t=M8s(t),A8s(s,function(n,a,i){E8s(r,a,t(n,a,i))}),r}var P8s=I8s;const L8s=gl(P8s);function D8s(s,t){for(var r=-1,n=s==null?0:s.length;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Q8s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function J8s(s,t){var r=s.x,n=s.y,a=X8s(s,W8s),i="".concat(r),l=parseInt(i,10),o="".concat(n),c=parseInt(o,10),d="".concat(t.height||a.height),u=parseInt(d,10),m="".concat(t.width||a.width),f=parseInt(m,10);return uO(uO(uO(uO(uO({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:f,name:t.name,radius:t.radius})}function iGe(s){return Ct.createElement(zgt,H4e({shapeType:"rectangle",propTransformer:J8s,activeClassName:"recharts-active-bar"},s))}var eDs=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,a){if(typeof t=="number")return t;var i=Jn(n)||D1s(n);return i?t(n,a):(i||RA(),r)}},tDs=["value","background"],Wgt;function BL(s){"@babel/helpers - typeof";return BL=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},BL(s)}function sDs(s,t){if(s==null)return{};var r=rDs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function rDs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function jpe(){return jpe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(te)0&&Math.abs(W)0&&(Q=Math.min((Ee||0)-(W[Me-1]||0),Q))}),Number.isFinite(Q)){var te=Q/Z,ne=_.layout==="vertical"?n.height:n.width;if(_.padding==="gap"&&(R=te*ne/2),_.padding==="no-gap"){var ae=kx(t.barCategoryGap,te*ne),ue=te*ne/2;R=ue-ae-(ue-ae)/ne*ae}}}a==="xAxis"?F=[n.left+(C.left||0)+(R||0),n.left+n.width-(C.right||0)-(R||0)]:a==="yAxis"?F=c==="horizontal"?[n.top+n.height-(C.bottom||0),n.top+(C.top||0)]:[n.top+(C.top||0)+(R||0),n.top+n.height-(C.bottom||0)-(R||0)]:F=_.range,E&&(F=[F[1],F[0]]);var me=hgt(_,i,f),de=me.scale,fe=me.realScaleType;de.domain(j).range(F),mgt(de);var je=fgt(de,u1(u1({},_),{},{realScaleType:fe}));a==="xAxis"?(K=b==="top"&&!A||b==="bottom"&&A,O=n.left,B=m[D]-K*_.height):a==="yAxis"&&(K=b==="left"&&!A||b==="right"&&A,O=m[D]-K*_.width,B=n.top);var xe=u1(u1(u1({},_),je),{},{realScaleType:fe,x:O,y:B,scale:de,width:a==="xAxis"?n.width:_.width,height:a==="yAxis"?n.height:_.height});return xe.bandSize=ope(xe,je),!_.hide&&a==="xAxis"?m[D]+=(K?-1:1)*xe.height:_.hide||(m[D]+=(K?-1:1)*xe.width),u1(u1({},x),{},cye({},y,xe))},{})},Qgt=function(t,r){var n=t.x,a=t.y,i=r.x,l=r.y;return{x:Math.min(n,i),y:Math.min(a,l),width:Math.abs(i-n),height:Math.abs(l-a)}},fDs=function(t){var r=t.x1,n=t.y1,a=t.x2,i=t.y2;return Qgt({x:r,y:n},{x:a,y:i})},Jgt=function(){function s(t){uDs(this,s),this.scale=t}return hDs(s,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=n.bandAware,i=n.position;if(r!==void 0){if(i)switch(i){case"start":return this.scale(r);case"middle":{var l=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+l}case"end":{var o=this.bandwidth?this.bandwidth():0;return this.scale(r)+o}default:return this.scale(r)}if(a){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),a=n[0],i=n[n.length-1];return a<=i?r>=a&&r<=i:r>=i&&r<=a}}],[{key:"create",value:function(r){return new s(r)}}])}();cye(Jgt,"EPS",1e-4);var YMe=function(t){var r=Object.keys(t).reduce(function(n,a){return u1(u1({},n),{},cye({},a,Jgt.create(t[a])))},{});return u1(u1({},r),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return L8s(a,function(c,d){return r[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return Ggt(a,function(i,l){return r[l].isInRange(i)})}})};function pDs(s){return(s%180+180)%180}var xDs=function(t){var r=t.width,n=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=pDs(a),l=i*Math.PI/180,o=Math.atan(n/r),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var _Ds=bDs,wDs=Ugt;function jDs(s){var t=wDs(s),r=t%1;return t===t?r?t-r:t:0}var NDs=jDs,kDs=Gpt,SDs=cw,CDs=NDs,TDs=Math.max;function EDs(s,t,r){var n=s==null?0:s.length;if(!n)return-1;var a=r==null?0:CDs(r);return a<0&&(a=TDs(n+a,0)),kDs(s,SDs(t),a)}var ADs=EDs,MDs=_Ds,IDs=ADs,PDs=MDs(IDs),LDs=PDs;const DDs=gl(LDs);var RDs=zvs(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("")}),ZMe=k.createContext(void 0),XMe=k.createContext(void 0),e0t=k.createContext(void 0),t0t=k.createContext({}),s0t=k.createContext(void 0),r0t=k.createContext(0),n0t=k.createContext(0),uGe=function(t){var r=t.state,n=r.xAxisMap,a=r.yAxisMap,i=r.offset,l=t.clipPathId,o=t.children,c=t.width,d=t.height,u=RDs(i);return Ct.createElement(ZMe.Provider,{value:n},Ct.createElement(XMe.Provider,{value:a},Ct.createElement(t0t.Provider,{value:i},Ct.createElement(e0t.Provider,{value:u},Ct.createElement(s0t.Provider,{value:l},Ct.createElement(r0t.Provider,{value:d},Ct.createElement(n0t.Provider,{value:c},o)))))))},ODs=function(){return k.useContext(s0t)},a0t=function(t){var r=k.useContext(ZMe);r==null&&RA();var n=r[t];return n==null&&RA(),n},FDs=function(){var t=k.useContext(ZMe);return wk(t)},zDs=function(){var t=k.useContext(XMe),r=DDs(t,function(n){return Ggt(n.domain,Number.isFinite)});return r||wk(t)},i0t=function(t){var r=k.useContext(XMe);r==null&&RA();var n=r[t];return n==null&&RA(),n},BDs=function(){var t=k.useContext(e0t);return t},$Ds=function(){return k.useContext(t0t)},QMe=function(){return k.useContext(n0t)},JMe=function(){return k.useContext(r0t)};function $L(s){"@babel/helpers - typeof";return $L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$L(s)}function UDs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function qDs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);rs*a)return!1;var i=r();return s*(t-s*i/2-n)>=0&&s*(t+s*i/2-a)<=0}function NRs(s,t){return m0t(s,t+1)}function kRs(s,t,r,n,a){for(var i=(n||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,m=function(){var y=n==null?void 0:n[c];if(y===void 0)return{v:m0t(n,d)};var _=c,b,j=function(){return b===void 0&&(b=r(y,_)),b},N=y.coordinate,C=c===0||Tpe(s,N,j,u,o);C||(c=0,u=l,d+=1),C&&(u=N+s*(j()/2+a),c+=d)},f;d<=i.length;)if(f=m(),f)return f.v;return[]}function Mz(s){"@babel/helpers - typeof";return Mz=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Mz(s)}function vGe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function wp(s){for(var t=1;t0?x.coordinate-b*s:x.coordinate})}else i[f]=x=wp(wp({},x),{},{tickCoord:x.coordinate});var j=Tpe(s,x.tickCoord,_,o,c);j&&(c=x.tickCoord-s*(_()/2+a),i[f]=wp(wp({},x),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function ARs(s,t,r,n,a,i){var l=(n||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var u=n[o-1],m=r(u,o-1),f=s*(u.coordinate+s*m/2-d);l[o-1]=u=wp(wp({},u),{},{tickCoord:f>0?u.coordinate-f*s:u.coordinate});var x=Tpe(s,u.tickCoord,function(){return m},c,d);x&&(d=u.tickCoord-s*(m/2+a),l[o-1]=wp(wp({},u),{},{isShow:!0}))}for(var y=i?o-1:o,_=function(N){var C=l[N],A,E=function(){return A===void 0&&(A=r(C,N)),A};if(N===0){var D=s*(C.coordinate-s*E()/2-c);l[N]=C=wp(wp({},C),{},{tickCoord:D<0?C.coordinate-D*s:C.coordinate})}else l[N]=C=wp(wp({},C),{},{tickCoord:C.coordinate});var R=Tpe(s,C.tickCoord,E,c,d);R&&(c=C.tickCoord+s*(E()/2+a),l[N]=wp(wp({},C),{},{isShow:!0}))},b=0;b=2?Nx(a[1].coordinate-a[0].coordinate):1,j=jRs(i,b,x);return c==="equidistantPreserveStart"?kRs(b,j,_,a,l):(c==="preserveStart"||c==="preserveStartEnd"?f=ARs(b,j,_,a,l,c==="preserveStartEnd"):f=ERs(b,j,_,a,l),f.filter(function(N){return N.isShow}))}var MRs=["viewBox"],IRs=["viewBox"],PRs=["ticks"];function VL(s){"@babel/helpers - typeof";return VL=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},VL(s)}function MI(){return MI=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function LRs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function DRs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function _Ge(s,t){for(var r=0;r0?c(this.props):c(x)),l<=0||o<=0||!y||!y.length?null:Ct.createElement(Bl,{className:_o("recharts-cartesian-axis",d),ref:function(b){n.layerReference=b}},i&&this.renderAxisLine(),this.renderTicks(y,this.state.fontSize,this.state.letterSpacing),sf.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,a,i){var l,o=_o(a.className,"recharts-cartesian-axis-tick-value");return Ct.isValidElement(n)?l=Ct.cloneElement(n,tm(tm({},a),{},{className:o})):oo(n)?l=n(tm(tm({},a),{},{className:o})):l=Ct.createElement(LA,MI({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(k.Component);r6e(eD,"displayName","CartesianAxis");r6e(eD,"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 URs=["x1","y1","x2","y2","key"],qRs=["offset"];function OA(s){"@babel/helpers - typeof";return OA=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},OA(s)}function wGe(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function kp(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function WRs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var KRs=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return Ct.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function x0t(s,t){var r;if(Ct.isValidElement(s))r=Ct.cloneElement(s,t);else if(oo(s))r=s(t);else{var n=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=jGe(t,URs),d=Li(c,!1);d.offset;var u=jGe(d,qRs);r=Ct.createElement("line",oE({},u,{x1:n,y1:a,x2:i,y2:l,fill:"none",key:o}))}return r}function YRs(s){var t=s.x,r=s.width,n=s.horizontal,a=n===void 0?!0:n,i=s.horizontalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=kp(kp({},s),{},{x1:t,y1:o,x2:t+r,y2:o,key:"line-".concat(c),index:c});return x0t(a,d)});return Ct.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function ZRs(s){var t=s.y,r=s.height,n=s.vertical,a=n===void 0?!0:n,i=s.verticalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=kp(kp({},s),{},{x1:o,y1:t,x2:o,y2:t+r,key:"line-".concat(c),index:c});return x0t(a,d)});return Ct.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function XRs(s){var t=s.horizontalFill,r=s.fillOpacity,n=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(f){return Math.round(f+a-a)}).sort(function(f,x){return f-x});a!==u[0]&&u.unshift(0);var m=u.map(function(f,x){var y=!u[x+1],_=y?a+l-f:u[x+1]-f;if(_<=0)return null;var b=x%t.length;return Ct.createElement("rect",{key:"react-".concat(x),y:f,x:n,height:_,width:i,stroke:"none",fill:t[b],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return Ct.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},m)}function QRs(s){var t=s.vertical,r=t===void 0?!0:t,n=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!r||!n||!n.length)return null;var u=d.map(function(f){return Math.round(f+i-i)}).sort(function(f,x){return f-x});i!==u[0]&&u.unshift(0);var m=u.map(function(f,x){var y=!u[x+1],_=y?i+o-f:u[x+1]-f;if(_<=0)return null;var b=x%n.length;return Ct.createElement("rect",{key:"react-".concat(x),x:f,y:l,width:_,height:c,stroke:"none",fill:n[b],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Ct.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},m)}var JRs=function(t,r){var n=t.xAxis,a=t.width,i=t.height,l=t.offset;return ugt(s6e(kp(kp(kp({},eD.defaultProps),n),{},{ticks:Xj(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,r)},eOs=function(t,r){var n=t.yAxis,a=t.width,i=t.height,l=t.offset;return ugt(s6e(kp(kp(kp({},eD.defaultProps),n),{},{ticks:Xj(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,r)},F6={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function g0t(s){var t,r,n,a,i,l,o=QMe(),c=JMe(),d=$Ds(),u=kp(kp({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:F6.stroke,fill:(r=s.fill)!==null&&r!==void 0?r:F6.fill,horizontal:(n=s.horizontal)!==null&&n!==void 0?n:F6.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:F6.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:F6.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:F6.verticalFill,x:Jn(s.x)?s.x:d.left,y:Jn(s.y)?s.y:d.top,width:Jn(s.width)?s.width:d.width,height:Jn(s.height)?s.height:d.height}),m=u.x,f=u.y,x=u.width,y=u.height,_=u.syncWithTicks,b=u.horizontalValues,j=u.verticalValues,N=FDs(),C=zDs();if(!Jn(x)||x<=0||!Jn(y)||y<=0||!Jn(m)||m!==+m||!Jn(f)||f!==+f)return null;var A=u.verticalCoordinatesGenerator||JRs,E=u.horizontalCoordinatesGenerator||eOs,D=u.horizontalPoints,R=u.verticalPoints;if((!D||!D.length)&&oo(E)){var F=b&&b.length,O=E({yAxis:C?kp(kp({},C),{},{ticks:F?b:C.ticks}):void 0,width:o,height:c,offset:d},F?!0:_);P1(Array.isArray(O),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(OA(O),"]")),Array.isArray(O)&&(D=O)}if((!R||!R.length)&&oo(A)){var B=j&&j.length,K=A({xAxis:N?kp(kp({},N),{},{ticks:B?j:N.ticks}):void 0,width:o,height:c,offset:d},B?!0:_);P1(Array.isArray(K),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(OA(K),"]")),Array.isArray(K)&&(R=K)}return Ct.createElement("g",{className:"recharts-cartesian-grid"},Ct.createElement(KRs,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Ct.createElement(YRs,oE({},u,{offset:d,horizontalPoints:D,xAxis:N,yAxis:C})),Ct.createElement(ZRs,oE({},u,{offset:d,verticalPoints:R,xAxis:N,yAxis:C})),Ct.createElement(XRs,oE({},u,{horizontalPoints:D})),Ct.createElement(QRs,oE({},u,{verticalPoints:R})))}g0t.displayName="CartesianGrid";var tOs=["type","layout","connectNulls","ref"],sOs=["key"];function HL(s){"@babel/helpers - typeof";return HL=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},HL(s)}function NGe(s,t){if(s==null)return{};var r=rOs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function rOs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function H7(){return H7=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);rm){x=[].concat(z6(c.slice(0,y)),[m-_]);break}var b=x.length%2===0?[0,f]:[f];return[].concat(z6(t.repeat(c,u)),z6(x),b).map(function(j){return"".concat(j,"px")}).join(", ")}),h1(r,"id",G8("recharts-line-")),h1(r,"pathRef",function(l){r.mainCurve=l}),h1(r,"handleAnimationEnd",function(){r.setState({isAnimationFinished:!0}),r.props.onAnimationEnd&&r.props.onAnimationEnd()}),h1(r,"handleAnimationStart",function(){r.setState({isAnimationFinished:!1}),r.props.onAnimationStart&&r.props.onAnimationStart()}),r}return mOs(t,s),cOs(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();this.setState({totalLength:n})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();n!==this.state.totalLength&&this.setState({totalLength:n})}}},{key:"getTotalLength",value:function(){var n=this.mainCurve;try{return n&&n.getTotalLength&&n.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(n,a){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,l=i.points,o=i.xAxis,c=i.yAxis,d=i.layout,u=i.children,m=L0(u,e$);if(!m)return null;var f=function(_,b){return{x:_.x,y:_.y,value:_.value,errorVal:hm(_.payload,b)}},x={clipPath:n?"url(#clipPath-".concat(a,")"):null};return Ct.createElement(Bl,x,m.map(function(y){return Ct.cloneElement(y,{key:"bar-".concat(y.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:f})}))}},{key:"renderDots",value:function(n,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,m=Li(this.props,!1),f=Li(c,!0),x=d.map(function(_,b){var j=a0(a0(a0({key:"dot-".concat(b),r:3},m),f),{},{index:b,cx:_.x,cy:_.y,value:_.value,dataKey:u,payload:_.payload,points:d});return t.renderDotItem(c,j)}),y={clipPath:n?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Ct.createElement(Bl,H7({className:"recharts-line-dots",key:"dots"},y),x)}},{key:"renderCurveStatically",value:function(n,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var m=NGe(o,tOs),f=a0(a0(a0({},Li(m,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:n},l),{},{type:c,layout:d,connectNulls:u});return Ct.createElement(dpe,H7({},f,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(n,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,m=l.animationDuration,f=l.animationEasing,x=l.animationId,y=l.animateNewValues,_=l.width,b=l.height,j=this.state,N=j.prevPoints,C=j.totalLength;return Ct.createElement(G_,{begin:u,duration:m,isActive:d,easing:f,from:{t:0},to:{t:1},key:"line-".concat(x),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(A){var E=A.t;if(N){var D=N.length/o.length,R=o.map(function(Z,Q){var W=Math.floor(Q*D);if(N[W]){var te=N[W],ne=g0(te.x,Z.x),ae=g0(te.y,Z.y);return a0(a0({},Z),{},{x:ne(E),y:ae(E)})}if(y){var ue=g0(_*2,Z.x),me=g0(b/2,Z.y);return a0(a0({},Z),{},{x:ue(E),y:me(E)})}return a0(a0({},Z),{},{x:Z.x,y:Z.y})});return i.renderCurveStatically(R,n,a)}var F=g0(0,C),O=F(E),B;if(c){var K="".concat(c).split(/[,\s]+/gim).map(function(Z){return parseFloat(Z)});B=i.getStrokeDasharray(O,C,K)}else B=i.generateSimpleStrokeDasharray(C,O);return i.renderCurveStatically(o,n,a,{strokeDasharray:B})})}},{key:"renderCurve",value:function(n,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||!JB(d,l))?this.renderCurveWithAnimation(n,a):this.renderCurveStatically(l,n,a)}},{key:"render",value:function(){var n,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,m=a.top,f=a.left,x=a.width,y=a.height,_=a.isAnimationActive,b=a.id;if(i||!o||!o.length)return null;var j=this.state.isAnimationFinished,N=o.length===1,C=_o("recharts-line",c),A=d&&d.allowDataOverflow,E=u&&u.allowDataOverflow,D=A||E,R=yo(b)?this.id:b,F=(n=Li(l,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},O=F.r,B=O===void 0?3:O,K=F.strokeWidth,Z=K===void 0?2:K,Q=W1s(l)?l:{},W=Q.clipDot,te=W===void 0?!0:W,ne=B*2+Z;return Ct.createElement(Bl,{className:C},A||E?Ct.createElement("defs",null,Ct.createElement("clipPath",{id:"clipPath-".concat(R)},Ct.createElement("rect",{x:A?f:f-x/2,y:E?m:m-y/2,width:A?x:x*2,height:E?y:y*2})),!te&&Ct.createElement("clipPath",{id:"clipPath-dots-".concat(R)},Ct.createElement("rect",{x:f-ne/2,y:m-ne/2,width:x+ne,height:y+ne}))):null,!N&&this.renderCurve(D,R),this.renderErrorBar(D,R),(N||l)&&this.renderDots(D,te,R),(!_||j)&&y2.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,prevPoints:a.curPoints}:n.points!==a.curPoints?{curPoints:n.points}:null}},{key:"repeat",value:function(n,a){for(var i=n.length%2!==0?[].concat(z6(n),[0]):n,l=[],o=0;os.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function sFs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function rFs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function nFs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r0?l:t&&t.length&&Jn(a)&&Jn(i)?t.slice(a,i+1):[]};function P0t(s){return s==="number"?[0,"auto"]:void 0}var dCe=function(t,r,n,a){var i=t.graphicalItems,l=t.tooltipAxis,o=fye(r,t);return n<0||!i||!i.length||n>=o.length?null:i.reduce(function(c,d){var u,m=(u=d.props.data)!==null&&u!==void 0?u:r;m&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(m=m.slice(t.dataStartIndex,t.dataEndIndex+1));var f;if(l.dataKey&&!l.allowDuplicatedCategory){var x=m===void 0?o:m;f=Pfe(x,l.dataKey,a)}else f=m&&m[n]||o[n];return f?[].concat(YL(c),[xgt(d,f)]):c},[])},IGe=function(t,r,n,a){var i=a||{x:t.chartX,y:t.chartY},l=xFs(i,n),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=KAs(l,o,d,c);if(u>=0&&d){var m=d[u]&&d[u].value,f=dCe(t,r,u,m),x=gFs(n,o,u,i);return{activeTooltipIndex:u,activeLabel:m,activePayload:f,activeCoordinate:x}}return null},yFs=function(t,r){var n=r.axes,a=r.graphicalItems,i=r.axisType,l=r.axisIdKey,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,u=t.layout,m=t.children,f=t.stackOffset,x=dgt(u,i);return n.reduce(function(y,_){var b,j=_.type.defaultProps!==void 0?sn(sn({},_.type.defaultProps),_.props):_.props,N=j.type,C=j.dataKey,A=j.allowDataOverflow,E=j.allowDuplicatedCategory,D=j.scale,R=j.ticks,F=j.includeHidden,O=j[l];if(y[O])return y;var B=fye(t.data,{graphicalItems:a.filter(function(je){var xe,Ee=l in je.props?je.props[l]:(xe=je.type.defaultProps)===null||xe===void 0?void 0:xe[l];return Ee===O}),dataStartIndex:c,dataEndIndex:d}),K=B.length,Z,Q,W;VOs(j.domain,A,N)&&(Z=N4e(j.domain,null,A),x&&(N==="number"||D!=="auto")&&(W=$7(B,C,"category")));var te=P0t(N);if(!Z||Z.length===0){var ne,ae=(ne=j.domain)!==null&&ne!==void 0?ne:te;if(C){if(Z=$7(B,C,N),N==="category"&&x){var ue=O1s(Z);E&&ue?(Q=Z,Z=bpe(0,K)):E||(Z=eHe(ae,Z,_).reduce(function(je,xe){return je.indexOf(xe)>=0?je:[].concat(YL(je),[xe])},[]))}else if(N==="category")E?Z=Z.filter(function(je){return je!==""&&!yo(je)}):Z=eHe(ae,Z,_).reduce(function(je,xe){return je.indexOf(xe)>=0||xe===""||yo(xe)?je:[].concat(YL(je),[xe])},[]);else if(N==="number"){var me=JAs(B,a.filter(function(je){var xe,Ee,Me=l in je.props?je.props[l]:(xe=je.type.defaultProps)===null||xe===void 0?void 0:xe[l],Oe="hide"in je.props?je.props.hide:(Ee=je.type.defaultProps)===null||Ee===void 0?void 0:Ee.hide;return Me===O&&(F||!Oe)}),C,i,u);me&&(Z=me)}x&&(N==="number"||D!=="auto")&&(W=$7(B,C,"category"))}else x?Z=bpe(0,K):o&&o[O]&&o[O].hasStack&&N==="number"?Z=f==="expand"?[0,1]:pgt(o[O].stackGroups,c,d):Z=cgt(B,a.filter(function(je){var xe=l in je.props?je.props[l]:je.type.defaultProps[l],Ee="hide"in je.props?je.props.hide:je.type.defaultProps.hide;return xe===O&&(F||!Ee)}),N,u,!0);if(N==="number")Z=oCe(m,Z,O,i,R),ae&&(Z=N4e(ae,Z,A));else if(N==="category"&&ae){var de=ae,fe=Z.every(function(je){return de.indexOf(je)>=0});fe&&(Z=de)}}return sn(sn({},y),{},Ki({},O,sn(sn({},j),{},{axisType:i,domain:Z,categoricalDomain:W,duplicateDomain:Q,originalDomain:(b=j.domain)!==null&&b!==void 0?b:te,isCategorical:x,layout:u})))},{})},vFs=function(t,r){var n=r.graphicalItems,a=r.Axis,i=r.axisType,l=r.axisIdKey,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,u=t.layout,m=t.children,f=fye(t.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:d}),x=f.length,y=dgt(u,i),_=-1;return n.reduce(function(b,j){var N=j.type.defaultProps!==void 0?sn(sn({},j.type.defaultProps),j.props):j.props,C=N[l],A=P0t("number");if(!b[C]){_++;var E;return y?E=bpe(0,x):o&&o[C]&&o[C].hasStack?(E=pgt(o[C].stackGroups,c,d),E=oCe(m,E,C,i)):(E=N4e(A,cgt(f,n.filter(function(D){var R,F,O=l in D.props?D.props[l]:(R=D.type.defaultProps)===null||R===void 0?void 0:R[l],B="hide"in D.props?D.props.hide:(F=D.type.defaultProps)===null||F===void 0?void 0:F.hide;return O===C&&!B}),"number",u),a.defaultProps.allowDataOverflow),E=oCe(m,E,C,i)),sn(sn({},b),{},Ki({},C,sn(sn({axisType:i},a.defaultProps),{},{hide:!0,orientation:P0(fFs,"".concat(i,".").concat(_%2),null),domain:E,originalDomain:A,isCategorical:y,layout:u})))}return b},{})},bFs=function(t,r){var n=r.axisType,a=n===void 0?"xAxis":n,i=r.AxisComp,l=r.graphicalItems,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,u=t.children,m="".concat(a,"Id"),f=L0(u,i),x={};return f&&f.length?x=yFs(t,{axes:f,graphicalItems:l,axisType:a,axisIdKey:m,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(x=vFs(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:m,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),x},_Fs=function(t){var r=wk(t),n=Xj(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:_Me(n,function(a){return a.coordinate}),tooltipAxis:r,tooltipAxisBandSize:ope(r,n)}},PGe=function(t){var r=t.children,n=t.defaultShowTooltip,a=h0(r,zL),i=0,l=0;return t.data&&t.data.length!==0&&(l=t.data.length-1),a&&a.props&&(a.props.startIndex>=0&&(i=a.props.startIndex),a.props.endIndex>=0&&(l=a.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:i,dataEndIndex:l,activeTooltipIndex:-1,isTooltipActive:!!n}},wFs=function(t){return!t||!t.length?!1:t.some(function(r){var n=x2(r&&r.type);return n&&n.indexOf("Bar")>=0})},LGe=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"}},jFs=function(t,r){var n=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=n.width,u=n.height,m=n.children,f=n.margin||{},x=h0(m,zL),y=h0(m,EP),_=Object.keys(c).reduce(function(E,D){var R=c[D],F=R.orientation;return!R.mirror&&!R.hide?sn(sn({},E),{},Ki({},F,E[F]+R.width)):E},{left:f.left||0,right:f.right||0}),b=Object.keys(l).reduce(function(E,D){var R=l[D],F=R.orientation;return!R.mirror&&!R.hide?sn(sn({},E),{},Ki({},F,P0(E,"".concat(F))+R.height)):E},{top:f.top||0,bottom:f.bottom||0}),j=sn(sn({},b),_),N=j.bottom;x&&(j.bottom+=x.props.height||zL.defaultProps.height),y&&r&&(j=XAs(j,a,n,r));var C=d-j.left-j.right,A=u-j.top-j.bottom;return sn(sn({brushBottom:N},j),{},{width:Math.max(C,0),height:Math.max(A,0)})},NFs=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},n6e=function(t){var r=t.chartName,n=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,u=t.formatAxisMap,m=t.defaultProps,f=function(j,N){var C=N.graphicalItems,A=N.stackGroups,E=N.offset,D=N.updateId,R=N.dataStartIndex,F=N.dataEndIndex,O=j.barSize,B=j.layout,K=j.barGap,Z=j.barCategoryGap,Q=j.maxBarSize,W=LGe(B),te=W.numericAxisName,ne=W.cateAxisName,ae=wFs(C),ue=[];return C.forEach(function(me,de){var fe=fye(j.data,{graphicalItems:[me],dataStartIndex:R,dataEndIndex:F}),je=me.type.defaultProps!==void 0?sn(sn({},me.type.defaultProps),me.props):me.props,xe=je.dataKey,Ee=je.maxBarSize,Me=je["".concat(te,"Id")],Oe=je["".concat(ne,"Id")],Ie={},ze=c.reduce(function(et,Ze){var rt=N["".concat(Ze.axisType,"Map")],ct=je["".concat(Ze.axisType,"Id")];rt&&rt[ct]||Ze.axisType==="zAxis"||RA();var vt=rt[ct];return sn(sn({},et),{},Ki(Ki({},Ze.axisType,vt),"".concat(Ze.axisType,"Ticks"),Xj(vt)))},Ie),Ve=ze[ne],Le=ze["".concat(ne,"Ticks")],$e=A&&A[Me]&&A[Me].hasStack&&lMs(me,A[Me].stackGroups),ve=x2(me.type).indexOf("Bar")>=0,Qe=ope(Ve,Le),we=[],nt=ae&&YAs({barSize:O,stackGroups:A,totalSize:NFs(ze,ne)});if(ve){var Se,Ge,We=yo(Ee)?Q:Ee,Ce=(Se=(Ge=ope(Ve,Le,!0))!==null&&Ge!==void 0?Ge:We)!==null&&Se!==void 0?Se:0;we=ZAs({barGap:K,barCategoryGap:Z,bandSize:Ce!==Qe?Ce:Qe,sizeList:nt[Oe],maxBarSize:We}),Ce!==Qe&&(we=we.map(function(et){return sn(sn({},et),{},{position:sn(sn({},et.position),{},{offset:et.position.offset-Ce/2})})}))}var qe=me&&me.type&&me.type.getComposedData;qe&&ue.push({props:sn(sn({},qe(sn(sn({},ze),{},{displayedData:fe,props:j,dataKey:xe,item:me,bandSize:Qe,barPosition:we,offset:E,stackedData:$e,layout:B,dataStartIndex:R,dataEndIndex:F}))),{},Ki(Ki(Ki({key:me.key||"item-".concat(de)},te,ze[te]),ne,ze[ne]),"animationId",D)),childIndex:Z1s(me,j.children),item:me})}),ue},x=function(j,N){var C=j.props,A=j.dataStartIndex,E=j.dataEndIndex,D=j.updateId;if(!WUe({props:C}))return null;var R=C.children,F=C.layout,O=C.stackOffset,B=C.data,K=C.reverseStackOrder,Z=LGe(F),Q=Z.numericAxisName,W=Z.cateAxisName,te=L0(R,n),ne=iMs(B,te,"".concat(Q,"Id"),"".concat(W,"Id"),O,K),ae=c.reduce(function(je,xe){var Ee="".concat(xe.axisType,"Map");return sn(sn({},je),{},Ki({},Ee,bFs(C,sn(sn({},xe),{},{graphicalItems:te,stackGroups:xe.axisType===Q&&ne,dataStartIndex:A,dataEndIndex:E}))))},{}),ue=jFs(sn(sn({},ae),{},{props:C,graphicalItems:te}),N==null?void 0:N.legendBBox);Object.keys(ae).forEach(function(je){ae[je]=u(C,ae[je],ue,je.replace("Map",""),r)});var me=ae["".concat(W,"Map")],de=_Fs(me),fe=f(C,sn(sn({},ae),{},{dataStartIndex:A,dataEndIndex:E,updateId:D,graphicalItems:te,stackGroups:ne,offset:ue}));return sn(sn({formattedGraphicalItems:fe,graphicalItems:te,offset:ue,stackGroups:ne},de),ae)},y=function(b){function j(N){var C,A,E;return rFs(this,j),E=iFs(this,j,[N]),Ki(E,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Ki(E,"accessibilityManager",new qOs),Ki(E,"handleLegendBBoxUpdate",function(D){if(D){var R=E.state,F=R.dataStartIndex,O=R.dataEndIndex,B=R.updateId;E.setState(sn({legendBBox:D},x({props:E.props,dataStartIndex:F,dataEndIndex:O,updateId:B},sn(sn({},E.state),{},{legendBBox:D}))))}}),Ki(E,"handleReceiveSyncEvent",function(D,R,F){if(E.props.syncId===D){if(F===E.eventEmitterSymbol&&typeof E.props.syncMethod!="function")return;E.applySyncEvent(R)}}),Ki(E,"handleBrushChange",function(D){var R=D.startIndex,F=D.endIndex;if(R!==E.state.dataStartIndex||F!==E.state.dataEndIndex){var O=E.state.updateId;E.setState(function(){return sn({dataStartIndex:R,dataEndIndex:F},x({props:E.props,dataStartIndex:R,dataEndIndex:F,updateId:O},E.state))}),E.triggerSyncEvent({dataStartIndex:R,dataEndIndex:F})}}),Ki(E,"handleMouseEnter",function(D){var R=E.getMouseInfo(D);if(R){var F=sn(sn({},R),{},{isTooltipActive:!0});E.setState(F),E.triggerSyncEvent(F);var O=E.props.onMouseEnter;oo(O)&&O(F,D)}}),Ki(E,"triggeredAfterMouseMove",function(D){var R=E.getMouseInfo(D),F=R?sn(sn({},R),{},{isTooltipActive:!0}):{isTooltipActive:!1};E.setState(F),E.triggerSyncEvent(F);var O=E.props.onMouseMove;oo(O)&&O(F,D)}),Ki(E,"handleItemMouseEnter",function(D){E.setState(function(){return{isTooltipActive:!0,activeItem:D,activePayload:D.tooltipPayload,activeCoordinate:D.tooltipPosition||{x:D.cx,y:D.cy}}})}),Ki(E,"handleItemMouseLeave",function(){E.setState(function(){return{isTooltipActive:!1}})}),Ki(E,"handleMouseMove",function(D){D.persist(),E.throttleTriggeredAfterMouseMove(D)}),Ki(E,"handleMouseLeave",function(D){E.throttleTriggeredAfterMouseMove.cancel();var R={isTooltipActive:!1};E.setState(R),E.triggerSyncEvent(R);var F=E.props.onMouseLeave;oo(F)&&F(R,D)}),Ki(E,"handleOuterEvent",function(D){var R=Y1s(D),F=P0(E.props,"".concat(R));if(R&&oo(F)){var O,B;/.*touch.*/i.test(R)?B=E.getMouseInfo(D.changedTouches[0]):B=E.getMouseInfo(D),F((O=B)!==null&&O!==void 0?O:{},D)}}),Ki(E,"handleClick",function(D){var R=E.getMouseInfo(D);if(R){var F=sn(sn({},R),{},{isTooltipActive:!0});E.setState(F),E.triggerSyncEvent(F);var O=E.props.onClick;oo(O)&&O(F,D)}}),Ki(E,"handleMouseDown",function(D){var R=E.props.onMouseDown;if(oo(R)){var F=E.getMouseInfo(D);R(F,D)}}),Ki(E,"handleMouseUp",function(D){var R=E.props.onMouseUp;if(oo(R)){var F=E.getMouseInfo(D);R(F,D)}}),Ki(E,"handleTouchMove",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&E.throttleTriggeredAfterMouseMove(D.changedTouches[0])}),Ki(E,"handleTouchStart",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&E.handleMouseDown(D.changedTouches[0])}),Ki(E,"handleTouchEnd",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&E.handleMouseUp(D.changedTouches[0])}),Ki(E,"handleDoubleClick",function(D){var R=E.props.onDoubleClick;if(oo(R)){var F=E.getMouseInfo(D);R(F,D)}}),Ki(E,"handleContextMenu",function(D){var R=E.props.onContextMenu;if(oo(R)){var F=E.getMouseInfo(D);R(F,D)}}),Ki(E,"triggerSyncEvent",function(D){E.props.syncId!==void 0&&Kwe.emit(Ywe,E.props.syncId,D,E.eventEmitterSymbol)}),Ki(E,"applySyncEvent",function(D){var R=E.props,F=R.layout,O=R.syncMethod,B=E.state.updateId,K=D.dataStartIndex,Z=D.dataEndIndex;if(D.dataStartIndex!==void 0||D.dataEndIndex!==void 0)E.setState(sn({dataStartIndex:K,dataEndIndex:Z},x({props:E.props,dataStartIndex:K,dataEndIndex:Z,updateId:B},E.state)));else if(D.activeTooltipIndex!==void 0){var Q=D.chartX,W=D.chartY,te=D.activeTooltipIndex,ne=E.state,ae=ne.offset,ue=ne.tooltipTicks;if(!ae)return;if(typeof O=="function")te=O(ue,D);else if(O==="value"){te=-1;for(var me=0;me=0){var $e,ve;if(Q.dataKey&&!Q.allowDuplicatedCategory){var Qe=typeof Q.dataKey=="function"?Le:"payload.".concat(Q.dataKey.toString());$e=Pfe(me,Qe,te),ve=de&&fe&&Pfe(fe,Qe,te)}else $e=me==null?void 0:me[W],ve=de&&fe&&fe[W];if(Oe||Me){var we=D.props.activeIndex!==void 0?D.props.activeIndex:W;return[k.cloneElement(D,sn(sn(sn({},O.props),ze),{},{activeIndex:we})),null,null]}if(!yo($e))return[Ve].concat(YL(E.renderActivePoints({item:O,activePoint:$e,basePoint:ve,childIndex:W,isRange:de})))}else{var nt,Se=(nt=E.getItemByXY(E.state.activeCoordinate))!==null&&nt!==void 0?nt:{graphicalItem:Ve},Ge=Se.graphicalItem,We=Ge.item,Ce=We===void 0?D:We,qe=Ge.childIndex,et=sn(sn(sn({},O.props),ze),{},{activeIndex:qe});return[k.cloneElement(Ce,et),null,null]}return de?[Ve,null,null]:[Ve,null]}),Ki(E,"renderCustomized",function(D,R,F){return k.cloneElement(D,sn(sn({key:"recharts-customized-".concat(F)},E.props),E.state))}),Ki(E,"renderMap",{CartesianGrid:{handler:pV,once:!0},ReferenceArea:{handler:E.renderReferenceElement},ReferenceLine:{handler:pV},ReferenceDot:{handler:E.renderReferenceElement},XAxis:{handler:pV},YAxis:{handler:pV},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((C=N.id)!==null&&C!==void 0?C:G8("recharts"),"-clip"),E.throttleTriggeredAfterMouseMove=ixt(E.triggeredAfterMouseMove,(A=N.throttleDelay)!==null&&A!==void 0?A:1e3/60),E.state={},E}return cFs(j,b),aFs(j,[{key:"componentDidMount",value:function(){var C,A;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(C=this.props.margin.left)!==null&&C!==void 0?C: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 C=this.props,A=C.children,E=C.data,D=C.height,R=C.layout,F=h0(A,rg);if(F){var O=F.props.defaultIndex;if(!(typeof O!="number"||O<0||O>this.state.tooltipTicks.length-1)){var B=this.state.tooltipTicks[O]&&this.state.tooltipTicks[O].value,K=dCe(this.state,E,O,B),Z=this.state.tooltipTicks[O].coordinate,Q=(this.state.offset.top+D)/2,W=R==="horizontal",te=W?{x:Z,y:Q}:{y:Z,x:Q},ne=this.state.formattedGraphicalItems.find(function(ue){var me=ue.item;return me.type.name==="Scatter"});ne&&(te=sn(sn({},te),ne.props.points[O].tooltipPosition),K=ne.props.points[O].tooltipPayload);var ae={activeTooltipIndex:O,isTooltipActive:!0,activeLabel:B,activePayload:K,activeCoordinate:te};this.setState(ae),this.renderCursor(F),this.accessibilityManager.setIndex(O)}}}},{key:"getSnapshotBeforeUpdate",value:function(C,A){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==A.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==C.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==C.margin){var E,D;this.accessibilityManager.setDetails({offset:{left:(E=this.props.margin.left)!==null&&E!==void 0?E:0,top:(D=this.props.margin.top)!==null&&D!==void 0?D:0}})}return null}},{key:"componentDidUpdate",value:function(C){zSe([h0(C.children,rg)],[h0(this.props.children,rg)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var C=h0(this.props.children,rg);if(C&&typeof C.props.shared=="boolean"){var A=C.props.shared?"axis":"item";return o.indexOf(A)>=0?A:i}return i}},{key:"getMouseInfo",value:function(C){if(!this.container)return null;var A=this.container,E=A.getBoundingClientRect(),D=w3s(E),R={chartX:Math.round(C.pageX-D.left),chartY:Math.round(C.pageY-D.top)},F=E.width/A.offsetWidth||1,O=this.inRange(R.chartX,R.chartY,F);if(!O)return null;var B=this.state,K=B.xAxisMap,Z=B.yAxisMap,Q=this.getTooltipEventType(),W=IGe(this.state,this.props.data,this.props.layout,O);if(Q!=="axis"&&K&&Z){var te=wk(K).scale,ne=wk(Z).scale,ae=te&&te.invert?te.invert(R.chartX):null,ue=ne&&ne.invert?ne.invert(R.chartY):null;return sn(sn({},R),{},{xValue:ae,yValue:ue},W)}return W?sn(sn({},R),W):null}},{key:"inRange",value:function(C,A){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,D=this.props.layout,R=C/E,F=A/E;if(D==="horizontal"||D==="vertical"){var O=this.state.offset,B=R>=O.left&&R<=O.left+O.width&&F>=O.top&&F<=O.top+O.height;return B?{x:R,y:F}:null}var K=this.state,Z=K.angleAxisMap,Q=K.radiusAxisMap;if(Z&&Q){var W=wk(Z);return rHe({x:R,y:F},W)}return null}},{key:"parseEventsOfWrapper",value:function(){var C=this.props.children,A=this.getTooltipEventType(),E=h0(C,rg),D={};E&&A==="axis"&&(E.props.trigger==="click"?D={onClick:this.handleClick}:D={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var R=Lfe(this.props,this.handleOuterEvent);return sn(sn({},R),D)}},{key:"addListener",value:function(){Kwe.on(Ywe,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Kwe.removeListener(Ywe,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(C,A,E){for(var D=this.state.formattedGraphicalItems,R=0,F=D.length;R{const{data:N,error:C}=await U.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(C)throw C;return N}}),{data:n}=pt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:N,error:C}=await U.from("profiles").select("id, name, email");if(C)throw C;return N}});if(r)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((n||[]).map(N=>[N.id,N])),l=a.reduce((N,C)=>N+(C.sent_count||0),0),o=a.reduce((N,C)=>N+(C.open_count||0),0),c=a.reduce((N,C)=>N+(C.click_count||0),0),d=a.reduce((N,C)=>N+(C.bounce_count||0),0),u=a.reduce((N,C)=>N+(C.complaint_count||0),0),m=l>0?(o/l*100).toFixed(1):"0.0",f=l>0?(c/l*100).toFixed(1):"0.0",x=[{label:"Campaigns Sent",value:a.length,icon:hn,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Dr,color:"text-green-600"},{label:"Avg Open Rate",value:`${m}%`,icon:Nn,color:"text-blue-600"},{label:"Avg Click Rate",value:`${f}%`,icon:dm,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:du,color:"text-orange-600"},{label:"Complaints",value:u,icon:Wo,color:"text-destructive"}],y=new Map;a.forEach(N=>{var E,D;const C=N.user_id,A=y.get(C)||{name:((E=i.get(C))==null?void 0:E.name)||((D=i.get(C))==null?void 0:D.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};A.campaigns++,A.sent+=N.sent_count||0,A.opens+=N.open_count||0,A.clicks+=N.click_count||0,y.set(C,A)});const _=[...y.entries()].map(([N,C])=>({id:N,...C,openRate:C.sent>0?+(C.opens/C.sent*100).toFixed(1):0})).sort((N,C)=>C.sent-N.sent),b=_.slice(0,6).map(N=>({name:N.name,value:N.sent})),j=a.map(N=>{var C;return{name:N.name.length>20?N.name.slice(0,20)+"…":N.name,agent:((C=i.get(N.user_id))==null?void 0:C.name)||"Unknown",openRate:N.sent_count>0?+(N.open_count/N.sent_count*100).toFixed(1):0,clickRate:N.sent_count>0?+(N.click_count/N.sent_count*100).toFixed(1):0,sent:N.sent_count,date:N.sent_at?As(new Date(N.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(hn,{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:x.map(N=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-center",children:[e.jsx(N.icon,{className:`h-5 w-5 mx-auto mb-1 ${N.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:N.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.label})]})},N.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Pe,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(AP,{width:"100%",height:"100%",children:e.jsxs(L0t,{data:j,children:[e.jsx(FA,{dataKey:"date",fontSize:11}),e.jsx(zA,{fontSize:11,unit:"%"}),e.jsx(rg,{formatter:N=>`${N}%`}),e.jsx(M2,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(M2,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Pe,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(AP,{width:"100%",height:"100%",children:e.jsxs(D0t,{children:[e.jsx(dw,{data:b,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:N,percent:C})=>`${N} (${(C*100).toFixed(0)}%)`,fontSize:11,children:b.map((N,C)=>e.jsx(KB,{fill:DGe[C%DGe.length]},C))}),e.jsx(rg,{})]})})})})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Pe,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(AP,{width:"100%",height:"100%",children:e.jsxs(kFs,{data:j,children:[e.jsx(FA,{dataKey:"date",fontSize:11}),e.jsx(zA,{fontSize:11}),e.jsx(rg,{}),e.jsx(t$,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Agent Performance"})}),e.jsx(Pe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-muted-foreground",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Agent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Campaigns"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Sent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Opens"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Clicks"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Open Rate"})]})}),e.jsx("tbody",{children:_.map(N=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:N.name}),e.jsx("td",{className:"py-2.5 text-center",children:N.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:N.sent}),e.jsx("td",{className:"py-2.5 text-center",children:N.opens}),e.jsx("td",{className:"py-2.5 text-center",children:N.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(Xe,{variant:"outline",children:[N.openRate,"%"]})})]},N.id))})]})})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((N,C)=>{const A=N.sent_count>0?N.open_count/N.sent_count:0;return(C.sent_count>0?C.open_count/C.sent_count:0)-A}).slice(0,10).map((N,C)=>{const A=N.sent_count>0?(N.open_count/N.sent_count*100).toFixed(1):"0.0",E=N.sent_count>0?(N.click_count/N.sent_count*100).toFixed(1):"0.0",D=i.get(N.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/${N.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",C+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:N.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(D==null?void 0:D.name)||"Unknown"," · ",N.sent_at?As(new Date(N.sent_at),"MMM d, yyyy"):""," · ",N.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"})," ",A,"%"]}),e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(dm,{className:"h-3 w-3"})," ",E,"%"]})]})]},N.id)})})})]})]})})}const CFs=()=>{const{toast:s}=Ba(),[t,r]=k.useState(!0),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});k.useEffect(()=>{d()},[]);const d=async()=>{try{r(!0);const u=new Date;u.setDate(u.getDate()-30);const m=u.toISOString(),{data:f}=await U.from("website_apps").select("slug, name").order("sort_order"),x=[];let y=0;for(;;){const{data:E,error:D}=await U.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(y,y+999);if(D)throw D;if(x.push(...E||[]),!E||E.length<1e3)break;y+=1e3}const _=[];for(y=0;;){const{data:E,error:D}=await U.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",m).order("created_at",{ascending:!1}).range(y,y+999);if(D)throw D;if(_.push(...E||[]),!E||E.length<1e3||(y+=1e3,y>2e4))break}const b=new Map;for(const E of f||[])b.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 x){const D=b.get(E.app_slug);D&&(D.installs+=1,E.enabled&&(D.enabled+=1))}for(const E of _){const D=b.get(E.app_slug);D&&(E.event_type==="impression"?D.impressions+=1:E.event_type==="expand"?D.expands+=1:E.event_type==="cta_click"?D.cta_clicks+=1:E.event_type==="lead_capture"&&(D.lead_captures+=1))}const j=new Map;for(const E of x){if(!E.enabled)continue;const D=j.get(E.user_id)||{user_id:E.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};D.apps_enabled.includes(E.app_slug)||D.apps_enabled.push(E.app_slug),j.set(E.user_id,D)}for(const E of _){const D=j.get(E.user_id);D&&(D.events_30d+=1,E.event_type==="lead_capture"&&(D.leads_30d+=1))}const N=Array.from(j.keys());if(N.length>0){const{data:E}=await U.from("profiles").select("id, name, email").in("id",N);for(const D of E||[]){const R=j.get(D.id);R&&(R.name=D.name,R.email=D.email)}}const C=Array.from(b.values()),A=Array.from(j.values()).sort((E,D)=>D.events_30d-E.events_30d);a(C),l(A),c({installs:C.reduce((E,D)=>E+D.enabled,0),activeAgents:A.length,impressions30d:C.reduce((E,D)=>E+D.impressions,0),leads30d:C.reduce((E,D)=>E+D.lead_captures,0)})}catch(u){console.error(u),s({title:"Error",description:u.message||"Failed to load website app analytics",variant:"destructive"})}finally{r(!1)}};return t?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(Ql,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.installs}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Apps turned on across all agents"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"At least one app enabled"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(Nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.impressions30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Widget views on lead sites"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(Ks,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.leads30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total submissions"})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"App Performance (last 30 days)"})}),e.jsx(Pe,{children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"App"}),e.jsx(At,{className:"text-right",children:"Installs"}),e.jsx(At,{className:"text-right",children:"Enabled"}),e.jsx(At,{className:"text-right",children:"Impressions"}),e.jsx(At,{className:"text-right",children:"Expands"}),e.jsx(At,{className:"text-right",children:"CTA Clicks"}),e.jsx(At,{className:"text-right",children:"Leads"}),e.jsx(At,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(ha,{children:[n.map(u=>{const m=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:u.app_name}),e.jsx(xt,{className:"text-right",children:u.installs}),e.jsx(xt,{className:"text-right",children:u.enabled}),e.jsx(xt,{className:"text-right",children:u.impressions}),e.jsx(xt,{className:"text-right",children:u.expands}),e.jsx(xt,{className:"text-right",children:u.cta_clicks}),e.jsx(xt,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(xt,{className:"text-right text-muted-foreground",children:m==="—"?"—":`${m}%`})]},u.app_slug)}),n.length===0&&e.jsx(Ws,{children:e.jsx(xt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Pe,{children:[e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Apps Enabled"}),e.jsx(At,{className:"text-right",children:"Events (30d)"}),e.jsx(At,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(ha,{children:[i.slice(0,100).map(u=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:u.name||"—"}),e.jsx(xt,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(xt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.apps_enabled.map(m=>e.jsx(Xe,{variant:"secondary",className:"text-xs",children:m},m))})}),e.jsx(xt,{className:"text-right",children:u.events_30d}),e.jsx(xt,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center text-muted-foreground py-6",children:"No agents have enabled website apps yet"})})]})]}),i.length>100&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Showing top 100 of ",i.length," agents."]})]})]})]})},TFs=()=>{const[s,t]=k.useState([]),[r,n]=k.useState([]),[a,i]=k.useState({}),[l,o]=k.useState(!0);k.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:m},{data:f}]=await Promise.all([U.rpc("get_extension_usage_summary"),U.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),x=m||[],y=f||[];t(x),n(y);const _=Array.from(new Set(y.map(b=>b.user_id)));if(_.length){const{data:b}=await U.from("profiles").select("id, name, email").in("id",_),j={};(b||[]).forEach(N=>{j[N.id]={name:N.name,email:N.email}}),i(j)}}finally{o(!1)}},d=s.reduce((m,f)=>({users:m.users+1,contacts:m.contacts+Number(f.contacts_saved||0),listings:m.listings+Number(f.listings_imported||0),activities:m.activities+Number(f.activities_logged||0),events:m.events+Number(f.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});const u=m=>{switch(m){case"contact_saved":return"Contact saved";case"listing_imported":return"Listing imported";case"activity_logged":return"Activity logged";case"template_used":return"Template used";case"paired":return"Extension paired";default:return m}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.users}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Using extension"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(CE,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.events}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All events"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(xl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(Pn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(Ui,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Users by Extension Activity"})}),e.jsx(Pe,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No extension usage yet. Once agents install and use the Chrome Extension, their activity will appear here."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"User"}),e.jsx(At,{className:"text-right",children:"Total"}),e.jsx(At,{className:"text-right",children:"Contacts"}),e.jsx(At,{className:"text-right",children:"Listings"}),e.jsx(At,{className:"text-right",children:"Activities"}),e.jsx(At,{children:"First Used"}),e.jsx(At,{children:"Last Used"})]})}),e.jsx(ha,{children:s.map(m=>e.jsxs(Ws,{children:[e.jsxs(xt,{children:[e.jsx("div",{className:"font-medium",children:m.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.email})]}),e.jsx(xt,{className:"text-right font-medium",children:m.total_events}),e.jsx(xt,{className:"text-right",children:m.contacts_saved}),e.jsx(xt,{className:"text-right",children:m.listings_imported}),e.jsx(xt,{className:"text-right",children:m.activities_logged}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:m.first_event_at?As(new Date(m.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:m.last_event_at?As(new Date(m.last_event_at),"MMM d, h:mm a"):"—"})]},m.user_id))})]})})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Recent Activity"})}),e.jsx(Pe,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:r.map(m=>{const f=a[m.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Xe,{variant:"secondary",children:u(m.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(f==null?void 0:f.name)||(f==null?void 0:f.email)||m.user_id.slice(0,8)}),m.metadata&&Object.keys(m.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(m.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:As(new Date(m.created_at),"MMM d, h:mm a")})]},m.id)})})})]})]})},EFs=()=>e.jsx(ws,{title:"Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Analytics & Activity"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Platform-wide usage statistics and user activity"})]}),e.jsxs(ta,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"analytics",children:"Analytics"}),e.jsx(rs,{value:"website-apps",children:"Website Apps"}),e.jsx(rs,{value:"extension",children:"Chrome Extension"}),e.jsx(rs,{value:"content",children:"Content"}),e.jsx(rs,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(rs,{value:"activity",children:"Activity"}),e.jsx(rs,{value:"shares",children:"Shares"})]}),e.jsx(fs,{value:"analytics",className:"space-y-4",children:e.jsx(e0s,{})}),e.jsx(fs,{value:"website-apps",className:"space-y-4",children:e.jsx(CFs,{})}),e.jsx(fs,{value:"extension",className:"space-y-4",children:e.jsx(TFs,{})}),e.jsx(fs,{value:"content",className:"space-y-4",children:e.jsx(s0s,{})}),e.jsx(fs,{value:"email-campaigns",className:"space-y-4",children:e.jsx(SFs,{})}),e.jsx(fs,{value:"activity",className:"space-y-4",children:e.jsx(Jgs,{})}),e.jsx(fs,{value:"shares",className:"space-y-4",children:e.jsx(Hft,{})})]})]})});function AFs(){const s=is(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=k.useState(null),[d,u]=k.useState(""),[m,f]=k.useState([]),[x,y]=k.useState([]),[_,b]=k.useState([]),[j,N]=k.useState(!1),[C,A]=k.useState(null),[E,D]=k.useState(""),{data:R,isLoading:F}=pt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:ve,error:Qe}=await U.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Qe)throw Qe;return ve}}),{data:O}=pt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:ve,error:Qe}=await U.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Qe)throw Qe;return ve}}),{data:B}=pt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:ve,error:Qe}=await U.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Qe)throw Qe;return ve}}),{data:K}=pt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:ve,error:Qe}=await U.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Qe)throw Qe;return ve}}),{data:Z,isLoading:Q}=pt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:ve,error:Qe}=await U.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Qe)throw Qe;return ve}}),W=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),f([]),y([]),b([]),a(null),D("")},te=ve=>{a(ve),l({title:ve.title,description:ve.description||"",publish_date:ve.publish_date.split("T")[0],is_published:ve.is_published,category_id:ve.category_id||""}),u(ve.preview_image_url||""),D("");const Qe=(O==null?void 0:O.filter(Se=>Se.resource_id===ve.id))||[];f(Qe.map(Se=>({id:Se.id,name:Se.name,file_url:Se.file_url,file_size:Se.file_size,sort_order:Se.sort_order})));const we=(B==null?void 0:B.filter(Se=>Se.resource_id===ve.id))||[];y(we.map(Se=>({id:Se.id,title:Se.title,video_url:Se.video_url,sort_order:Se.sort_order})));const nt=(K==null?void 0:K.filter(Se=>Se.resource_id===ve.id))||[];b(nt.map(Se=>({id:Se.id,title:Se.title,canva_share_link:Se.canva_share_link,sort_order:Se.sort_order}))),r(!0)},ne=ve=>{var we;const Qe=(we=ve.target.files)==null?void 0:we[0];Qe&&(c(Qe),u(URL.createObjectURL(Qe)))},ae=()=>{f([...m,{name:"",file_url:"",sort_order:m.length}])},ue=ve=>{f(m.filter((Qe,we)=>we!==ve))},me=(ve,Qe,we)=>{const nt=[...m];if(Qe==="file"&&we instanceof File){const Se=we.name.replace(/\.[^/.]+$/,"");nt[ve]={...nt[ve],file:we,file_size:we.size,name:nt[ve].name||Se}}else nt[ve]={...nt[ve],[Qe]:we};f(nt)},de=()=>{y([...x,{title:"",video_url:"",sort_order:x.length}])},fe=ve=>{y(x.filter((Qe,we)=>we!==ve))},je=(ve,Qe,we)=>{const nt=[...x];Qe==="file"&&we instanceof File?nt[ve]={...nt[ve],file:we}:nt[ve]={...nt[ve],[Qe]:we},y(nt)},xe=()=>{b([..._,{title:"",canva_share_link:"",sort_order:_.length}])},Ee=ve=>{b(_.filter((Qe,we)=>we!==ve))},Me=(ve,Qe,we)=>{const nt=[..._];nt[ve]={...nt[ve],[Qe]:we},b(nt)},Oe=async(ve,Qe)=>{try{const we=await U.functions.invoke("bunny-upload",{body:{action:"create",title:ve.name}});if(we.error)throw we.error;const{videoId:nt,uploadUrl:Se,libraryId:Ge}=we.data,We=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:nt,libraryId:Ge}});if(We.error)throw We.error;const{uploadUrl:Ce,apiKey:qe}=We.data,et=new XMLHttpRequest;return et.open("PUT",Ce,!0),et.setRequestHeader("AccessKey",qe),et.upload.onprogress=Ze=>{if(Ze.lengthComputable){const rt=Math.round(Ze.loaded/Ze.total*100),ct=[...x];ct[Qe]={...ct[Qe],uploadProgress:rt},y(ct)}},await new Promise((Ze,rt)=>{et.onload=()=>et.status>=200&&et.status<300?Ze():rt(new Error("Upload failed")),et.onerror=()=>rt(new Error("Upload failed")),et.send(ve)}),`https://iframe.mediadelivery.net/embed/${Ge}/${nt}`}catch(we){throw console.error("Bunny upload error:",we),we}},Ie=Mt({mutationFn:async ve=>{const{data:Qe,error:we}=await U.from("brokerage_resource_categories").insert({name:ve,sort_order:(Z==null?void 0:Z.length)||0}).select().single();if(we)throw we;return Qe},onSuccess:ve=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:ve.id}),D(""),he.success("Category created")},onError:ve=>{he.error("Failed to create category: "+ve.message)}}),ze=Mt({mutationFn:async()=>{N(!0);let ve=(n==null?void 0:n.preview_image_url)||null;if(o){const nt=o.name.split(".").pop(),Se=`${Date.now()}.${nt}`,{error:Ge}=await U.storage.from("brokerage-resources").upload(`previews/${Se}`,o);if(Ge)throw Ge;const{data:We}=U.storage.from("brokerage-resources").getPublicUrl(`previews/${Se}`);ve=We.publicUrl}const Qe={title:i.title,description:i.description||null,preview_image_url:ve,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let we;if(n){const{error:nt}=await U.from("brokerage_resources").update(Qe).eq("id",n.id);if(nt)throw nt;we=n.id;const Se=(O==null?void 0:O.filter(vt=>vt.resource_id===n.id).map(vt=>vt.id))||[],Ge=m.filter(vt=>vt.id).map(vt=>vt.id),We=Se.filter(vt=>!Ge.includes(vt));We.length>0&&await U.from("brokerage_resource_pdfs").delete().in("id",We);const Ce=(B==null?void 0:B.filter(vt=>vt.resource_id===n.id).map(vt=>vt.id))||[],qe=x.filter(vt=>vt.id).map(vt=>vt.id),et=Ce.filter(vt=>!qe.includes(vt));et.length>0&&await U.from("brokerage_resource_videos").delete().in("id",et);const Ze=(K==null?void 0:K.filter(vt=>vt.resource_id===n.id).map(vt=>vt.id))||[],rt=_.filter(vt=>vt.id).map(vt=>vt.id),ct=Ze.filter(vt=>!rt.includes(vt));ct.length>0&&await U.from("brokerage_resource_links").delete().in("id",ct)}else{const{data:nt,error:Se}=await U.from("brokerage_resources").insert(Qe).select().single();if(Se)throw Se;we=nt.id}for(let nt=0;nt{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),he.success(n?"Resource updated":"Resource created"),r(!1),W(),N(!1)},onError:ve=>{he.error("Failed to save resource: "+ve.message),N(!1)}}),Ve=Mt({mutationFn:async ve=>{const{error:Qe}=await U.from("brokerage_resources").delete().eq("id",ve);if(Qe)throw Qe},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),he.success("Resource deleted")},onError:ve=>{he.error("Failed to delete: "+ve.message)}}),Le=ve=>{if(ve.preventDefault(),!i.title){he.error("Please enter a title");return}ze.mutate()},$e=ve=>{const Qe=(O==null?void 0:O.filter(Se=>Se.resource_id===ve).length)||0,we=(B==null?void 0:B.filter(Se=>Se.resource_id===ve).length)||0,nt=(K==null?void 0:K.filter(Se=>Se.resource_id===ve).length)||0;return{pdfCount:Qe,videoCount:we,linkCount:nt}};return e.jsx(ws,{title:"Brokerage Resources Management",description:"Create and manage resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(R==null?void 0:R.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(R==null?void 0:R.filter(ve=>ve.is_published).length)||0})})]})]}),e.jsxs(q,{onClick:()=>{W(),r(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Category"}),e.jsx(At,{children:"Content"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:F?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(R==null?void 0:R.length)===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):R==null?void 0:R.map(ve=>{const{pdfCount:Qe,videoCount:we,linkCount:nt}=$e(ve.id),Se=Z==null?void 0:Z.find(Ge=>Ge.id===ve.category_id);return e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ve.preview_image_url?e.jsx("img",{src:ve.preview_image_url,alt:ve.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(bm,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ve.title}),ve.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ve.description})]})]})}),e.jsx(xt,{children:Se?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Se.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(En,{className:"h-3.5 w-3.5"}),Qe]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),we]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tl,{className:"h-3.5 w-3.5"}),nt]})]})}),e.jsx(xt,{children:As(new Date(ve.publish_date),"MMM d, yyyy")}),e.jsx(xt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ve.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ve.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{const Ge=(O==null?void 0:O.filter(qe=>qe.resource_id===ve.id))||[],We=(B==null?void 0:B.filter(qe=>qe.resource_id===ve.id))||[],Ce=(K==null?void 0:K.filter(qe=>qe.resource_id===ve.id))||[];A({...ve,pdfs:Ge,videos:We,links:Ce})},children:e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>te(ve),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Ve.mutate(ve.id)},children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},ve.id)})})]})})}),e.jsx(vs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:n?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Le,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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(bm,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:ne})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:i.title,onChange:ve=>l({...i,title:ve.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(Fh,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ds,{value:i.category_id,onValueChange:ve=>l({...i,category_id:ve}),children:[e.jsx(Ps,{className:"flex-1",children:e.jsx(Fs,{placeholder:"Select a category"})}),e.jsx(Ls,{children:Z==null?void 0:Z.map(ve=>e.jsx(lt,{value:ve.id,children:ve.name},ve.id))})]}),i.category_id&&e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Or create new category...",value:E,onChange:ve=>D(ve.target.value),className:"flex-1"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",disabled:!E.trim()||Ie.isPending,onClick:()=>Ie.mutate(E.trim()),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(V1,{content:i.description,onChange:ve=>l({...i,description:ve}),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(ce,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:i.publish_date,onChange:ve=>l({...i,publish_date:ve.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Rr,{checked:i.is_published,onCheckedChange:ve=>l({...i,is_published:ve})}),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(ce,{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-4 w-4"}),"PDF Documents (",m.length,")"]}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:ae,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),m.map((ve,Qe)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(Ne,{placeholder:"PDF Name",value:ve.name,onChange:we=>me(Qe,"name",we.target.value),className:"flex-1"}),e.jsx(Ne,{type:"file",accept:".pdf",onChange:we=>{var Se;const nt=(Se=we.target.files)==null?void 0:Se[0];nt&&me(Qe,"file",nt)},className:"flex-1"}),ve.file_url&&!ve.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>ue(Qe),children:e.jsx($r,{className:"h-4 w-4"})})]},Qe))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(bn,{className:"h-4 w-4"}),"Videos (",x.length,")"]}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:de,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),x.map((ve,Qe)=>e.jsxs("div",{className:"space-y-2 p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{placeholder:"Video Title",value:ve.title,onChange:we=>je(Qe,"title",we.target.value),className:"flex-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>fe(Qe),children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsx(Ne,{type:"file",accept:"video/*",onChange:we=>{var Se;const nt=(Se=we.target.files)==null?void 0:Se[0];nt&&je(Qe,"file",nt)}}),ve.uploadProgress!==void 0&&ve.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:`${ve.uploadProgress}%`}})}),ve.video_url&&!ve.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Qe))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ce,{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-4 w-4"}),"Canva Links (",_.length,")"]}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:xe,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),_.map((ve,Qe)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(Ne,{placeholder:"Link Title",value:ve.title,onChange:we=>Me(Qe,"title",we.target.value),className:"flex-1"}),e.jsx(Ne,{placeholder:"Canva Share Link",value:ve.canva_share_link,onChange:we=>Me(Qe,"canva_share_link",we.target.value),className:"flex-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>Ee(Qe),children:e.jsx($r,{className:"h-4 w-4"})})]},Qe))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:ze.isPending||j,children:ze.isPending||j?"Saving...":n?"Update":"Create"})]})]})]})}),e.jsx(vs,{open:!!C,onOpenChange:()=>A(null),children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:C==null?void 0:C.title})}),C&&e.jsxs("div",{className:"space-y-4",children:[C.preview_image_url&&e.jsx("img",{src:C.preview_image_url,alt:C.title,className:"w-full h-48 object-cover rounded-lg"}),C.description&&e.jsx("p",{className:"text-muted-foreground",children:C.description}),C.pdfs&&C.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(En,{className:"h-4 w-4"}),"PDF Documents (",C.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:C.pdfs.map(ve=>e.jsx("a",{href:ve.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ve.name},ve.id))})]}),C.videos&&C.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(bn,{className:"h-4 w-4"}),"Videos (",C.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:C.videos.map(ve=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:ve.title})},ve.id))})]}),C.links&&C.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(tl,{className:"h-4 w-4"}),"Canva Links (",C.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:C.links.map(ve=>e.jsx("a",{href:ve.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ve.title},ve.id))})]})]})]})})]})})}const R0t=[{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 MFs(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),[u,m]=k.useState(!1),[f,x]=k.useState(!1),[y,_]=k.useState(""),[b,j]=k.useState(""),[N,C]=k.useState(""),[A,E]=k.useState(""),[D,R]=k.useState("Learn More"),[F,O]=k.useState("top"),[B,K]=k.useState(""),[Z,Q]=k.useState(!0),[W,te]=k.useState(""),[ne,ae]=k.useState("");k.useEffect(()=>{ue()},[]);const ue=async()=>{try{const{data:Ie,error:ze}=await U.from("dashboard_banners").select("*").order("placement").order("sort_order");if(ze)throw ze;t(Ie||[])}catch(Ie){he.error("Failed to load banners: "+Ie.message)}finally{n(!1)}},me=()=>{_(""),j(""),C(""),E(""),R("Learn More"),O("top"),K(""),Q(!0),te(""),ae(""),d(null)},de=Ie=>{d(Ie),_(Ie.title),j(Ie.description||""),C(Ie.image_url),E(Ie.link_url||""),R(Ie.link_text||"Learn More"),O(Ie.placement),K(Ie.section_after||""),Q(Ie.is_active),te(Ie.start_date?As(new Date(Ie.start_date),"yyyy-MM-dd'T'HH:mm"):""),ae(Ie.end_date?As(new Date(Ie.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},fe=async Ie=>{var Ve;const ze=(Ve=Ie.target.files)==null?void 0:Ve[0];if(ze){m(!0);try{const Le=ze.name.split(".").pop(),$e=`${Date.now()}.${Le}`,{error:ve}=await U.storage.from("banner-images").upload($e,ze);if(ve)throw ve;const{data:{publicUrl:Qe}}=U.storage.from("banner-images").getPublicUrl($e);C(Qe),he.success("Image uploaded successfully")}catch(Le){he.error("Failed to upload image: "+Le.message)}finally{m(!1)}}},je=async()=>{if(!y.trim()||!N){he.error("Please fill in required fields (title and image)");return}x(!0);try{const Ie={title:y.trim(),description:b.trim()||null,image_url:N,link_url:A.trim()||null,link_text:D.trim()||"Learn More",placement:F,section_after:F==="between"?B:null,is_active:Z,start_date:W?new Date(W).toISOString():null,end_date:ne?new Date(ne).toISOString():null};if(c){const{error:ze}=await U.from("dashboard_banners").update(Ie).eq("id",c.id);if(ze)throw ze;he.success("Banner updated successfully")}else{const ze=s.filter(Le=>Le.placement===F).length,{error:Ve}=await U.from("dashboard_banners").insert({...Ie,sort_order:ze});if(Ve)throw Ve;he.success("Banner created successfully")}i(!1),me(),ue()}catch(Ie){he.error("Failed to save banner: "+Ie.message)}finally{x(!1)}},xe=async()=>{if(c)try{const{error:Ie}=await U.from("dashboard_banners").delete().eq("id",c.id);if(Ie)throw Ie;he.success("Banner deleted successfully"),o(!1),d(null),ue()}catch(Ie){he.error("Failed to delete banner: "+Ie.message)}},Ee=async Ie=>{try{const{error:ze}=await U.from("dashboard_banners").update({is_active:!Ie.is_active}).eq("id",Ie.id);if(ze)throw ze;he.success(Ie.is_active?"Banner deactivated":"Banner activated"),ue()}catch(ze){he.error("Failed to update banner: "+ze.message)}},Me=s.filter(Ie=>Ie.placement==="top"),Oe=s.filter(Ie=>Ie.placement==="between");return r?e.jsx(ws,{title:"Dashboard Management",children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs(ws,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(zo,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Ur,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(vs,{open:a&&F==="top",onOpenChange:Ie=>{Ie||me(),i(Ie),Ie&&O("top")},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{onClick:()=>{me(),O("top")},children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(an,{children:"Configure the banner's content and display settings"})]}),e.jsx(RGe,{title:y,setTitle:_,description:b,setDescription:j,imageUrl:N,linkUrl:A,setLinkUrl:E,linkText:D,setLinkText:R,placement:F,setPlacement:O,sectionAfter:B,setSectionAfter:K,isActive:Z,setIsActive:Q,startDate:W,setStartDate:te,endDate:ne,setEndDate:ae,handleImageUpload:fe,uploading:u,showPlacementOptions:!1}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>{i(!1),me()},children:"Cancel"}),e.jsx(q,{onClick:je,disabled:f,children:f?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Pe,{children:Me.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No hero banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:Me.map(Ie=>e.jsx(OGe,{banner:Ie,onEdit:()=>de(Ie),onDelete:()=>{d(Ie),o(!0)},onToggleActive:()=>Ee(Ie)},Ie.id))})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(zo,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Ur,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(vs,{open:a&&F==="between",onOpenChange:Ie=>{Ie||me(),i(Ie),Ie&&O("between")},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{onClick:()=>{me(),O("between")},children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(an,{children:"Configure where this banner appears between sections"})]}),e.jsx(RGe,{title:y,setTitle:_,description:b,setDescription:j,imageUrl:N,linkUrl:A,setLinkUrl:E,linkText:D,setLinkText:R,placement:F,setPlacement:O,sectionAfter:B,setSectionAfter:K,isActive:Z,setIsActive:Q,startDate:W,setStartDate:te,endDate:ne,setEndDate:ae,handleImageUpload:fe,uploading:u,showPlacementOptions:!0}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>{i(!1),me()},children:"Cancel"}),e.jsx(q,{onClick:je,disabled:f,children:f?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Pe,{children:Oe.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:Oe.map(Ie=>e.jsx(OGe,{banner:Ie,onEdit:()=>de(Ie),onDelete:()=>{d(Ie),o(!0)},onToggleActive:()=>Ee(Ie),showSection:!0},Ie.id))})})]})]}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Delete Banner"}),e.jsxs(an,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(q,{variant:"destructive",onClick:xe,children:"Delete"})]})]})})]})}function RGe({title:s,setTitle:t,description:r,setDescription:n,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:m,setSectionAfter:f,isActive:x,setIsActive:y,startDate:_,setStartDate:b,endDate:j,setEndDate:N,handleImageUpload:C,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(ce,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",placeholder:"Banner headline...",value:s,onChange:D=>t(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",placeholder:"Optional banner description...",value:r,onChange:D=>n(D.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Ne,{type:"file",accept:"image/*",onChange:C,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(ce,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(Ne,{id:"linkUrl",placeholder:"https://...",value:i,onChange:D=>l(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"linkText",children:"Button Text"}),e.jsx(Ne,{id:"linkText",placeholder:"Learn More",value:o,onChange:D=>c(D.target.value)})]})]}),E&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Placement"}),e.jsxs(Ds,{value:m,onValueChange:f,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select section placement..."})}),e.jsx(Ls,{children:R0t.map(D=>e.jsx(lt,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(Ne,{id:"startDate",type:"datetime-local",value:_,onChange:D=>b(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(Ne,{id:"endDate",type:"datetime-local",value:j,onChange:D=>N(D.target.value)})]})]}),e.jsx("div",{className:"flex items-center justify-between pt-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{id:"isActive",checked:x,onCheckedChange:y}),e.jsx(ce,{htmlFor:"isActive",children:"Active"})]})})]})}function OGe({banner:s,onEdit:t,onDelete:r,onToggleActive:n,showSection:a=!1}){var c;const i=(c=R0t.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=k.useState(null);return k.useEffect(()=>{(async()=>{const{count:u}=await U.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Vu,{className:"h-5 w-5 text-muted-foreground cursor-grab"}),e.jsx("img",{src:s.image_url,alt:s.title,className:"w-24 h-14 object-cover rounded"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium truncate",children:s.title}),!s.is_active&&e.jsx(Xe,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(Xe,{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(Bc,{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(q,{variant:"ghost",size:"icon",children:e.jsx(un,{className:"h-4 w-4"})})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:n,children:s.is_active?e.jsx(Nn,{className:"h-4 w-4"}):e.jsx(Wf,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:r,children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})]})}const xV={open:{label:"Open",icon:jn,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:gc,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Ti,color:"bg-green-500"},closed:{label:"Closed",icon:ad,color:"bg-muted-foreground"}},FGe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function IFs(){var F,O;const{user:s}=Cs(),t=is(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState([]),[c,d]=k.useState("all"),[u,m]=k.useState("all"),[f,x]=k.useState(!1),{data:y=[],isLoading:_}=pt({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let B=U.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(B=B.eq("status",c)),u!=="all"&&(B=B.eq("category",u));const{data:K,error:Z}=await B;if(Z)throw Z;return K}}),{data:b=[]}=pt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:B,error:K}=await U.from("user_roles").select("user_id").eq("role","admin");if(K)throw K;const Z=B.map(ue=>ue.user_id),{data:Q,error:W}=await U.from("profiles").select("id, name, email").in("id",Z);if(W)throw W;const{data:te,error:ne}=await U.from("support_notification_settings").select("user_id, receive_notifications");if(ne)throw ne;const ae=new Map((te==null?void 0:te.map(ue=>[ue.user_id,ue.receive_notifications]))||[]);return Q.map(ue=>({...ue,receives_notifications:ae.get(ue.id)||!1}))}}),{data:j=[]}=pt({queryKey:["admin-ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:B,error:K}=await U.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(K)throw K;return B},enabled:!!r}),N=Mt({mutationFn:async({userId:B,enabled:K})=>{const{data:Z}=await U.from("support_notification_settings").select("id").eq("user_id",B).maybeSingle();if(Z){const{error:Q}=await U.from("support_notification_settings").update({receive_notifications:K}).eq("user_id",B);if(Q)throw Q}else{const{error:Q}=await U.from("support_notification_settings").insert({user_id:B,receive_notifications:K});if(Q)throw Q}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),he.success("Notification settings updated")},onError:()=>{he.error("Failed to update settings")}}),C=Mt({mutationFn:async({ticketId:B,status:K})=>{const{error:Z}=await U.from("support_tickets").update({status:K}).eq("id",B);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),r&&n({...r,status:r.status}),he.success("Status updated")},onError:()=>{he.error("Failed to update status")}}),A=Mt({mutationFn:async({ticketId:B,assignedTo:K})=>{const{error:Z}=await U.from("support_tickets").update({assigned_to:K}).eq("id",B);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),he.success("Ticket assigned")},onError:()=>{he.error("Failed to assign ticket")}}),E=Mt({mutationFn:async({content:B,attachments:K})=>{var Q,W;if(!r||!s)throw new Error("Missing data");const{error:Z}=await U.from("support_ticket_replies").insert({ticket_id:r.id,user_id:s.id,content:B,is_admin_reply:!0,attachments:K});if(Z)throw Z;try{await U.functions.invoke("support-reply-notify",{body:{ticketId:r.id,ticketSubject:r.subject,replyContent:B,userEmail:(Q=r.profiles)==null?void 0:Q.email,userName:(W=r.profiles)==null?void 0:W.name}})}catch(te){console.error("Failed to send reply notification:",te)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",r==null?void 0:r.id]}),i(""),o([]),he.success("Reply sent!")},onError:()=>{he.error("Failed to send reply")}}),D=()=>{!a.trim()&&l.length===0||E.mutate({content:a,attachments:l})};k.useEffect(()=>{const B=U.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{U.removeChannel(B)}},[t]);const R=y.filter(B=>B.status==="open").length;return r?(xV[r.status].icon,e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>n(null),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"secondary",children:FGe[r.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((F=r.profiles)==null?void 0:F.name)||"Unknown"," (",(O=r.profiles)==null?void 0:O.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm",children:"Status"})}),e.jsx(Pe,{children:e.jsxs(Ds,{value:r.status,onValueChange:B=>{C.mutate({ticketId:r.id,status:B}),n({...r,status:B})},children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"open",children:"Open"}),e.jsx(lt,{value:"in_progress",children:"In Progress"}),e.jsx(lt,{value:"resolved",children:"Resolved"}),e.jsx(lt,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm",children:"Assigned To"})}),e.jsx(Pe,{children:e.jsxs(Ds,{value:r.assigned_to||"unassigned",onValueChange:B=>{const K=B==="unassigned"?null:B;A.mutate({ticketId:r.id,assignedTo:K}),n({...r,assigned_to:K})},children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Unassigned"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"unassigned",children:"Unassigned"}),b.map(B=>e.jsx(lt,{value:B.id,children:B.name},B.id))]})]})})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Ur,{children:["Created on ",As(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Pe,{children:[e.jsx(ui,{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(B=>{var K,Z;return e.jsxs("div",{className:`p-4 rounded-lg ${B.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:B.is_admin_reply?`${((K=B.profiles)==null?void 0:K.name)||"Admin"} (Support)`:((Z=B.profiles)==null?void 0:Z.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(B.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:B.content}),B.attachments&&B.attachments.length>0&&e.jsx(mft,{attachments:B.attachments})]},B.id)})})}),e.jsx(cl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pr,{placeholder:"Type your reply...",value:a,onChange:B=>i(B.target.value),className:"min-h-[80px]"}),e.jsx(q,{onClick:D,disabled:!a.trim()&&l.length===0||E.isPending,className:"self-end",children:e.jsx(hn,{className:"h-4 w-4"})})]}),e.jsx(hft,{value:l,onChange:o,disabled:E.isPending})]})]})]})]})})):e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Support Tickets"}),e.jsxs("p",{className:"text-muted-foreground",children:["Manage support requests from agents",R>0&&e.jsxs(Xe,{variant:"destructive",className:"ml-2",children:[R," open"]})]})]}),e.jsxs(vs,{open:f,onOpenChange:x,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Email Notification Settings"}),e.jsx(an,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:b.map(B=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(qi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:B.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:B.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[B.receives_notifications?e.jsx(ym,{className:"h-4 w-4 text-primary"}):e.jsx(b_,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Rr,{checked:B.receives_notifications,onCheckedChange:K=>N.mutate({userId:B.id,enabled:K})})]})]},B.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(ta,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(ea,{children:[e.jsx(rs,{value:"all",children:"All"}),e.jsx(rs,{value:"open",children:"Open"}),e.jsx(rs,{value:"in_progress",children:"In Progress"}),e.jsx(rs,{value:"resolved",children:"Resolved"}),e.jsx(rs,{value:"closed",children:"Closed"})]})}),e.jsxs(Ds,{value:u,onValueChange:m,children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{placeholder:"All Categories"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Categories"}),e.jsx(lt,{value:"general",children:"General Support"}),e.jsx(lt,{value:"technology",children:"Technology Support"}),e.jsx(lt,{value:"crm",children:"CRM Support"}),e.jsx(lt,{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(ke,{children:e.jsxs(Pe,{className:"text-center py-12",children:[e.jsx(gc,{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(B=>{var Z,Q;const K=xV[B.status].icon;return e.jsx(ke,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n(B),children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:B.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(Xe,{variant:"outline",className:"text-xs",children:FGe[B.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(Z=B.profiles)==null?void 0:Z.name," • ",As(new Date(B.created_at),"MMM d, yyyy")]}),B.assigned_to&&e.jsxs(Xe,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(qi,{className:"h-3 w-3"}),((Q=b.find(W=>W.id===B.assigned_to))==null?void 0:Q.name)||"Assigned"]})]})]}),e.jsxs(Xe,{className:xV[B.status].color,children:[e.jsx(K,{className:"h-3 w-3 mr-1"}),xV[B.status].label]})]})})},B.id)})})})]})]})})}const O0t=tp.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 PFs({content:s,onChange:t,variables:r}){const n=QEe({extensions:[eAe,dAe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),uAe.configure({types:["heading","paragraph"]}),hAe,O0t],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});k.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const a=l=>{n&&n.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!n)return;const l=n.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return n?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBold().run(),className:n.isActive("bold")?"bg-muted":"",children:e.jsx(Jk,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleItalic().run(),className:n.isActive("italic")?"bg-muted":"",children:e.jsx(rS,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBulletList().run(),className:n.isActive("bulletList")?"bg-muted":"",children:e.jsx(Zf,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleOrderedList().run(),className:n.isActive("orderedList")?"bg-muted":"",children:e.jsx(T1,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("left").run(),className:n.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(NE,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("center").run(),className:n.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(jE,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("right").run(),className:n.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(kE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:i,className:n.isActive("link")?"bg-muted":"",children:e.jsx(tl,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleCodeBlock().run(),className:n.isActive("codeBlock")?"bg-muted":"",children:e.jsx(TE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),children:e.jsx(hS,{className:"h-4 w-4"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),children:e.jsx(cS,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),r.length>0&&e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dP,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Sd,{align:"end",className:"w-64",children:r.map(l=>e.jsxs(ti,{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(ZEe,{editor:n,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),r.length>0&&e.jsxs("div",{className:"border-t p-3 bg-muted/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Available variables (click to copy):"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(l=>e.jsx(Xe,{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 LFs(){const s=is(),[t,r]=k.useState(null),[n,a]=k.useState(null),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[m,f]=k.useState(!0),[x,y]=k.useState("visual"),{data:_,isLoading:b}=pt({queryKey:["email-templates"],queryFn:async()=>{const{data:E,error:D}=await U.from("email_templates").select("*").order("name");if(D)throw D;return E.map(R=>({...R,available_variables:R.available_variables||[]}))}}),j=Mt({mutationFn:async E=>{const{error:D}=await U.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(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),he.success("Email template updated successfully"),r(null)},onError:E=>{he.error("Failed to update template: "+E.message)}}),N=E=>{r(E),l(E.subject),c(E.body_html),u(E.description||""),f(E.is_active),y("visual")},C=()=>{t&&j.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:m})},A=(E,D)=>{let R=E;return D.forEach(F=>{const O=`{{${F.key}}}`,B=`[${F.label}]`;R=R.replace(new RegExp(O.replace(/[{}]/g,"\\$&"),"g"),B)}),R};return t?e.jsxs(ws,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(q,{variant:"ghost",onClick:()=>r(null),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(q,{variant:"outline",onClick:()=>a(t),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(q,{onClick:C,disabled:j.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),j.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5"}),t.name]}),e.jsxs(Ur,{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(ce,{htmlFor:"active-toggle",children:"Active"}),e.jsx(Rr,{id:"active-toggle",checked:m,onCheckedChange:f})]})]})}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{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(ce,{htmlFor:"subject",children:"Email Subject"}),e.jsx(Ne,{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(ce,{children:"Email Body"}),e.jsx(ta,{value:x,onValueChange:E=>y(E),children:e.jsxs(ea,{className:"h-8",children:[e.jsxs(rs,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(k_,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(rs,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(TE,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),x==="visual"?e.jsx(PFs,{content:o,onChange:c,variables:t.available_variables}):e.jsx(pr,{value:o,onChange:E=>c(E.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(vs,{open:!!n,onOpenChange:()=>a(null),children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Email Preview"}),e.jsxs(an,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(o,t.available_variables)}})})]})})]}):e.jsx(ws,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),b?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((E,D)=>e.jsx(ke,{children:e.jsxs(Pt,{children:[e.jsx(dr,{className:"h-5 w-48"}),e.jsx(dr,{className:"h-4 w-96"})]})},D))}):e.jsx("div",{className:"grid gap-4",children:_==null?void 0:_.map(E=>e.jsxs(ke,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Dt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ks,{className:"h-5 w-5 text-muted-foreground"}),E.name,!E.is_active&&e.jsx(Xe,{variant:"secondary",children:"Inactive"})]}),e.jsx(Ur,{children:E.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>a(E),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(q,{size:"sm",onClick:()=>N(E),children:[e.jsx(iu,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),e.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-sm",children: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(D=>e.jsx(Xe,{variant:"outline",className:"font-mono text-xs",children:`{{${D.key}}}`},D.key))})]})]})})]},E.id))}),e.jsx(vs,{open:!!n&&!t,onOpenChange:()=>a(null),children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{children:["Email Preview: ",n==null?void 0:n.name]}),e.jsxs(an,{children:["Subject: ",n==null?void 0:n.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),n&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(n.body_html,n.available_variables)}})})]})})]})})}function DFs(){const s=is(),[t,r]=k.useState("templates"),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[m,f]=k.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[x,y]=k.useState({name:"",description:"",icon:"📧"}),{data:_=[]}=pt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:B,error:K}=await U.from("email_template_categories").select("*").order("sort_order");if(K)throw K;return B}}),{data:b=[],isLoading:j}=pt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:B,error:K}=await U.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(K)throw K;return B}}),N=Mt({mutationFn:async B=>{const K={title:B.title,subject:B.subject,body:B.body,description:B.description||null,tone:B.tone||null,category_id:B.category_id||null,is_active:B.is_active};if(B.id){const{error:Z}=await U.from("agent_email_templates").update(K).eq("id",B.id);if(Z)throw Z}else{const{error:Z}=await U.from("agent_email_templates").insert(K);if(Z)throw Z}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),he.success(n?"Template updated":"Template created")},onError:()=>he.error("Failed to save template")}),C=Mt({mutationFn:async B=>{const{error:K}=await U.from("agent_email_templates").delete().eq("id",B);if(K)throw K},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),he.success("Template deleted")}}),A=Mt({mutationFn:async B=>{const K={name:B.name,description:B.description||null,icon:B.icon};if(B.id){const{error:Z}=await U.from("email_template_categories").update(K).eq("id",B.id);if(Z)throw Z}else{const Z=_.length>0?Math.max(..._.map(W=>W.sort_order))+1:0,{error:Q}=await U.from("email_template_categories").insert({...K,sort_order:Z});if(Q)throw Q}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),he.success(i?"Category updated":"Category created")},onError:()=>he.error("Failed to save category")}),E=Mt({mutationFn:async B=>{const{error:K}=await U.from("email_template_categories").delete().eq("id",B);if(K)throw K},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),he.success("Category deleted")}}),D=()=>{a(null),f({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},R=B=>{a(B),f({title:B.title,subject:B.subject,body:B.body,description:B.description||"",tone:B.tone||"",category_id:B.category_id||"",is_active:B.is_active}),c(!0)},F=()=>{l(null),y({name:"",description:"",icon:"📧"}),u(!0)},O=B=>{l(B),y({name:B.name,description:B.description||"",icon:B.icon}),u(!0)};return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Uh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(ta,{value:t,onValueChange:r,children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"templates",className:"gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"})," Templates"]}),e.jsxs(rs,{value:"categories",className:"gap-2",children:[e.jsx(Kf,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(fs,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(q,{onClick:D,className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Template"}),e.jsx(At,{className:"hidden md:table-cell",children:"Category"}),e.jsx(At,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:j?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:e.jsx(ls,{className:"h-6 w-6 animate-spin mx-auto"})})}):b.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):b.map(B=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:B.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:B.subject})]})}),e.jsx(xt,{className:"hidden md:table-cell",children:B.category?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[B.category.icon," ",B.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{className:"hidden md:table-cell",children:B.tone?e.jsx(Xe,{variant:"secondary",children:B.tone}):"—"}),e.jsx(xt,{children:e.jsx(Xe,{variant:B.is_active?"default":"secondary",children:B.is_active?"Active":"Inactive"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>R(B),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&C.mutate(B.id)},children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},B.id))})]})})})]}),e.jsxs(fs,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(q,{onClick:F,className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:_.map(B=>e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:B.icon})," ",B.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>O(B),children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>{confirm("Delete this category?")&&E.mutate(B.id)},children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:B.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[b.filter(K=>K.category_id===B.id).length," templates"]})]})]},B.id))})]})]}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:n?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Title"}),e.jsx(Ne,{value:m.title,onChange:B=>f(K=>({...K,title:B.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Category"}),e.jsxs(Ds,{value:m.category_id,onValueChange:B=>f(K=>({...K,category_id:B})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select category"})}),e.jsx(Ls,{children:_.map(B=>e.jsxs(lt,{value:B.id,children:[B.icon," ",B.name]},B.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Subject Line"}),e.jsx(Ne,{value:m.subject,onChange:B=>f(K=>({...K,subject:B.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(ce,{children:"Email Body"}),e.jsx(pr,{value:m.body,onChange:B=>f(K=>({...K,body:B.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(ce,{children:"Description (internal)"}),e.jsx(Ne,{value:m.description,onChange:B=>f(K=>({...K,description:B.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Tone"}),e.jsx(Ne,{value:m.tone,onChange:B=>f(K=>({...K,tone:B.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{checked:m.is_active,onCheckedChange:B=>f(K=>({...K,is_active:B}))}),e.jsx(ce,{children:"Active"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(q,{onClick:()=>N.mutate({...m,id:n==null?void 0:n.id}),disabled:N.isPending||!m.title||!m.subject||!m.body,children:[N.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Save Changes":"Create Template"]})]})]})}),e.jsx(vs,{open:d,onOpenChange:u,children:e.jsxs(ys,{className:"sm:max-w-[450px]",children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{children:"Icon"}),e.jsx(Ne,{value:x.icon,onChange:B=>y(K=>({...K,icon:B.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Name"}),e.jsx(Ne,{value:x.name,onChange:B=>y(K=>({...K,name:B.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Description"}),e.jsx(Ne,{value:x.description,onChange:B=>y(K=>({...K,description:B.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(q,{onClick:()=>A.mutate({...x,id:i==null?void 0:i.id}),disabled:A.isPending||!x.name,children:[A.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const RFs=({brokerageId:s})=>{var Tn,Qt;const{toast:t}=Ba(),r=qr(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(""),[d,u]=k.useState("all"),[m,f]=k.useState(new Set),[x,y]=k.useState(!1),[_,b]=k.useState({}),[j,N]=k.useState(!1),[C,A]=k.useState(!1),[E,D]=k.useState({email:"",name:"",password:"",phone:""}),[R,F]=k.useState(!1),[O,B]=k.useState(null),[K,Z]=k.useState(!1),[Q,W]=k.useState(!1),[te,ne]=k.useState(!1),[ae,ue]=k.useState(""),[me,de]=k.useState(!1),[fe,je]=k.useState([]),[xe,Ee]=k.useState(!1),[Me,Oe]=k.useState(!1),[Ie,ze]=k.useState(null),[Ve,Le]=k.useState({name:"",phone:"",email:""}),[$e,ve]=k.useState(!1),[Qe,we]=k.useState(!1),[nt,Se]=k.useState(null),[Ge,We]=k.useState("asc"),[Ce,qe]=k.useState(!1),[et,Ze]=k.useState(null),[rt,ct]=k.useState(!1),[vt,kt]=k.useState(null),[St,Yt]=k.useState(""),[es,zs]=k.useState(!1),[sr,ms]=k.useState(null);k.useEffect(()=>{Ut(),gt()},[s]);const gt=async()=>{try{const{data:Re,error:Ke}=await U.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Ke)throw Ke;je((Re==null?void 0:Re.map(at=>at.user_id))||[])}catch(Re){console.error("Error loading brokerage managers:",Re)}},Ut=async()=>{try{l(!0);const{data:Re,error:Ke}=await U.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Ke)throw Ke;const at=Re.agents||[];if(a(at),at.length>0){const Nt=at.map(qt=>qt.id),{data:Ft}=await U.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",Nt);if(Ft&&Ft.length>0){const qt=Ft.map(Xt=>Xt.assistant_id),{data:cs}=await U.from("profiles").select("id, name, email").in("id",qt),it={};for(const Xt of Ft){const Bs=cs==null?void 0:cs.find(us=>us.id===Xt.assistant_id);Bs&&(it[Xt.agent_id]={name:Bs.name||"",email:Bs.email||""})}b(it)}else b({})}}catch(Re){console.error("Error loading agents:",Re),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},ht=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:Re}}=await U.auth.getSession(),Ke=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Re==null?void 0:Re.access_token}`},body:JSON.stringify({...E,brokerageId:s})}),at=await Ke.json();if(!Ke.ok)throw new Error(at.error||"Failed to create agent");t({title:"Success",description:`Agent ${E.email} created successfully`}),D({email:"",name:"",password:"",phone:""}),N(!1),Ut()}catch(Re){console.error("Error creating agent:",Re),t({title:"Error",description:Re.message||"Failed to create agent",variant:"destructive"})}finally{A(!1)}},Jt=async Re=>{try{const{data:{session:Ke}}=await U.auth.getSession(),at=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ke==null?void 0:Ke.access_token}`},body:JSON.stringify({userId:Re})}),Nt=await at.json();if(!at.ok)throw new Error(Nt.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Ke){console.error("Error resending welcome email:",Ke),t({title:"Error",description:Ke.message||"Failed to resend welcome email",variant:"destructive"})}},Ms=async(Re,Ke)=>{try{const{error:at}=await U.functions.invoke("send-password-reset",{body:{email:Re,redirectTo:window.location.origin}});if(at)throw at;t({title:"Password Reset Sent",description:`Password reset email sent to ${Ke}`})}catch(at){console.error("Error sending password reset:",at),t({title:"Error",description:at.message||"Failed to send password reset email",variant:"destructive"})}},ts=Re=>{B(Re),F(!0)},Xs=Re=>{ze(Re),Le({name:Re.name,phone:Re.phone||"",email:Re.email}),Oe(!0)},js=async()=>{if(!Ie)return;if(!Ve.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Re=Ve.email.trim().toLowerCase()!==Ie.email.toLowerCase();ve(!0);try{if(Re){if(!Ve.email.trim())throw new Error("Email is required");we(!0);const{data:{session:at}}=await U.auth.getSession(),Nt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${at==null?void 0:at.access_token}`},body:JSON.stringify({agentId:Ie.id,newEmail:Ve.email.trim(),brokerageId:s})}),Ft=await Nt.json();if(we(!1),!Nt.ok)throw new Error(Ft.error||"Failed to update email")}const{error:Ke}=await U.from("profiles").update({name:Ve.name.trim(),phone:Ve.phone.trim()||null}).eq("id",Ie.id);if(Ke)throw Ke;t({title:"Success",description:"Agent profile updated successfully"}),Oe(!1),ze(null),Ut()}catch(Ke){console.error("Error updating agent:",Ke),t({title:"Error",description:Ke.message||"Failed to update agent",variant:"destructive"})}finally{ve(!1),we(!1)}},$s=async()=>{if(!ae){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}de(!0);try{const{data:{session:Re}}=await U.auth.getSession(),Ke=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Re==null?void 0:Re.access_token}`},body:JSON.stringify({userId:ae,role:"brokerage_manager",action:"add",brokerageId:s})}),at=await Ke.json();if(!Ke.ok)throw new Error(at.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),ne(!1),ue(""),gt()}catch(Re){console.error("Error adding brokerage manager:",Re),t({title:"Error",description:Re.message||"Failed to add brokerage manager",variant:"destructive"})}finally{de(!1)}},Js=async Re=>{try{const{data:{session:Ke}}=await U.auth.getSession(),at=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ke==null?void 0:Ke.access_token}`},body:JSON.stringify({userId:Re,role:"brokerage_manager",action:"remove",brokerageId:s})}),Nt=await at.json();if(!at.ok)throw new Error(Nt.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),gt()}catch(Ke){console.error("Error removing brokerage manager:",Ke),t({title:"Error",description:Ke.message||"Failed to remove brokerage manager",variant:"destructive"})}},or=Re=>fe.includes(Re),Er=Re=>{kt(Re),Yt(""),ct(!0)},Sr=async()=>{if(!(!vt||!St)){if(St.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}zs(!0);try{const{data:{session:Re}}=await U.auth.getSession(),Ke=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Re==null?void 0:Re.access_token}`},body:JSON.stringify({agentId:vt.id,brokerageId:s,action:"set_password",newPassword:St})}),at=await Ke.json();if(!Ke.ok)throw new Error(at.error||"Failed to set password");t({title:"Success",description:`Password set for ${vt.name}`}),ct(!1),kt(null),Yt("")}catch(Re){console.error("Error setting password:",Re),t({title:"Error",description:Re.message||"Failed to set password",variant:"destructive"})}finally{zs(!1)}}},Gr=async Re=>{ms(Re.id);try{const{data:{session:Ke}}=await U.auth.getSession(),at=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ke==null?void 0:Ke.access_token}`},body:JSON.stringify({agentId:Re.id,brokerageId:s,action:"claim_account"})}),Nt=await at.json();if(!at.ok)throw new Error(Nt.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Re.name}`}),Ut()}catch(Ke){console.error("Error claiming account:",Ke),t({title:"Error",description:Ke.message||"Failed to claim account",variant:"destructive"})}finally{ms(null)}},Yr=async()=>{if(O){Z(!0);try{const{data:{session:Re}}=await U.auth.getSession(),Ke=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Re==null?void 0:Re.access_token}`},body:JSON.stringify({userId:O.id,brokerageId:s})}),at=await Ke.json();if(!Ke.ok)throw new Error(at.error||"Failed to remove agent");t({title:"Success",description:`${O.name} has been removed from your brokerage`}),F(!1),B(null),Ut()}catch(Re){console.error("Error removing agent:",Re),t({title:"Error",description:Re.message||"Failed to remove agent",variant:"destructive"})}finally{Z(!1)}}},Fn=Re=>{const Ke=Re.trim().split(" ");return Ke.length>1?Ke[Ke.length-1].toLowerCase():Re.toLowerCase()},sa=Re=>{nt===Re?We(Ge==="asc"?"desc":"asc"):(Se(Re),We("asc"))},gs=Re=>nt!==Re?e.jsx(Uu,{className:"ml-1 h-4 w-4"}):Ge==="asc"?e.jsx(qu,{className:"ml-1 h-4 w-4"}):e.jsx(gm,{className:"ml-1 h-4 w-4"}),mi=n.filter(Re=>{if(d==="active"&&!Re.claimed||d==="pending"&&Re.claimed)return!1;if(!o)return!0;const Ke=o.toLowerCase();return Re.name.toLowerCase().includes(Ke)||Re.email.toLowerCase().includes(Ke)}),In=[...mi].sort((Re,Ke)=>{if(!nt)return 0;let at=0;return nt==="name"?at=Fn(Re.name).localeCompare(Fn(Ke.name)):nt==="status"&&(at=Re.claimed===Ke.claimed?0:Re.claimed?-1:1),Ge==="asc"?at:-at});mi.filter(Re=>Re.claimed&&!or(Re.id));const Br=Re=>{f(Ke=>{const at=new Set(Ke);return at.has(Re)?at.delete(Re):at.add(Re),at})},ps=()=>{m.size===In.length?f(new Set):f(new Set(In.map(Re=>Re.id)))},Or=()=>{f(new Set)},Qr=async()=>{const Re=Array.from(m);if(Re.length===0)return;y(!0);let Ke=0,at=0;try{const{data:{session:Nt}}=await U.auth.getSession();for(const Ft of Re)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Nt==null?void 0:Nt.access_token}`},body:JSON.stringify({userId:Ft})})).ok?Ke++:at++}catch{at++}Ke>0?t({title:"Success",description:`Welcome emails sent to ${Ke} agent${Ke>1?"s":""}${at>0?` (${at} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Or()}catch(Nt){console.error("Error bulk sending welcome emails:",Nt),t({title:"Error",description:Nt.message||"Failed to send welcome emails",variant:"destructive"})}finally{y(!1)}};return i?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Agents"}),e.jsx(Ur,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(q,{variant:"outline",onClick:()=>ne(!0),children:[e.jsx(Oh,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(q,{variant:"outline",onClick:()=>W(!0),children:[e.jsx(s2,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(q,{onClick:()=>N(!0),children:[e.jsx(xl,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:o,onChange:Re=>c(Re.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:d,onValueChange:Re=>u(Re),children:[e.jsx(Ps,{className:"w-[160px]",children:e.jsx(Fs,{placeholder:"Filter by status"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Agents"}),e.jsx(lt,{value:"active",children:"Active"}),e.jsx(lt,{value:"pending",children:"Pending"})]})]})]}),m.size>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border bg-muted/50 p-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[m.size," agent",m.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>{const Ke=n.filter(at=>m.has(at.id)&&at.email).map(at=>({email:at.email,name:at.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Ke)),r("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Ke}})},disabled:x,children:[e.jsx(fh,{className:"mr-2 h-4 w-4"}),"Email Agents (",m.size,")"]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:Qr,disabled:x,children:[e.jsx(Ks,{className:"mr-2 h-4 w-4"}),x?"Sending...":"Resend Welcome Email"]}),e.jsx(q,{size:"sm",variant:"ghost",onClick:Or,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-[40px]",children:e.jsx(Ri,{checked:In.length>0&&m.size===In.length,onCheckedChange:ps,"aria-label":"Select all"})}),e.jsx(At,{children:e.jsxs(q,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>sa("name"),children:["Name (Last)",gs("name")]})}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:e.jsxs(q,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>sa("status"),children:["Status",gs("status")]})}),e.jsx(At,{children:"Actions"})]})}),e.jsx(ha,{children:In.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):In.map(Re=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsx(Ri,{checked:m.has(Re.id),onCheckedChange:()=>Br(Re.id),"aria-label":`Select ${Re.name}`})}),e.jsx(xt,{className:"font-medium",children:Re.name}),e.jsx(xt,{children:Re.email}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Re.claimed?e.jsx(Xe,{variant:"default",children:"Active"}):e.jsx(Xe,{variant:"secondary",children:"Pending"}),or(Re.id)&&e.jsxs(Xe,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(A1,{className:"mr-1 h-3 w-3"}),"Manager"]}),_[Re.id]&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:[e.jsx(Dr,{className:"mr-1 h-3 w-3"}),"Asst: ",_[Re.id].name||_[Re.id].email]})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>{Ze(Re),qe(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(ph,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>Xs(Re),title:"Edit agent",children:e.jsx(Ua,{className:"h-4 w-4"})}),!Re.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>Jt(Re.id),title:"Resend welcome email",children:e.jsx(Ks,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>Gr(Re),title:"Claim account for agent",disabled:sr===Re.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(M1,{className:"h-4 w-4"})})]}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>Er(Re),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(q,{size:"sm",variant:"ghost",onClick:()=>Ms(Re.email,Re.name),title:"Send password reset email",children:e.jsx(PE,{className:"h-4 w-4"})}),or(Re.id)&&e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>Js(Re.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Oh,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>ts(Re),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},Re.id))})]})})]})]}),e.jsx(vs,{open:j,onOpenChange:N,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Add New Agent"}),e.jsx(an,{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(ce,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",value:E.name,onChange:Re=>D({...E,name:Re.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",value:E.email,onChange:Re=>D({...E,email:Re.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(Ne,{id:"phone",type:"tel",value:E.phone,onChange:Re=>D({...E,phone:Re.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"password",children:"Temporary Password"}),e.jsx(Ne,{id:"password",type:"password",value:E.password,onChange:Re=>D({...E,password:Re.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>N(!1),children:"Cancel"}),e.jsx(q,{onClick:ht,disabled:C,children:C?"Creating...":"Create Agent"})]})]})}),e.jsx(vs,{open:R,onOpenChange:F,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Remove Agent"}),e.jsxs(an,{children:["Are you sure you want to remove ",e.jsx("strong",{children:O==null?void 0:O.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>F(!1),children:"Cancel"}),e.jsx(q,{variant:"destructive",onClick:Yr,disabled:K,children:K?"Removing...":"Remove Agent"})]})]})}),e.jsx(fft,{open:Q,onOpenChange:W,fixedBrokerageId:s,onSuccess:Ut}),e.jsx(vs,{open:te,onOpenChange:ne,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Add Brokerage Manager"}),e.jsx(an,{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(ce,{children:"Select Agent"}),e.jsxs(sl,{open:xe,onOpenChange:Ee,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",role:"combobox","aria-expanded":xe,className:"w-full justify-between",children:[ae?((Tn=n.find(Re=>Re.id===ae))==null?void 0:Tn.name)+" ("+((Qt=n.find(Re=>Re.id===ae))==null?void 0:Qt.email)+")":"Select an agent to promote...",e.jsx(xg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-full p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search by name or email..."}),e.jsxs(kg,{className:"max-h-[200px]",children:[e.jsx(Sg,{children:"No eligible agents found."}),e.jsx(Cg,{children:n.filter(Re=>!or(Re.id)).map(Re=>e.jsxs(Sp,{value:`${Re.name} ${Re.email}`,onSelect:()=>{ue(Re.id),Ee(!1)},children:[e.jsx(la,{className:`mr-2 h-4 w-4 ${ae===Re.id?"opacity-100":"opacity-0"}`}),Re.name," (",Re.email,")"]},Re.id))})]})]})})]}),n.filter(Re=>!or(Re.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx(q,{onClick:$s,disabled:me||!ae,children:me?"Adding...":"Add as Manager"})]})]})}),e.jsx(vs,{open:Me,onOpenChange:Oe,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Edit Agent"}),e.jsxs(an,{children:["Update profile information for ",Ie==null?void 0:Ie.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"edit-name",children:"Name"}),e.jsx(Ne,{id:"edit-name",value:Ve.name,onChange:Re=>Le({...Ve,name:Re.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"edit-email",children:"Email"}),e.jsx(Ne,{id:"edit-email",type:"email",value:Ve.email,onChange:Re=>Le({...Ve,email:Re.target.value}),placeholder:"agent@example.com"}),Ve.email.trim().toLowerCase()!==(Ie==null?void 0:Ie.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(ce,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(Ne,{id:"edit-phone",type:"tel",value:Ve.phone,onChange:Re=>Le({...Ve,phone:Re.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>Oe(!1),children:"Cancel"}),e.jsx(q,{onClick:js,disabled:$e||Qe,children:Qe?"Updating email...":$e?"Saving...":"Save Changes"})]})]})}),et&&e.jsx(pft,{open:Ce,onOpenChange:Re=>{qe(Re),Re||Ze(null)},userId:et.id,userName:et.name}),e.jsx(vs,{open:rt,onOpenChange:ct,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Set Password"}),e.jsxs(an,{children:["Set a new password for ",vt==null?void 0:vt.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(ce,{htmlFor:"new-password",children:"New Password"}),e.jsx(Ne,{id:"new-password",type:"password",value:St,onChange:Re=>Yt(Re.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(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>ct(!1),children:"Cancel"}),e.jsx(q,{onClick:Sr,disabled:es||!St||St.length<6,children:es?"Setting...":"Set Password"})]})]})})]})},OFs={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},FFs={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},zFs=s=>{switch(s){case"academy_video":return e.jsx(bn,{className:"h-4 w-4"});case"template":return e.jsx(En,{className:"h-4 w-4"});case"toolbox":return e.jsx(En,{className:"h-4 w-4"});case"newsletter":return e.jsx(E1,{className:"h-4 w-4"});case"social_swag":return e.jsx(Ir,{className:"h-4 w-4"});case"event":return e.jsx(vn,{className:"h-4 w-4"});default:return e.jsx(un,{className:"h-4 w-4"})}},BFs=({brokerageId:s})=>{const{toast:t}=Ba(),[r,n]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState([]),[c,d]=k.useState(!0),[u,m]=k.useState(null);k.useEffect(()=>{f()},[s]);const f=async()=>{try{d(!0);const{data:_,error:b}=await U.from("profiles").select("id, name, email").eq("brokerage_id",s);if(b)throw b;const j=_.map(K=>K.id),N=new Map(_.map(K=>[K.id,K]));if(j.length===0){n([]),i([]),o([]);return}const{data:C,error:A}=await U.from("activity_logs").select("*").in("user_id",j).order("launched_at",{ascending:!1});if(A)throw A;const E=C.map(K=>{var Z,Q;return{id:K.id,user_id:K.user_id,app_name:K.app_name,launched_at:K.launched_at,user_name:((Z=N.get(K.user_id))==null?void 0:Z.name)||"Unknown",user_email:((Q=N.get(K.user_id))==null?void 0:Q.email)||"Unknown"}});n(E);const{data:D,error:R}=await U.from("content_engagement_logs").select("*").in("user_id",j).order("created_at",{ascending:!1});if(R)throw R;const F=(D||[]).map(K=>{var Z,Q;return{id:K.id,user_id:K.user_id,resource_type:K.resource_type,resource_id:K.resource_id,resource_title:K.resource_title,action_type:K.action_type,created_at:K.created_at,user_name:((Z=N.get(K.user_id))==null?void 0:Z.name)||"Unknown",user_email:((Q=N.get(K.user_id))==null?void 0:Q.email)||"Unknown"}});i(F);const O=new Map;_.forEach(K=>{O.set(K.id,{user_id:K.id,user_name:K.name,user_email:K.email,app_launches:0,content_views:0,last_activity:""})}),E.forEach(K=>{const Z=O.get(K.user_id);Z&&(Z.app_launches++,(!Z.last_activity||new Date(K.launched_at)>new Date(Z.last_activity))&&(Z.last_activity=K.launched_at))}),F.forEach(K=>{const Z=O.get(K.user_id);Z&&(Z.content_views++,(!Z.last_activity||new Date(K.created_at)>new Date(Z.last_activity))&&(Z.last_activity=K.created_at))});const B=Array.from(O.values()).filter(K=>K.app_launches>0||K.content_views>0).sort((K,Z)=>new Date(Z.last_activity).getTime()-new Date(K.last_activity).getTime());o(B)}catch(_){console.error("Error loading activity:",_),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},x=_=>r.filter(b=>b.user_id===_),y=_=>a.filter(b=>b.user_id===_);return c?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Agent Activity"}),e.jsx(Ur,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{className:"text-center",children:"App Launches"}),e.jsx(At,{className:"text-center",children:"Content Views"}),e.jsx(At,{children:"Last Active"})]})}),e.jsx(ha,{children:l.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(_=>e.jsxs(Ws,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>m({id:_.user_id,name:_.user_name,email:_.user_email}),children:[e.jsx(xt,{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(xt,{className:"text-center",children:e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Al,{className:"h-3 w-3"}),_.app_launches]})}),e.jsx(xt,{className:"text-center",children:e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(En,{className:"h-3 w-3"}),_.content_views]})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:_.last_activity&&Nl(new Date(_.last_activity),{addSuffix:!0})})]},_.user_id))})]})})})]}),e.jsx(vs,{open:!!u,onOpenChange:_=>!_&&m(null),children:e.jsxs(ys,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(_s,{children:[e.jsxs(bs,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(an,{children:u==null?void 0:u.email})]}),e.jsxs(ta,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ea,{className:"grid w-full grid-cols-2",children:[e.jsx(rs,{value:"content",children:"Content Engagement"}),e.jsx(rs,{value:"apps",children:"App Launches"})]}),e.jsx(fs,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Resource"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Action"}),e.jsx(At,{children:"Time"})]})}),e.jsx(ha,{children:u&&y(u.id).length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&y(u.id).map(_=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"max-w-[200px] truncate font-medium",children:_.resource_title}),e.jsx(xt,{children:e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[zFs(_.resource_type),OFs[_.resource_type]||_.resource_type]})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:FFs[_.action_type]||_.action_type})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:Nl(new Date(_.created_at),{addSuffix:!0})})]},_.id))})]})})}),e.jsx(fs,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"App"}),e.jsx(At,{children:"Time"})]})}),e.jsx(ha,{children:u&&x(u.id).length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&x(u.id).map(_=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsx(Xe,{variant:"outline",children:_.app_name})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:Nl(new Date(_.launched_at),{addSuffix:!0})})]},_.id))})]})})})]})]})})]})},$Fs=({brokerageId:s})=>{const{toast:t}=Ba(),[r,n]=k.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=k.useState(!0);k.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await U.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:m,error:f}=await U.from("profiles").select("id, email").in("id",d);if(f)throw f;const{count:x}=await U.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),y=x||0,_=u-y,{count:b}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),j=new Date;j.setDate(j.getDate()-7);const{count:N}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",j.toISOString()),C=new Date;C.setMonth(C.getMonth()-1);const{count:A}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",C.toISOString());n({totalAgents:u,activeAgents:y,pendingAgents:_,totalLaunches:b||0,launchesThisWeek:N||0,launchesThisMonth:A||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.activeAgents," active, ",r.pendingAgents," pending"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Ti,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.totalAgents>0?`${Math.round(r.activeAgents/r.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(jn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(xm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(xm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(xm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]})]})},UFs=({brokerageId:s})=>{const[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState({description:"",maxUses:""});k.useEffect(()=>{m()},[s]);const m=async()=>{try{const{data:j,error:N}=await U.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(N)throw N;r(j||[])}catch(j){console.error("Error loading invite codes:",j),he.error("Failed to load invite links")}finally{a(!1)}},f=()=>Math.random().toString(36).substring(2,8).toUpperCase(),x=async()=>{l(!0);try{const j=f(),{error:N}=await U.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(N)throw N;he.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),m()}catch(j){console.error("Error creating invite code:",j),he.error("Failed to create invite link")}finally{l(!1)}},y=async j=>{try{const{error:N}=await U.from("invite_codes").delete().eq("id",j);if(N)throw N;he.success("Invite link deleted"),r(t.filter(C=>C.id!==j))}catch(N){console.error("Error deleting invite code:",N),he.error("Failed to delete invite link")}},_=async(j,N)=>{try{const{error:C}=await U.from("invite_codes").update({is_active:!N}).eq("id",j);if(C)throw C;r(t.map(A=>A.id===j?{...A,is_active:!N}:A)),he.success(`Invite link ${N?"deactivated":"activated"}`)}catch(C){console.error("Error toggling invite code:",C),he.error("Failed to update invite link")}},b=j=>{const N=`${window.location.origin}/join?code=${j}`;navigator.clipboard.writeText(N),he.success("Link copied to clipboard!")};return n?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Ur,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{size:"sm",children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create Invite Link"}),e.jsx(an,{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(ce,{htmlFor:"description",children:"Description (optional)"}),e.jsx(Ne,{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(ce,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(Ne,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:j=>u({...d,maxUses:j.target.value})})]}),e.jsx(q,{onClick:x,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Pe,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(tl,{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(Xe,{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(q,{variant:"ghost",size:"sm",onClick:()=>b(j.code),title:"Copy link",children:e.jsx(si,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>_(j.id,j.is_active),title:j.is_active?"Deactivate":"Activate",children:j.is_active?"Disable":"Enable"}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>y(j.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(zr,{className:"h-4 w-4"})})]})]},j.id))})})]})},qFs=({open:s,onOpenChange:t,referralCode:r,brokerageId:n,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=k.useState(""),[d,u]=k.useState([]),[m,f]=k.useState(""),[x,y]=k.useState(!1),_=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A),b=()=>{const A=o.trim().toLowerCase();if(A&&_(A)&&!d.includes(A)){if(d.length>=10){he.error("Maximum 10 emails per invite");return}u([...d,A]),c("")}else A&&!_(A)?he.error("Please enter a valid email address"):d.includes(A)&&he.error("Email already added")},j=A=>{u(d.filter(E=>E!==A))},N=A=>{(A.key==="Enter"||A.key===",")&&(A.preventDefault(),b())},C=async()=>{if(d.length===0){he.error("Please add at least one email address");return}y(!0);try{const{data:A,error:E}=await U.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:m.trim()||void 0,referralCode:r,brokerageId:n,senderName:a,brokerageName:i}});if(E)throw E;A.successCount===A.totalCount?he.success(`${A.successCount} invite${A.successCount>1?"s":""} sent successfully!`):he.warning(`${A.successCount} of ${A.totalCount} invites sent. Some failed.`),u([]),f(""),t(!1),l==null||l()}catch(A){console.error("Error sending invites:",A),he.error("Failed to send invites. Please try again.")}finally{y(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[550px]",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(an,{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(Di,{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(ce,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:A=>c(A.target.value),onKeyDown:N,onBlur:b}),e.jsx(q,{type:"button",variant:"secondary",onClick:b,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(A=>e.jsxs(Xe,{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($r,{className:"h-3 w-3"})})]},A))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(pr,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:m,onChange:A=>f(A.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[m.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Ir,{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(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{onClick:C,disabled:d.length===0||x,children:x?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(hn,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},VFs=({brokerageId:s,refreshTrigger:t})=>{const[r,n]=k.useState([]),[a,i]=k.useState(!0);k.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await U.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;n(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(Xe,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(Ti,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(Xe,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(ad,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),"Pending"]})}};return a?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):r.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(Ks,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No invites sent yet"}),e.jsx("p",{className:"text-xs",children:"Start inviting broker friends to earn rewards!"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Recent Invites"}),r.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.recipient_email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent ",As(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},HFs=()=>{const{brokerageId:s,user:t}=Cs(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState([]),[u,m]=k.useState(!0),[f,x]=k.useState(!1),[y,_]=k.useState(0);k.useEffect(()=>{s&&b()},[s]);const b=async()=>{try{const[D,R]=await Promise.all([U.from("brokerages").select("name").eq("id",s).single(),t?U.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);D.data&&i(D.data.name),R.data&&o(R.data.name||"A LevelUp Member");const{data:F}=await U.from("referral_codes").select("code").eq("brokerage_id",s).single();if(F)n(F.code);else{const B=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await U.from("referral_codes").insert({brokerage_id:s,code:B}),n(B)}const{data:O}=await U.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(O||[])}catch(D){console.error("Error fetching referral data:",D)}finally{m(!1)}},j=()=>{const D=`https://dashboard.relevelup.com/?ref=${r}`;navigator.clipboard.writeText(D),he.success("Referral link copied to clipboard!")},N=c.filter(D=>D.status==="qualified").length,C=c.filter(D=>D.status==="pending").length,A=N*25,E=Math.max(0,Math.ceil((299-A)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-gradient-to-r from-primary/10 via-primary/5 to-background border-b",children:e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"bg-primary/20 rounded-full p-2",children:e.jsx(Di,{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(Ti,{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(Ir,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Pe,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(q,{onClick:()=>x(!0),className:"w-full",size:"lg",children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(q,{onClick:j,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Copy Referral Link"]})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Your Referral Link"}),e.jsxs("code",{className:"block px-3 py-2 bg-background rounded border text-sm break-all",children:["https://dashboard.relevelup.com/?ref=",r]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-900",children:[e.jsx(Xl,{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(Dr,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:N}),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(jn,{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:C}),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(VFs,{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(D=>{var R,F;return e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsx("span",{className:"text-sm truncate",children:((R=D.referred_brokerage)==null?void 0:R.name)||((F=D.referred_user)==null?void 0:F.email)||"Pending setup"}),e.jsxs(Xe,{variant:D.status==="qualified"?"default":D.status==="pending"?"secondary":"destructive",className:D.status==="qualified"?"bg-green-600":"",children:[D.status==="qualified"&&e.jsx(Ti,{className:"h-3 w-3 mr-1"}),D.status]})]},D.id)})]})]})]}),e.jsx(qFs,{open:f,onOpenChange:x,referralCode:r||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>_(D=>D+1)})]})},GFs=({brokerageId:s})=>{const t=qr(),{teams:r,isLoading:n}=aM(s),{data:a,isLoading:i}=pt({queryKey:["team-aggregate-stats",s,r.map(u=>u.id)],queryFn:async()=>{if(r.length===0)return[];const u=r.map(D=>D.id),{data:m}=await U.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!m||m.length===0)return r.map(D=>({team_id:D.id,team_name:D.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const f=m.map(D=>D.user_id),x=m.filter(D=>D.role==="team_leader").map(D=>D.user_id),{data:y}=await U.from("profiles").select("id, name, avatar_url").in("id",x),_=new Map((y||[]).map(D=>[D.id,D])),{data:b}=await U.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",f),{data:j}=await U.from("deal_pipeline").select("owner_user_id").in("owner_user_id",f),{data:N}=await U.from("agent_videos").select("owner_user_id").in("owner_user_id",f).eq("is_deleted",!1),C=new Map;(b||[]).forEach(D=>{C.set(D.owner_user_id,(C.get(D.owner_user_id)||0)+1)});const A=new Map;(j||[]).forEach(D=>{A.set(D.owner_user_id,(A.get(D.owner_user_id)||0)+1)});const E=new Map;return(N||[]).forEach(D=>{E.set(D.owner_user_id,(E.get(D.owner_user_id)||0)+1)}),r.map(D=>{const R=m.filter(W=>W.team_id===D.id),F=R.find(W=>W.role==="team_leader"),O=F?_.get(F.user_id):null,B=R.map(W=>W.user_id),K=B.reduce((W,te)=>W+(C.get(te)||0),0),Z=B.reduce((W,te)=>W+(A.get(te)||0),0),Q=B.reduce((W,te)=>W+(E.get(te)||0),0);return{team_id:D.id,team_name:D.name,member_count:R.length,leader_name:(O==null?void 0:O.name)||null,leader_avatar:(O==null?void 0:O.avatar_url)||null,total_contacts:K,total_deals:Z,total_videos:Q}})},enabled:r.length>0});if(n||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(dr,{className:"h-5 w-32"})}),e.jsx(Pe,{children:e.jsx(dr,{className:"h-24 w-full"})})]},u))});if(r.length===0)return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Dr,{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(q,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((u,m)=>u+m.member_count,0),c=(a||[]).reduce((u,m)=>u+m.total_contacts,0),d=(a||[]).reduce((u,m)=>u+m.total_deals,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 grid-cols-2 md:grid-cols-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Dr,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:r.length})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Dr,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(AE,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(bm,{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(ke,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Pt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Dt,{className:"text-lg",children:u.team_name}),e.jsxs(Xe,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Wn,{className:"h-6 w-6",children:[e.jsx(Xa,{src:u.leader_avatar||""}),e.jsx(Kn,{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(Gf,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Pe,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children: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(q,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},WFs=()=>{const{user:s,isBrokerageManager:t,brokerageId:r,isAdmin:n,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=Cs(),o=qr(),{toast:c}=Ba(),[d,u]=k.useState(""),[m,f]=k.useState(!0),x=i||(a.length>0?a[0].id:r);k.useEffect(()=>{if(!s||!t&&!n){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),x?y():a.length===0&&!r&&f(!1)},[s,t,n,x,o,a,i]);const y=async()=>{if(!x){f(!1);return}try{const{data:_,error:b}=await U.from("brokerages").select("name").eq("id",x).single();if(b)throw b;u(_.name)}catch(_){console.error("Error loading brokerage info:",_),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{f(!1)}};return m?e.jsx(ws,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):x?e.jsx(ws,{title:d||"Manage Brokerages",description:"Brokerage Management Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(Ds,{value:i||"",onValueChange:l,children:[e.jsxs(Ps,{className:"w-[280px]",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),e.jsx(Fs,{placeholder:"Select brokerage"})]}),e.jsx(Ls,{children:a.map(_=>e.jsx(lt,{value:_.id,children:_.name},_.id))})]})]}),e.jsxs(ta,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ea,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(rs,{value:"agents",children:"Agents"}),e.jsx(rs,{value:"teams",children:"Teams"}),e.jsx(rs,{value:"invite",children:"Invite Links"}),e.jsx(rs,{value:"referrals",children:"Referrals"}),e.jsx(rs,{value:"leaderboard",children:"Leaderboard"}),e.jsx(rs,{value:"activity",children:"Activity"}),e.jsx(rs,{value:"analytics",children:"Analytics"}),e.jsx(rs,{value:"shares",children:"Shares"})]}),e.jsx(fs,{value:"agents",className:"space-y-4",children:e.jsx(RFs,{brokerageId:x})}),e.jsx(fs,{value:"teams",className:"space-y-4",children:e.jsx(GFs,{brokerageId:x})}),e.jsx(fs,{value:"invite",className:"space-y-4",children:e.jsx(UFs,{brokerageId:x})}),e.jsx(fs,{value:"referrals",className:"space-y-4",children:e.jsx(HFs,{})}),e.jsx(fs,{value:"leaderboard",className:"space-y-4",children:e.jsx(_ht,{brokerageId:x,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(fs,{value:"activity",className:"space-y-4",children:e.jsx(BFs,{brokerageId:x})}),e.jsx(fs,{value:"analytics",className:"space-y-4",children:e.jsx($Fs,{brokerageId:x})}),e.jsx(fs,{value:"shares",className:"space-y-4",children:e.jsx(Hft,{brokerageOnly:!0,brokerageId:x})})]})]})}):e.jsx(ws,{title:"Manage Brokerages",description:"Brokerage Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ga,{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 KFs({brokerageId:s,canManage:t}){const{user:r}=Cs(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(!1),[d,u]=k.useState(null),[m,f]=k.useState(null),[x,y]=k.useState(!1),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState(!1),E=async()=>{try{const{data:B,error:K}=await U.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(K)throw K;const Z=B;if(Z&&Z.length>0){const Q=[...new Set(Z.map(ae=>ae.created_by))],{data:W}=await U.from("profiles").select("id, name, avatar_url").in("id",Q),te=new Map((W==null?void 0:W.map(ae=>[ae.id,ae]))||[]),ne=Z.map(ae=>({...ae,author:te.get(ae.created_by)||{name:"Unknown",avatar_url:null}}));a(ne)}else a([])}catch(B){console.error("Error fetching announcements:",B)}finally{l(!1)}};k.useEffect(()=>{E()},[s]);const D=()=>{b(""),N(""),A(!1),u(null)},R=B=>{B?(u(B),b(B.title),N(B.content),A(B.is_pinned)):D(),c(!0)},F=async()=>{if(!_.trim()||!j.trim()){he.error("Please fill in all fields");return}y(!0);try{if(d){const{error:B}=await U.from("brokerage_announcements").update({title:_.trim(),content:j.trim(),is_pinned:C,pinned_at:C?new Date().toISOString():null}).eq("id",d.id);if(B)throw B;he.success("Announcement updated")}else{const{error:B}=await U.from("brokerage_announcements").insert({brokerage_id:s,created_by:r==null?void 0:r.id,title:_.trim(),content:j.trim(),is_pinned:C,pinned_at:C?new Date().toISOString():null});if(B)throw B;he.success("Announcement created")}c(!1),D(),E()}catch(B){console.error("Error saving announcement:",B),he.error("Failed to save announcement")}finally{y(!1)}},O=async()=>{if(m)try{const{error:B}=await U.from("brokerage_announcements").delete().eq("id",m);if(B)throw B;he.success("Announcement deleted"),E()}catch(B){console.error("Error deleting announcement:",B),he.error("Failed to delete announcement")}finally{f(null)}};return i?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(fh,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:e.jsx("div",{className:"h-20 bg-muted rounded"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(fh,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(q,{size:"sm",onClick:()=>R(),className:"gap-1",children:[e.jsx(Ys,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Pe,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:n.map(B=>{var K,Z,Q,W;return e.jsx("div",{className:`p-4 rounded-lg border ${B.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:[B.is_pinned&&e.jsx(lS,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:B.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:B.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(Wn,{className:"h-5 w-5",children:[e.jsx(Xa,{src:((K=B.author)==null?void 0:K.avatar_url)||void 0}),e.jsx(Kn,{className:"text-[10px]",children:((Q=(Z=B.author)==null?void 0:Z.name)==null?void 0:Q.charAt(0))||"?"})]}),e.jsx("span",{children:(W=B.author)==null?void 0:W.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:As(new Date(B.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>R(B),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>f(B.id),children:e.jsx(zr,{className:"h-4 w-4"})})]})]})},B.id)})})})]}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",value:_,onChange:B=>b(B.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"content",children:"Content"}),e.jsx(pr,{id:"content",value:j,onChange:B=>N(B.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(Rr,{id:"pinned",checked:C,onCheckedChange:A}),e.jsxs(ce,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(lS,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(q,{onClick:F,disabled:x,children:x?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(el,{open:!!m,onOpenChange:()=>f(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete Announcement"}),e.jsx(Ho,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:O,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function YFs({brokerageId:s,canManage:t=!1}){const{startImpersonation:r,isLoading:n}=Rxe(),{user:a}=Cs(),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,u]=k.useState(""),[m,f]=k.useState(new Set);k.useEffect(()=>{(async()=>{try{const{data:_,error:b}=await U.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(b)throw b;if(l(_||[]),_&&_.length>0){const j=_.map(C=>C.id),{data:N}=await U.from("agent_assistant_assignments").select("agent_id").in("agent_id",j);N&&f(new Set(N.map(C=>C.agent_id)))}}catch(_){console.error("Error fetching agents:",_)}finally{c(!1)}})()},[s]);const x=i.filter(y=>{var _,b;return y.name.toLowerCase().includes(d.toLowerCase())||y.email.toLowerCase().includes(d.toLowerCase())||((_=y.title)==null?void 0:_.toLowerCase().includes(d.toLowerCase()))||((b=y.areas_served)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(y=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},y))})})]}):e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Dr,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:d,onChange:y=>u(y.target.value),className:"pl-9"})]})]}),e.jsx(Pe,{children:x.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:x.map(y=>e.jsx(ZFs,{agent:y,hasAssistant:m.has(y.id),canImpersonate:t&&y.id!==(a==null?void 0:a.id),onImpersonate:()=>r(y.id,"/my-brokerage"),impersonationLoading:n},y.id))})})]})}function ZFs({agent:s,hasAssistant:t,canImpersonate:r,onImpersonate:n,impersonationLoading:a}){const i=s.name.split(" ").map(l=>l[0]).join("").toUpperCase().slice(0,2);return e.jsxs("div",{className:"group relative bg-card border rounded-xl p-4 hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex flex-col items-center text-center mb-3",children:[e.jsxs(Wn,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(Xa,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(Kn,{className:"text-lg bg-primary/10 text-primary",children:i})]}),e.jsx("h3",{className:"font-semibold text-sm leading-tight",children:s.name}),s.title&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:s.title}),t&&e.jsx(Xe,{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(Ma,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.areas_served})]}),s.years_experience&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[s.years_experience," ",s.years_experience===1?"year":"years"," experience"]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[r&&e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:n,disabled:a,children:e.jsx(RE,{className:"h-4 w-4"})})}),e.jsxs(Sc,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(q,{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(Mn,{className:"h-4 w-4"})})}),e.jsx(q,{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(Ks,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx(q,{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(Yf,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(q,{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(gu,{className:"h-4 w-4"})})})]})]})}function XFs({brokerageId:s}){const[t,r]=k.useState([]),[n,a]=k.useState(!0);if(k.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await U.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),a(!1);return}const u=c.map(_=>_.id),{data:m,error:f}=await U.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(f)throw f;const x=new Map(c.map(_=>[_.id,_])),y=(m||[]).filter(_=>_.total_points>0).map(_=>{const b=x.get(_.user_id);return{user_id:_.user_id,total_points:_.total_points,name:(b==null?void 0:b.name)||"Unknown",avatar_url:(b==null?void 0:b.avatar_url)||null}});r(y)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),n)return e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(wo,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:[1,2,3].map(o=>e.jsx("div",{className:"h-12 bg-muted rounded"},o))})})]});const i=o=>o===1?"text-yellow-500":o===2?"text-gray-400":o===3?"text-amber-600":"text-muted-foreground",l=o=>o<=3?e.jsx(c2,{className:zt("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(wo,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Pe,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No points earned yet. Attend events to earn points!"}):e.jsx("div",{className:"space-y-2",children:t.slice(0,10).map((o,c)=>{const d=o.name.split(" ").map(m=>m[0]).join("").toUpperCase().slice(0,2),u=c+1;return e.jsxs("div",{className:zt("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(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:o.avatar_url||void 0}),e.jsx(Kn,{className:"text-xs",children:d})]}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:o.name}),e.jsxs("span",{className:"text-sm font-semibold text-primary",children:[o.total_points.toLocaleString()," pts"]})]},o.user_id)})})})]})}function QFs({brokerageId:s}){const t=qr(),[r,n]=k.useState([]),[a,i]=k.useState(!0);k.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await U.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),i(!1);return}const u=c.map(_=>_.id),m=new Map(c.map(_=>[_.id,_])),{data:f,error:x}=await U.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(x)throw x;const y=(f||[]).map(_=>({id:_.id,slug:_.slug,property_address:_.property_address,city:_.city,price:_.price,property_type:_.property_type,agent_id:_.agent_id,agent:m.get(_.agent_id)||null,photos:_.listing_photos||[]}));n(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(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[1,2].map(o=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-32 bg-muted rounded-lg"})},o))})})]}):e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Pe,{children:[r.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Pn,{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(q,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Your First Listing"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:r.map(o=>e.jsxs("div",{onClick:()=>window.open(`https://listings.relevelup.com/${o.slug||o.id}`,"_blank"),className:"group cursor-pointer border rounded-lg overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"relative h-24 bg-muted",children:[o.photos&&o.photos.length>0?e.jsx("img",{src:o.photos[0].photo_url,alt:o.property_address||"Listing",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Pn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),r.length>0&&e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(un,{className:"h-3 w-3 ml-1"})]})]})]})}function JFs(){const{user:s,isAdmin:t,isBrokerageManager:r}=Cs(),n=qr(),[a,i]=k.useState(!0),[l,o]=k.useState(null),[c,d]=k.useState(""),[u,m]=k.useState(0),[f,x]=k.useState(!1),[y,_]=k.useState(!1);return k.useEffect(()=>{(async()=>{if(s)try{const{data:j}=await U.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:N}=await U.from("brokerages").select("name").eq("id",j.brokerage_id).maybeSingle();N&&d(N.name);const{count:C}=await U.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",j.brokerage_id);if(m(C||0),t)x(!0),_(!0);else if(r){const{data:A}=await U.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",j.brokerage_id).maybeSingle();x(!!A),_(!!A)}}catch(j){console.error("Error fetching brokerage info:",j)}finally{i(!1)}})()},[s,t,r]),a?e.jsx(ws,{title:"My Brokerage",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):l?e.jsx(ws,{title:c||"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 rounded-lg px-4 py-2",children:[e.jsx(Dr,{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(q,{variant:"outline",onClick:()=>n("/brokerage-content"),children:[e.jsx(vm,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(q,{onClick:()=>n(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(KFs,{brokerageId:l,canManage:f}),e.jsx(YFs,{brokerageId:l,canManage:f}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(XFs,{brokerageId:l}),e.jsx(QFs,{brokerageId:l})]})]})}):e.jsx(ws,{title:"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ga,{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 e7s(s){if(!s)return null;try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}function t7s(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 zGe={video:{icon:Al,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:En,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Ul,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:vn,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:dl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function s7s({item:s,canManage:t}){const[r,n]=k.useState(!1),[a,i]=k.useState(null),l=NQt(),o=qr(),c=zGe[s.content_type]||zGe.link,d=c.icon,u=k.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?e7s(s.url):null,[s]);k.useEffect(()=>{u||!s.url||s.content_type!=="video"||!t7s(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 m=u||a,f=()=>{o(`/brokerage-content/${s.id}`)},x=async()=>{try{await l.mutateAsync(s.id),he.success("Content deleted")}catch{he.error("Failed to delete")}n(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:f,children:[m?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:m,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs(Xe,{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(Xe,{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:["📅 ",As(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",As(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,onClick:y=>y.stopPropagation(),children:e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Fy,{className:"h-4 w-4"})})}),e.jsx(Sd,{align:"end",children:e.jsxs(ti,{onClick:y=>{y.stopPropagation(),n(!0)},className:"text-destructive",children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(el,{open:r,onOpenChange:n,children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete Content"}),e.jsxs(Ho,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:x,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function r7s(s){try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}const BGe=[{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 n7s({brokerageId:s,categories:t}){var je;const{user:r}=Cs(),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,u]=k.useState("📁"),[m,f]=k.useState(!1);k.useRef(null);const[x,y]=k.useState("video"),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState(""),[E,D]=k.useState(""),[R,F]=k.useState(""),[O,B]=k.useState(""),[K,Z]=k.useState(""),Q=jQt(),W=kQt(s),te=SQt(),ne=CQt(s),ae=()=>{y("video"),b(""),N(""),A(""),D(""),F(""),B(""),Z("")},ue=async(xe,Ee)=>{var Oe;const Me=(Oe=xe.target.files)==null?void 0:Oe[0];if(Me){f(!0);try{const Ie=Me.name.split(".").pop(),ze=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Ie}`,{error:Ve}=await U.storage.from("brokerage-content").upload(ze,Me);if(Ve)throw Ve;const{data:{publicUrl:Le}}=U.storage.from("brokerage-content").getPublicUrl(ze);Ee==="file"?(D(Le),x==="graphic"&&!R&&F(Le)):F(Le),he.success("File uploaded")}catch(Ie){he.error(Ie.message||"Upload failed")}finally{f(!1)}}},me=async()=>{if(!_.trim()){he.error("Title is required");return}if(r)try{await Q.mutateAsync({brokerage_id:s,category_id:K||null,content_type:x,title:_.trim(),description:j.trim()||null,url:C.trim()||null,file_url:E.trim()||null,thumbnail_url:R.trim()||null,event_date:O?new Date(O).toISOString():null,created_by:r.id}),he.success("Content added!"),ae(),a(!1)}catch(xe){he.error(xe.message||"Failed to add content")}},de=async()=>{if(o.trim())try{await W.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),he.success("Category created")}catch(xe){he.error(xe.message||"Failed to create category")}},fe=async()=>{try{await ne.mutateAsync(),he.success("Default categories created")}catch{he.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(vs,{open:n,onOpenChange:a,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{children:"Content Type"}),e.jsxs(Ds,{value:x,onValueChange:y,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:BGe.map(xe=>e.jsx(lt,{value:xe.value,children:xe.label},xe.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(je=BGe.find(xe=>xe.value===x))==null?void 0:je.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Category"}),e.jsxs(Ds,{value:K,onValueChange:Z,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select category (optional)"})}),e.jsx(Ls,{children:t.map(xe=>e.jsxs(lt,{value:xe.id,children:[xe.icon," ",xe.name]},xe.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Title *"}),e.jsx(Ne,{value:_,onChange:xe=>b(xe.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{value:j,onChange:xe=>N(xe.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(x)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:x==="video"?"Video URL":x==="graphic"?"Canva / Image URL":x==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(Ne,{value:C,onChange:xe=>{const Ee=xe.target.value;if(A(Ee),x==="video"&&!R){const Me=r7s(Ee);Me&&F(Me)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(x)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:x==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"file",accept:x==="pdf"?".pdf,.doc,.docx":"image/*",onChange:xe=>ue(xe,"file"),disabled:m}),m&&e.jsx(ls,{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(ce,{children:"Thumbnail Image (optional)"}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:xe=>ue(xe,"thumbnail"),disabled:m}),R&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:R,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>F(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx($r,{className:"h-3 w-3"})})]})]}),x==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Event Date & Time"}),e.jsx(Ne,{type:"datetime-local",value:O,onChange:xe=>B(xe.target.value)})]}),e.jsxs(q,{onClick:me,disabled:Q.isPending||!_.trim(),className:"w-full",children:[Q.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(vs,{open:i,onOpenChange:l,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{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(q,{variant:"outline",size:"sm",onClick:fe,disabled:ne.isPending,children:[ne.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(xe=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[xe.icon," ",xe.name]}),!xe.is_default&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await te.mutateAsync(xe.id),he.success("Category deleted")},children:e.jsx($r,{className:"h-4 w-4"})})]},xe.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(Ne,{value:d,onChange:xe=>u(xe.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(Ne,{value:o,onChange:xe=>c(xe.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:xe=>xe.key==="Enter"&&de()}),e.jsx(q,{size:"sm",onClick:de,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function a7s(){const{user:s,isAdmin:t,isBrokerageManager:r}=Cs(),[n,a]=k.useState(!0),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,u]=k.useState(!1),[m,f]=k.useState(null),[x,y]=k.useState("");k.useEffect(()=>{(async()=>{if(s)try{const{data:A}=await U.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 U.from("brokerages").select("name").eq("id",A.brokerage_id).maybeSingle();if(E&&c(E.name),t)u(!0);else if(r){const{data:D}=await U.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",A.brokerage_id).maybeSingle();u(!!D)}}catch(A){console.error("Error fetching brokerage info:",A)}finally{a(!1)}})()},[s,t,r]);const{data:_=[]}=bQt(i),{data:b=[],isLoading:j}=_Qt(i,m),N=k.useMemo(()=>{if(!x.trim())return b;const C=x.toLowerCase();return b.filter(A=>{var E;return A.title.toLowerCase().includes(C)||((E=A.description)==null?void 0:E.toLowerCase().includes(C))||A.content_type.toLowerCase().includes(C)})},[b,x]);return n?e.jsx(ws,{title:"Brokerage Content",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):i?e.jsx(ws,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(n7s,{brokerageId:i,categories:_}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search content...",value:x,onChange:C=>y(C.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(q,{variant:m===null?"default":"outline",size:"sm",onClick:()=>f(null),children:"All"}),_.map(C=>e.jsxs(q,{variant:m===C.id?"default":"outline",size:"sm",onClick:()=>f(C.id),children:[e.jsx("span",{className:"mr-1",children:C.icon}),C.name]},C.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"})}):N.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Kf,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:x.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:x.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:N.map(C=>e.jsx(s7s,{item:C,canManage:d},C.id))})]})}):e.jsx(ws,{title:"Brokerage Content",description:"Content Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ga,{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 $Ge={video:{icon:Al,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:En,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Ul,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:vn,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:dl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function i7s(s){try{const t=new URL(s),r=t.hostname.replace("www.","");if(t.pathname==="/playlist"){const n=t.searchParams.get("list");if(n)return`https://www.youtube.com/embed/videoseries?list=${n}`}if(r==="youtube.com"||r==="m.youtube.com"){const n=t.searchParams.get("v");if(n){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${n}`;return a&&(i+=`?list=${a}`),i}}if(r==="youtu.be"){const n=t.pathname.slice(1);if(n){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${n}`;return a&&(i+=`?list=${a}`),i}}if(r==="youtube.com"&&t.pathname.startsWith("/embed/"))return s}catch{}return null}function o7s(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function l7s(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function c7s(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function d7s(){const{contentId:s}=xo(),{data:t,isLoading:r}=pt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await U.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(r)return e.jsx(ws,{title:"Brokerage Content",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!t)return e.jsx(ws,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ga,{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(q,{asChild:!0,className:"mt-4",children:e.jsx(Vn,{to:"/brokerage-content",children:"Back to Content"})})]})});const n=$Ge[t.content_type]||$Ge.link,a=n.icon,i=t.url||t.file_url,l=i&&o7s(i)?i7s(i):null,o=i&&l7s(i)?c7s(i):null,c=l||o;return e.jsx(ws,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(q,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Vn,{to:"/brokerage-content",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Xe,{variant:"secondary",className:`text-xs px-2 py-0.5 ${n.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),n.label]}),t.category&&e.jsxs(Xe,{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 ",As(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("div",{className:"relative w-full bg-black",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:c,className:"absolute top-0 left-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:t.title})})}),t.content_type==="graphic"&&t.file_url&&!c&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("img",{src:t.file_url,alt:t.title,className:"w-full max-h-[600px] object-contain bg-muted"})}),!c&&t.content_type!=="graphic"&&t.thumbnail_url&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("img",{src:t.thumbnail_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),t.description&&e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})})}),t.content_type==="event"&&t.event_date&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(vn,{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:As(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(q,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(q,{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(un,{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 Lpe={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 u7s(s="open"){const{user:t}=Cs();return pt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let r=U.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")r=r.eq("status","open");else if(s==="mine")r=r.eq("requester_user_id",t.id);else if(s==="filled")r=r.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await U.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];r=r.in("id",l)}const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})}function h7s(s){return pt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function m7s(s){return pt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function f7s(){const s=is(),{user:t,brokerageId:r}=Cs();return Mt({mutationFn:async n=>{if(!t||!r)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await U.from("brokerage_help_requests").insert({...n,brokerage_id:r,requester_user_id:t.id}).select().single();if(i)throw i;try{await U.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function p7s(){const s=is(),{user:t}=Cs();return Mt({mutationFn:async({request_id:r,note:n})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await U.from("brokerage_help_claims").insert({request_id:r,claimant_user_id:t.id,note:n}).select().single();if(i)throw i;return a},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function x7s(){const s=is();return Mt({mutationFn:async({claim_id:t,request_id:r,claimant_user_id:n})=>{const{error:a}=await U.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await U.from("brokerage_help_requests").update({status:"filled",assigned_user_id:n}).eq("id",r);if(i)throw i;try{await U.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function g7s(){const s=is();return Mt({mutationFn:async({claim_id:t})=>{const{error:r}=await U.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]})}})}function y7s(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",r]})}})}function v7s(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",r]})}})}function b7s(){const{user:s,brokerageId:t}=Cs(),r=is(),n=pt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await U.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=Mt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await U.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...n,setEmailEnabled:a.mutate,isSaving:a.isPending}}function _7s(s,t){if(!s)return null;const r=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),n=r(s,{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});if(t){const a=r(t,{hour:"numeric",minute:"2-digit"});return`${n} – ${a} ET`}return`${n} ET`}function w7s(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 j7s({req:s,onClick:t}){var i;const r=Lpe[s.request_type],n=_7s(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(ke,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Pe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[r.emoji," ",r.label]}),s.status!=="open"&&e.jsx(Xe,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground group-hover:translate-x-0.5 transition"})]}),e.jsx("h3",{className:"font-semibold text-base mb-2 line-clamp-2",children:s.title}),e.jsxs("div",{className:"space-y-1.5 text-sm text-muted-foreground",children:[n&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:n})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{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(Xl,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:w7s(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 N7s(){var c;const s=qr(),{brokerageId:t}=Cs(),[r,n]=k.useState("open"),{data:a=[],isLoading:i}=u7s(r),l=b7s(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(ws,{title:"Help Board",description:"Ask a teammate to cover an open house, showing, or shift.",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx(ta,{value:r,onValueChange:d=>n(d),children:e.jsxs(ea,{children:[e.jsx(rs,{value:"open",children:"Open"}),e.jsx(rs,{value:"mine",children:"My Posts"}),e.jsx(rs,{value:"my_claims",children:"My Claims"}),e.jsx(rs,{value:"filled",children:"Filled"})]})}),e.jsxs(q,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Pe,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(ym,{className:"h-4 w-4 text-primary"}):e.jsx(b_,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{id:"email-notif",checked:o,disabled:l.isLoading||l.isSaving,onCheckedChange:d=>l.setEmailEnabled(d)})]})}),i?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(p1,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"font-medium",children:"Nothing here yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:r==="open"?"No open requests right now — be the first to post one!":"Check back later."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:a.map(d=>e.jsx(j7s,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(ws,{title:"Help Board",description:"Brokerage Help Board",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(p1,{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 k7s(){const s=qr(),{toast:t}=Ba(),r=f7s(),[n,a]=k.useState("open_house"),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState(""),[E,D]=k.useState(""),[R,F]=k.useState(""),[O,B]=k.useState("goodwill"),[K,Z]=k.useState(""),[Q,W]=k.useState(""),te=n==="open_house"||n==="showing_coverage",ne=n!=="general",ae=(me,de)=>!me||!de?null:`${me}T${de}:00`,ue=async me=>{if(me.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const de=ae(d,m),fe=ae(d,x);await r.mutateAsync({request_type:n,title:i.trim(),description:o.trim()||null,event_start_at:de,event_end_at:fe,address:te&&_.trim()||null,city:te&&j.trim()||null,state:te&&C.trim()||null,zip:te&&E.trim()||null,mls_number:R.trim()||null,compensation_type:O,compensation_amount:K?Number(K):null,compensation_notes:Q.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(de){t({title:"Could not post",description:(de==null?void 0:de.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(ws,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:ue,children:e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(Lpe).map(me=>{const de=Lpe[me],fe=me===n;return e.jsxs("button",{type:"button",onClick:()=>a(me),className:`text-left p-3 rounded-lg border-2 transition ${fe?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:de.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:de.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:de.description})]},me)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:i,onChange:me=>l(me.target.value),placeholder:n==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"description",children:"Details"}),e.jsx(pr,{id:"description",value:o,onChange:me=>c(me.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),ne&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"date",children:"Date"}),e.jsx(Ne,{id:"date",type:"date",value:d,onChange:me=>u(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"start",children:"Start"}),e.jsx(Ne,{id:"start",type:"time",value:m,onChange:me=>f(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"end",children:"End"}),e.jsx(Ne,{id:"end",type:"time",value:x,onChange:me=>y(me.target.value)})]})]}),te&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"address",children:"Address"}),e.jsx(Ne,{id:"address",value:_,onChange:me=>b(me.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(ce,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:j,onChange:me=>N(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:C,onChange:me=>A(me.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(ce,{htmlFor:"zip",children:"Zip"}),e.jsx(Ne,{id:"zip",value:E,onChange:me=>D(me.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(Ne,{id:"mls",value:R,onChange:me=>F(me.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(ce,{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(me=>{const de=O===me.val;return e.jsxs("button",{type:"button",onClick:()=>B(me.val),className:`text-left p-3 rounded-lg border-2 transition ${de?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:me.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:me.sub})]},me.val)})}),O!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"amount",children:O==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(Ne,{id:"amount",type:"number",min:"0",step:O==="referral_percent"?"1":"5",value:K,onChange:me=>Z(me.target.value),placeholder:O==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(Ne,{id:"comp-notes",value:Q,onChange:me=>W(me.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(q,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:r.isPending,className:"gap-2",children:[r.isPending&&e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function S7s(s,t){if(!s)return null;const r=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),n=r(s,{weekday:"long",month:"long",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});return t?`${n} – ${r(t,{hour:"numeric",minute:"2-digit"})} ET`:`${n} ET`}function Xwe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function C7s(){var R,F,O,B,K,Z,Q,W;const{id:s}=xo(),t=qr(),{user:r}=Cs(),{toast:n}=Ba(),{data:a,isLoading:i}=h7s(s),{data:l=[]}=m7s(s),o=p7s(),c=x7s(),d=g7s(),u=y7s(),m=v7s(),[f,x]=k.useState("");if(i)return e.jsx(ws,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(ws,{title:"Not Found",description:"",children:[e.jsxs(q,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Aa,{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=Lpe[a.request_type],_=S7s(a.event_start_at,a.event_end_at),b=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),j=(r==null?void 0:r.id)===a.requester_user_id,N=l.find(te=>te.claimant_user_id===(r==null?void 0:r.id)),C=l.find(te=>te.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)",D=async()=>{if(!f.trim()){n({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:f.trim()}),n({title:"You're in!",description:"The requester will review and pick someone."}),x("")}catch(te){n({title:"Could not submit",description:te==null?void 0:te.message,variant:"destructive"})}};return e.jsx(ws,{title:a.title,description:`${y.emoji} ${y.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to board"]}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Xe,{variant:"secondary",children:[y.emoji," ",y.label]}),e.jsx(Xe,{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(Wn,{className:"h-7 w-7",children:[e.jsx(Xa,{src:((R=a.requester)==null?void 0:R.avatar_url)||void 0}),e.jsx(Kn,{children:Xwe((F=a.requester)==null?void 0:F.name)})]}),e.jsx("span",{children:((O=a.requester)==null?void 0:O.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(jn,{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:_})]})]}),b&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Ma,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Where"}),e.jsx("div",{children:b})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Xl,{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(sS,{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&&!N&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(pr,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:f,onChange:te=>x(te.target.value),rows:3,maxLength:400}),e.jsxs(q,{onClick:D,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(ls,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!j&&N&&e.jsx(ke,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx(la,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",N.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[N.status==="pending"&&"Waiting for the requester to pick.",N.status==="accepted"&&"You're confirmed — see contact info below.",N.status==="declined"&&"They went with someone else this time."]})]})]})}),C&&(j||C.claimant_user_id===(r==null?void 0:r.id))&&e.jsx(ke,{className:"border-primary/30",children:e.jsxs(Pe,{className:"p-6",children:[e.jsx("h3",{className:"font-semibold mb-3",children:"Confirmed coverage"}),e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsxs(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:((B=C.claimant)==null?void 0:B.avatar_url)||void 0}),e.jsx(Kn,{children:Xwe((K=C.claimant)==null?void 0:K.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(Z=C.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:[((Q=C.claimant)==null?void 0:Q.email)&&e.jsxs("a",{href:`mailto:${C.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Ks,{className:"h-4 w-4"})," ",C.claimant.email]}),((W=C.claimant)==null?void 0:W.phone)&&e.jsxs("a",{href:`tel:${C.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Mn,{className:"h-4 w-4"})," ",C.claimant.phone]})]})]})}),j&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-3",children:[e.jsxs("h3",{className:"font-semibold",children:["Interested agents (",l.length,")"]}),l.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No claims yet. Hang tight — your teammates were just notified."}),l.map(te=>{var ne,ae,ue,me,de;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:((ne=te.claimant)==null?void 0:ne.avatar_url)||void 0}),e.jsx(Kn,{children:Xwe((ae=te.claimant)==null?void 0:ae.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:((ue=te.claimant)==null?void 0:ue.name)||"Teammate"}),e.jsx(Xe,{variant:"outline",className:"capitalize text-xs",children:te.status})]}),te.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',te.note,'"']}),te.status==="pending"&&A&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(q,{size:"sm",onClick:()=>c.mutate({claim_id:te.id,request_id:a.id,claimant_user_id:te.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(la,{className:"h-3.5 w-3.5"})," Pick ",((de=(me=te.claimant)==null?void 0:me.name)==null?void 0:de.split(" ")[0])||"them"]}),e.jsxs(q,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:te.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx($r,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},te.id)}),j&&A&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(q,{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(q,{size:"sm",onClick:()=>m.mutate(a.id),disabled:m.isPending,children:"Mark complete"})})]})})]})})}function F0t({onSelect:s,maxHeight:t="460px"}){const[r,n]=k.useState(""),[a,i]=k.useState("all"),{data:l=[],isLoading:o}=pt({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:m}=await U.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(m)throw m;return u||[]}}),c=k.useMemo(()=>{const u=new Set;return l.forEach(m=>u.add(m.category||"general")),["all",...Array.from(u).sort()]},[l]),d=k.useMemo(()=>{const u=r.trim().toLowerCase();return l.filter(m=>a!=="all"&&m.category!==a?!1:u?m.title.toLowerCase().includes(u)||(m.description||"").toLowerCase().includes(u)||(m.tags||[]).some(f=>f.toLowerCase().includes(u)):!0)},[l,r,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{value:r,onChange:u=>n(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(ui,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ls,{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(zo,{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(Xe,{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(fa,{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 T7s=[{key:"search",label:"Search for Properties",icon:_n,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Mn,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:Ks,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:vn,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:Pn,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:Xl,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:Ma,defaultText:"See Open Houses",placeholder:"https://your-website.com/open-houses",helper:"Link to your open houses page"},{key:"forward",label:"Forward to a Friend",icon:Ec,defaultText:"Forward to a Friend",isForward:!0,placeholder:"Optional landing page (or leave blank)",helper:"Opens recipient's email pre-filled — leave blank to default"},{key:"custom",label:"Custom Button",icon:Bc,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function UGe(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function E7s(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function z0t({html:s,onChange:t}){const{user:r}=Cs(),n=k.useRef(null),a=k.useRef(""),i=k.useRef(t);i.current=t;const[l,o]=k.useState("desktop"),c=k.useRef(null),[d,u]=k.useState(!1),[m,f]=k.useState(""),[x,y]=k.useState(""),_=k.useRef(null),b=()=>{var ht;const gt=(ht=n.current)==null?void 0:ht.contentDocument,Ut=gt==null?void 0:gt.getSelection();Ut&&Ut.rangeCount>0&&(gt!=null&>.body.contains(Ut.anchorNode))&&(_.current=Ut.getRangeAt(0).cloneRange())},j=()=>{var ts;const gt=c.current,Ut=(ts=n.current)==null?void 0:ts.contentDocument;if(!gt||!Ut)return;let ht=m.trim();ht&&!/^(https?:|mailto:|tel:|#|\/)/i.test(ht)&&(ht="https://"+ht),gt.setAttribute("href",ht),gt.setAttribute("target","_blank");const Jt=x.trim();Jt&&Jt!==(gt.textContent||"").trim()&&(gt.textContent=Jt);const Ms=` `+Ut.documentElement.outerHTML;a.current=Ms,i.current(Ms),u(!1)};k.useEffect(()=>{var ht,Jt;const gt=n.current;if(!gt||a.current===s)return;const Ut=()=>{const Ms=gt.contentDocument;if(!Ms)return;Ms.open(),Ms.write(s||""),Ms.close(),a.current=s;const ts=Ms.body;if(!ts)return;ts.setAttribute("contenteditable","true"),ts.style.outline="none",ts.style.minHeight="400px",ts.style.cursor="text";const Xs=()=>{const $s=` `+Ms.documentElement.outerHTML;a.current=$s,i.current($s)};ts.addEventListener("input",Xs),ts.addEventListener("blur",Xs),ts.addEventListener("mouseup",b),ts.addEventListener("keyup",b),Ms.addEventListener("selectionchange",b);const js=$s=>{var Yr;const Js=$s.target,or=Js==null?void 0:Js.closest("a");if(or){if($s.metaKey||$s.ctrlKey||$s.shiftKey)return;$s.preventDefault(),$s.stopPropagation(),c.current=or,f(or.getAttribute("href")||""),y((or.textContent||"").trim()),u(!0);return}const Er=Ms.getSelection();if(!Er)return;const Sr=(Yr=Ms.caretRangeFromPoint)==null?void 0:Yr.call(Ms,$s.clientX,$s.clientY),Gr=Sr==null?void 0:Sr.startContainer;if(Gr&&Gr.nodeType===Node.TEXT_NODE){const Fn=Gr.textContent||"",sa=Sr.startOffset,gs=Fn.lastIndexOf("[",sa),mi=Fn.indexOf("]",sa);if(gs!==-1&&mi!==-1&&mi>gs){const In=Ms.createRange();In.setStart(Gr,gs),In.setEnd(Gr,mi+1),Er.removeAllRanges(),Er.addRange(In),_.current=In.cloneRange()}}};ts.addEventListener("click",js,!0)};((ht=gt.contentDocument)==null?void 0:ht.readyState)==="complete"||(Jt=gt.contentDocument)!=null&&Jt.body?Ut():gt.addEventListener("load",Ut,{once:!0})},[s]);const N=(gt,Ut)=>{var Ms;const ht=(Ms=n.current)==null?void 0:Ms.contentDocument;if(!ht)return;ht.body.focus(),ht.execCommand(gt,!1,Ut);const Jt=` `+ht.documentElement.outerHTML;a.current=Jt,i.current(Jt)},C=()=>{const gt=window.prompt("Enter URL (https://...)");gt&&N("createLink",gt)},A=(gt,Ut)=>{var Ms;const ht=(Ms=n.current)==null?void 0:Ms.contentDocument;if(!ht)return;if(ht.body.focus(),Ut==="cursor"&&_.current&&ht.body.contains(_.current.startContainer)){const ts=ht.getSelection();if(ts){ts.removeAllRanges(),ts.addRange(_.current),ht.execCommand("insertHTML",!1,gt);const Xs=` `+ht.documentElement.outerHTML;a.current=Xs,i.current(Xs);return}}Ut==="top"?ht.body.insertAdjacentHTML("afterbegin",gt):ht.body.insertAdjacentHTML("beforeend",gt);const Jt=` `+ht.documentElement.outerHTML;a.current=Jt,i.current(Jt)},[E,D]=k.useState(!1),[R,F]=k.useState(null),[O,B]=k.useState(""),[K,Z]=k.useState(""),[Q,W]=k.useState("#406E71"),[te,ne]=k.useState("cursor"),ae=gt=>{F(gt),B(gt.defaultText),Z(""),D(!0)},ue=()=>{if(!R)return;const gt=K.trim();if(!R.isForward&&!gt)return;let Ut=gt;if(R.isForward){const ts=gt||"",Xs=encodeURIComponent("You should see this newsletter"),js=encodeURIComponent(ts?`I thought you'd like this — take a look: ${ts} `:`I thought you'd like this newsletter — take a look! `);Ut=`mailto:?subject=${Xs}&body=${js}`}else R.hrefPrefix==="tel:"?Ut="tel:"+gt.replace(/[^0-9+]/g,""):R.hrefPrefix==="mailto:"?Ut="mailto:"+gt:/^https?:\/\//i.test(gt)||(Ut="https://"+gt);const ht=(O||R.defaultText).replace(/[<>]/g,""),Jt=Q||"#406E71",Ms=`
${ht}

 

`;A(Ms,te),D(!1)},[me,de]=k.useState(!1),[fe,je]=k.useState(""),[xe,Ee]=k.useState(""),[Me,Oe]=k.useState(""),[Ie,ze]=k.useState("cursor"),Ve=(()=>{if(xe.trim())return xe.trim();const gt=UGe(fe);return gt?`https://i.ytimg.com/vi/${gt}/hqdefault.jpg`:""})(),Le=()=>{je(""),Ee(""),Oe(""),de(!0)},$e=()=>{const gt=fe.trim();if(!gt)return;let Ut=gt;/^https?:\/\//i.test(Ut)||(Ut="https://"+Ut);const ht=UGe(Ut),Jt=ht?null:E7s(Ut);let Ms=xe.trim();!Ms&&ht&&(Ms=`https://i.ytimg.com/vi/${ht}/hqdefault.jpg`),!Ms&&Jt&&(Ms=`https://vumbnail.com/${Jt}.jpg`),Ms||(Ms="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const ts=(Me||"Watch the video").replace(/[<>]/g,""),Xs=`
${ts}
▶ ${ts}

 

`.trim();A(Xs,Ie),de(!1)},[ve,Qe]=k.useState(!1),[we,nt]=k.useState(""),[Se,Ge]=k.useState(""),[We,Ce]=k.useState("full"),[qe,et]=k.useState("cursor"),[Ze,rt]=k.useState(!1),ct=k.useRef(null),vt=()=>{nt(""),Ge(""),Ce("full"),Qe(!0)},kt=async gt=>{var Ut;if(!r){he.error("You must be signed in to upload images");return}if(gt.size>10*1024*1024){he.error("Image must be under 10MB");return}rt(!0);try{const ht=((Ut=gt.name.split(".").pop())==null?void 0:Ut.toLowerCase())||"png",Jt=`${r.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${ht}`,{error:Ms}=await U.storage.from("email-assets").upload(Jt,gt,{cacheControl:"3600",upsert:!1,contentType:gt.type});if(Ms)throw Ms;const{data:ts}=U.storage.from("email-assets").getPublicUrl(Jt);nt(ts.publicUrl),he.success("Image uploaded")}catch(ht){he.error(ht.message||"Upload failed")}finally{rt(!1)}},St=()=>{if(!we.trim())return;const gt=(Se||"").replace(/[<>"]/g,""),Ut=We==="half"?280:560,ht=`
${gt}

 

`.trim();A(ht,qe),Qe(!1)},{data:Yt,isLoading:es}=pt({queryKey:["newsletter-editor-videos",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&me,queryFn:async()=>{const{data:gt,error:Ut}=await U.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",r.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(Ut)throw Ut;return gt||[]}}),zs=gt=>{gt.share_token&&(je(`https://video.relevelup.com/share/video/${gt.share_token}`),Ee(`https://video.relevelup.com/thumb/${gt.share_token}`),Oe(gt.title||"Watch the video"))},sr=l==="mobile"?390:"100%",ms=l==="mobile"?390:void 0;return e.jsxs("div",{className:"rounded-md border overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b bg-muted/40 px-2 py-1.5 flex-wrap",children:[e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>N("bold"),title:"Bold",children:e.jsx(Jk,{className:"h-3.5 w-3.5"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>N("italic"),title:"Italic",children:e.jsx(rS,{className:"h-3.5 w-3.5"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>N("underline"),title:"Underline",children:e.jsx(cP,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>N("insertUnorderedList"),title:"Bullet list",children:e.jsx(Zf,{className:"h-3.5 w-3.5"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>N("insertOrderedList"),title:"Numbered list",children:e.jsx(T1,{className:"h-3.5 w-3.5"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:C,title:"Insert link",children:e.jsx(tl,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>N("undo"),title:"Undo",children:e.jsx(hS,{className:"h-3.5 w-3.5"})}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>N("redo"),title:"Redo",children:e.jsx(cS,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(Bc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(Sd,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(S9,{children:"Insert a call-to-action"}),e.jsx(z_,{}),T7s.map(gt=>{const Ut=gt.icon;return e.jsxs(ti,{onClick:()=>ae(gt),children:[e.jsx(Ut,{className:"h-4 w-4 mr-2"}),gt.label]},gt.key)})]})]}),e.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:vt,children:[e.jsx(zo,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Le,children:[e.jsx(bn,{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(SP,{type:"single",value:l,onValueChange:gt=>gt&&o(gt),size:"sm",className:"h-7",children:[e.jsx(tA,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(k_,{className:"h-3.5 w-3.5"})}),e.jsx(tA,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(yg,{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(Bc,{className:"h-3 w-3"}),e.jsxs("span",{children:["Tip: click where you want to add an image, video, or button — or click a ",e.jsx("em",{children:"[ bracketed placeholder ]"})," to replace it. Click any button/link to edit where it goes."]})]}),e.jsx("div",{className:"bg-muted/20 flex justify-center overflow-auto",style:{padding:l==="mobile"?16:0},children:e.jsx("iframe",{ref:n,title:"Newsletter visual editor",className:"bg-white",style:{width:sr,maxWidth:ms,height:480,border:l==="mobile"?"1px solid hsl(var(--border))":"none",borderRadius:l==="mobile"?12:0,boxShadow:l==="mobile"?"0 4px 12px rgba(0,0,0,0.08)":"none"}})}),e.jsx(vs,{open:d,onOpenChange:u,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(Ne,{id:"link-edit-text",value:x,onChange:gt=>y(gt.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(Ne,{id:"link-edit-href",value:m,onChange:gt=>f(gt.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(fn,{children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(q,{type:"button",onClick:j,disabled:!m.trim(),children:"Save link"})]})]})}),e.jsx(vs,{open:E,onOpenChange:D,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(_s,{children:e.jsxs(bs,{children:["Insert ",(R==null?void 0:R.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"cta-text",children:"Button text"}),e.jsx(Ne,{id:"cta-text",value:O,onChange:gt=>B(gt.target.value),placeholder:R==null?void 0:R.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"cta-value",children:R==null?void 0:R.helper}),e.jsx(Ne,{id:"cta-value",value:K,onChange:gt=>Z(gt.target.value),placeholder:R==null?void 0:R.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{id:"cta-color",type:"color",value:Q,onChange:gt=>W(gt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(Ne,{value:Q,onChange:gt=>W(gt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Position"}),e.jsxs(u_,{value:te,onValueChange:gt=>ne(gt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"cursor",id:"cta-cursor"}),e.jsxs(ce,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Bc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"top",id:"cta-top"}),e.jsxs(ce,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(qu,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"bottom",id:"cta-bottom"}),e.jsxs(ce,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(gm,{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:Q,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:O||(R==null?void 0:R.defaultText)})})]}),e.jsxs(fn,{children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(q,{type:"button",onClick:ue,disabled:!(R!=null&&R.isForward)&&!K.trim(),children:"Insert Button"})]})]})}),e.jsx(vs,{open:me,onOpenChange:de,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Insert Video Block"})}),e.jsxs(ta,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ea,{className:"grid w-full grid-cols-3",children:[e.jsx(rs,{value:"library",children:"My Library"}),e.jsx(rs,{value:"url",children:"From URL"}),e.jsx(rs,{value:"record",children:"Record New"})]}),e.jsxs(fs,{value:"library",className:"space-y-3 mt-2",children:[es?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(ls,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!Yt||Yt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(bn,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),e.jsx("p",{children:"No videos in your library yet."}),e.jsx("p",{className:"text-xs mt-1",children:'Record one in the "Record New" tab.'})]}):e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-72 overflow-y-auto pr-1",children:Yt.map(gt=>{const Ut=fe.includes(gt.share_token||"___"),ht=gt.share_token?`https://video.relevelup.com/thumb/${gt.share_token}`:gt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>zs(gt),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${Ut?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ht?e.jsx("img",{src:ht,alt:gt.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(bn,{className:"h-6 w-6"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-black/60 w-9 h-9 flex items-center justify-center",children:e.jsx(Al,{className:"h-4 w-4 text-white fill-white"})})})]}),e.jsx("div",{className:"p-1.5",children:e.jsx("p",{className:"text-xs font-medium line-clamp-1",children:gt.title||"Untitled"})})]},gt.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(Ne,{id:"vid-title-lib",value:Me,onChange:gt=>Oe(gt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(fs,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(Ne,{id:"vid-url",value:fe,onChange:gt=>je(gt.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(ce,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(Ne,{id:"vid-title",value:Me,onChange:gt=>Oe(gt.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(Ne,{id:"vid-thumb",value:xe,onChange:gt=>Ee(gt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(fs,{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(bn,{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(q,{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(ce,{children:"Position"}),e.jsxs(u_,{value:Ie,onValueChange:gt=>ze(gt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"cursor",id:"vid-cursor"}),e.jsxs(ce,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Bc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"top",id:"vid-top"}),e.jsxs(ce,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(qu,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"bottom",id:"vid-bottom"}),e.jsxs(ce,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(gm,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Ve&&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:Ve,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:gt=>{gt.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(fn,{children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>de(!1),children:"Cancel"}),e.jsx(q,{type:"button",onClick:$e,disabled:!fe.trim(),children:"Insert Video"})]})]})}),e.jsx(vs,{open:ve,onOpenChange:Qe,children:e.jsxs(ys,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Insert Image"})}),e.jsxs(ta,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ea,{className:"grid w-full grid-cols-3",children:[e.jsx(rs,{value:"library",children:"Library"}),e.jsx(rs,{value:"upload",children:"Upload"}),e.jsx(rs,{value:"url",children:"From URL"})]}),e.jsx(fs,{value:"library",className:"mt-2",children:e.jsx(F0t,{maxHeight:"380px",onSelect:gt=>{nt(gt.image_url),Se||Ge(gt.title)}})}),e.jsxs(fs,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:ct,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:gt=>{var ht;const Ut=(ht=gt.target.files)==null?void 0:ht[0];Ut&&kt(Ut),gt.target.value=""}}),we?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:we,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(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>nt(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var gt;return(gt=ct.current)==null?void 0:gt.click()},disabled:Ze,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:Ze?e.jsxs(e.Fragment,{children:[e.jsx(ls,{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(ka,{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(fs,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"img-url",children:"Image URL"}),e.jsx(Ne,{id:"img-url",value:we,onChange:gt=>nt(gt.target.value),placeholder:"https://..."})]}),we&&/^https?:\/\//i.test(we)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:we,alt:"Preview",className:"w-full max-h-48 object-contain",onError:gt=>{gt.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(ce,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(Ne,{id:"img-alt",value:Se,onChange:gt=>Ge(gt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Size"}),e.jsxs(u_,{value:We,onValueChange:gt=>Ce(gt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"full",id:"img-full"}),e.jsx(ce,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"half",id:"img-half"}),e.jsx(ce,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Position"}),e.jsxs(u_,{value:qe,onValueChange:gt=>et(gt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"cursor",id:"img-cursor"}),e.jsxs(ce,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Bc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"top",id:"img-top"}),e.jsxs(ce,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(qu,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Du,{value:"bottom",id:"img-bottom"}),e.jsxs(ce,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(gm,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>Qe(!1),children:"Cancel"}),e.jsx(q,{type:"button",onClick:St,disabled:!we.trim()||Ze,children:"Insert Image"})]})]})})]})}const qGe="newsletter-content",A7s="inline-images";function M7s(s,t){const r=atob(s),n=new Array(r.length);for(let a=0;a{const{data:F}=await U.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return F}}),E=(A==null?void 0:A.role)==="team_leader",D=(A==null?void 0:A.team_id)??null;k.useEffect(()=>{s&&(d((r==null?void 0:r.title)??""),m((r==null?void 0:r.description)??""),x((r==null?void 0:r.html_content)??L7s()),_((r==null?void 0:r.is_template)??!1),j((r==null?void 0:r.share_scope)??"private"))},[s,r]);const R=async()=>{if(a){if(!c.trim()){he.error("Please enter a title");return}if(!f.trim()){he.error("Newsletter content is empty");return}C(!0);try{const F=await I7s(f);F!==f&&x(F);const O={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:F,is_template:y,share_scope:b,shared_team_id:b==="team"?D:null,shared_brokerage_id:b==="brokerage"?o:null};if(b==="team"&&!D){he.error("You must be a team leader to share with a team"),C(!1);return}if(b==="brokerage"&&!l){he.error("Only brokerage managers can share to a brokerage"),C(!1);return}if(b==="global"&&!i){he.error("Only admins can publish global starter templates"),C(!1);return}let B;if(r!=null&&r.id?{error:B}=await U.from("agent_custom_newsletters").update(O).eq("id",r.id):{error:B}=await U.from("agent_custom_newsletters").insert(O),B)throw B;he.success(r!=null&&r.id?"Saved":"Newsletter created"),n==null||n(),t(!1)}catch(F){he.error(F.message||"Failed to save")}finally{C(!1)}}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(_s,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(bs,{children:r!=null&&r.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"acn-title",children:"Title *"}),e.jsx(Ne,{id:"acn-title",value:c,onChange:F=>d(F.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(Ne,{id:"acn-desc",value:u,onChange:F=>m(F.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(Rr,{id:"acn-template",checked:y,onCheckedChange:_}),e.jsx(ce,{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(ce,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(u_,{value:b,onValueChange:F=>j(F),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Du,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(ce,{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(Du,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(ce,{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(Du,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(ce,{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(Du,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(ce,{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(ce,{className:"mb-2 block",children:"Content"}),e.jsx(z0t,{html:f,onChange:x})]})]}),e.jsxs(fn,{className:"px-6 py-3 border-t",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),disabled:N,children:"Cancel"}),e.jsxs(q,{onClick:R,disabled:N,children:[N?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),r!=null&&r.id?"Save Changes":"Create"]})]})]})})}function L7s(){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 tD(){var a;const{user:s}=Cs(),{data:t,isLoading:r}=pt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,u,m,f;const[i,l]=await Promise.all([U.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),U.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((m=o==null?void 0:o.display_name)==null?void 0:m.trim())||((f=c==null?void 0:c.name)==null?void 0:f.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:r,settings:t}}function pye(){const{user:s}=Cs();return pt({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,r]=await Promise.all([U.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),U.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),n=t.data||[],a=n.filter(l=>l.status==="verified"),i=n.filter(l=>l.status==="pending");return{hasVerifiedSes:a.length>0,hasPendingSes:i.length>0,hasAnySender:n.length>0,hasGmail:!!r.data,verifiedEmails:a.map(l=>l.email),pendingEmails:i.map(l=>l.email)}}})}function xye({open:s,onOpenChange:t,hasPending:r,pendingEmails:n}){const a=qr();return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-amber-500/10 text-amber-600 flex items-center justify-center",children:e.jsx(go,{className:"h-5 w-5"})}),e.jsx(bs,{children:"Verify your sending email first"})]}),e.jsx(an,{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.`})]}),r&&n&&n.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(jn,{className:"h-4 w-4"})," Waiting for you to click Amazon's link"]}),n.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ks,{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(fn,{className:"gap-2 sm:gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs(q,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(un,{className:"h-4 w-4 mr-1"}),r?"Manage senders":"Verify my email"]})]})]})})}function sD(){const s=xa();return pt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(r)throw r;return t},enabled:!!s})}function D7s(s){return pt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(r)throw r;return t},enabled:!!s})}function a6e(){const s=is(),t=xa();return Mt({mutationFn:async({name:r,color:n})=>{const{data:a,error:i}=await U.from("contact_custom_tags").insert({owner_user_id:t,name:r.trim(),color:n||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function R7s(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("contact_custom_tags").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function O7s(){const s=is();return Mt({mutationFn:async({id:t,name:r,color:n})=>{const a={};r!==void 0&&(a.name=r.trim()),n!==void 0&&(a.color=n);const{error:i}=await U.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function B0t(){const s=is();return Mt({mutationFn:async({contactId:t,tagId:r})=>{const{error:n}=await U.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:r});if(n)throw n},onSuccess:(t,{contactId:r})=>{s.invalidateQueries({queryKey:["contact-custom-tags",r]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function F7s(){const s=is();return Mt({mutationFn:async({contactId:t,tagId:r})=>{const{error:n}=await U.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",r);if(n)throw n},onSuccess:(t,{contactId:r})=>{s.invalidateQueries({queryKey:["contact-custom-tags",r]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function gye(){const s=xa();return pt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(r)throw r;return t},enabled:!!s})}function $0t(){const{user:s}=Cs();return pt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function z7s(){const s=is(),{user:t}=Cs();return Mt({mutationFn:async({name:r,filters:n,sort_by:a})=>{const{data:i,error:l}=await U.from("contact_smart_lists").insert({owner_user_id:t.id,name:r,filters:n,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Dn({title:"Smart filter saved"})},onError:r=>{Dn({title:"Error saving smart filter",description:r.message,variant:"destructive"})}})}function B7s(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("contact_smart_lists").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Dn({title:"Smart filter deleted"})}})}const VGe=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function HGe(s,t,r,n){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c={first_name:t.first_name||"there",last_name:t.last_name||"",name:a,full_name:a,email:t.email||"",phone:t.phone||"",address:t.address||"",city:t.city||"",state:t.state||"",zip:t.zip||t.zip_code||"",agent_name:(r==null?void 0:r.name)||"",agent_email:(r==null?void 0:r.email)||"",agent_phone:(r==null?void 0:r.phone)||"",agent_title:(r==null?void 0:r.title)||"",brokerage:n||"",current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(d,u)=>c[u]??`{{${u}}}`)}function $7s(s,t,r,n){const a=t.trim()?`
${VGe(t).replace(/\n/g,"
")}
`:"",i=r.trim()?`
${VGe(r).replace(/\n/g,"
")}
`:"",l=n?`
${n}
`:"";return`${a} ${s} ${i} ${l}`}function U7s(s,t,r){const n=(s==null?void 0:s.name)||"Your Agent",a=(s==null?void 0:s.email)||"",i=(t==null?void 0:t.name)||"",l=[t==null?void 0:t.city,t==null?void 0:t.state].filter(Boolean).join(", "),o=a?`mailto:${encodeURIComponent(a)}?subject=${encodeURIComponent("Unsubscribe")}&body=${encodeURIComponent(`Please remove ${r} from your newsletter list.`)}`:"#";return`
${n}${i?" • "+i:""}
${l?`
${l}
`:""}
You're receiving this because ${n} thought you'd find it useful. Unsubscribe
`}const q7s=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function V7s(s,t){const r=[],n=s.trim();if(n.length>0){n.length<10&&r.push("Subject line is very short — most opened subjects are 30-60 characters."),n.length>90&&r.push("Subject line is very long — many inboxes truncate after 60-70 characters.");const l=n.replace(/[^A-Za-z]/g,""),o=n.replace(/[^A-Z]/g,"");l.length>6&&o.length/l.length>.6&&r.push("Subject is mostly uppercase — this often triggers spam filters."),(n.match(/!/g)||[]).length>=3&&r.push("Too many exclamation marks in the subject.");const d=n.toLowerCase(),u=q7s.filter(m=>d.includes(m));u.length>0&&r.push(`Subject contains spam-trigger words: ${u.slice(0,3).join(", ")}.`)}const a=t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return a.length<40&&r.push("Email body is very short — add more text so it doesn't look like a spam blast."),(t.match(/0&&a.length<80&&r.push("Email is mostly images with little text — many spam filters block these."),r}function i6e({open:s,onOpenChange:t,newsletterId:r,newsletterTitle:n,htmlCode:a}){const{user:i}=Cs();Cm();const{isReady:l,settings:o}=tD(),{data:c}=pye(),[d,u]=k.useState(!1),m=xa(),{data:f}=pt({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:ps}=await U.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature").eq("id",i.id).maybeSingle();return ps}}),[x,y]=k.useState("visual"),[_,b]=k.useState("all"),[j,N]=k.useState(""),[C,A]=k.useState(""),[E,D]=k.useState(""),[R,F]=k.useState(""),[O,B]=k.useState(!0),[K,Z]=k.useState([]),[Q,W]=k.useState(null),[te,ne]=k.useState(new Set),[ae,ue]=k.useState(""),[me,de]=k.useState(!1),[fe,je]=k.useState(!1),[xe,Ee]=k.useState(!1),[Me,Oe]=k.useState({sent:0,failed:0,total:0,currentName:""}),[Ie,ze]=k.useState(!0),[Ve,Le]=k.useState(!1),[$e,ve]=k.useState([]),[Qe,we]=k.useState(!1),[nt,Se]=k.useState(new Set),[Ge,We]=k.useState("now"),[Ce,qe]=k.useState(""),{data:et=[]}=sD(),{data:Ze=[]}=gye(),{data:rt=[]}=$0t(),{data:ct=[],isLoading:vt}=pt({queryKey:["newsletter-send-contacts",m],enabled:!!m&&s,queryFn:async()=>{const ps=[];let Or=0;const Qr=1e3;for(;;){const{data:Tn,error:Qt}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",m).not("email","is",null).neq("email","").order("first_name").range(Or,Or+Qr-1);if(Qt)throw Qt;if(!Tn||Tn.length===0||(ps.push(...Tn),Tn.length{const{data:ps}=await U.from("ses_suppressed_emails").select("email");return(ps||[]).map(Or=>Or.email.toLowerCase())}}),{data:St}=pt({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:ps}=await U.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(ps!=null&&ps.brokerage_id))return null;const{data:Or}=await U.from("brokerages").select("name, city, state").eq("id",ps.brokerage_id).maybeSingle();return Or}}),{data:Yt}=pt({queryKey:["newsletter-active-lead-site",m],enabled:!!m&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!m)return null;const{data:ps}=await U.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",m).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return ps}}),es=!!(Yt!=null&&Yt.mls_provider_id),zs=(Yt==null?void 0:Yt.mls_agent_id)||(Yt==null?void 0:Yt.mls_agent_key)||null,{data:sr=[],isLoading:ms}=pt({queryKey:["newsletter-agent-listings",m,zs],enabled:!!m&&!!zs&&Qe,staleTime:60*1e3,queryFn:async()=>{if(!zs)return[];const{data:ps}=await U.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",zs).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return ps||[]}}),{data:gt=[],isLoading:Ut}=pt({queryKey:["newsletter-exchange-listings",m],enabled:!!m&&Qe,staleTime:60*1e3,queryFn:async()=>{const{data:ps}=await U.from("listings").select("id, slug, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, created_at").eq("agent_id",m).in("status",["active","coming_soon","office_exclusive","pre_market"]).order("created_at",{ascending:!1}).limit(30),Or=ps||[];if(Or.length===0)return[];const Qr=Or.map(Ke=>Ke.id),{data:Tn}=await U.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Qr),Qt=new Map,Re=new Map;for(const Ke of Tn||[])Ke.is_primary&&!Qt.has(Ke.listing_id)&&Qt.set(Ke.listing_id,Ke.photo_url),Re.has(Ke.listing_id)||Re.set(Ke.listing_id,Ke.photo_url);return Or.map(Ke=>({...Ke,_photo:Qt.get(Ke.id)||Re.get(Ke.id)||""}))}}),{data:ht=!1}=pt({queryKey:["newsletter-exchange-listings-exists",m],enabled:!!m&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:ps}=await U.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",m).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(ps||0)>0}}),Jt=k.useMemo(()=>{const ps=new Set(kt);return ct.filter(Or=>Or.email&&Or.email.includes("@")&&!ps.has(Or.email.toLowerCase()))},[ct,kt]),Ms=k.useMemo(()=>{if(K.length===0)return null;const ps=new Set;for(const Or of Ze)K.includes(Or.tag_id)&&ps.add(Or.contact_id);return ps},[Ze,K]),ts=k.useMemo(()=>rt.find(ps=>ps.id===Q)||null,[rt,Q]),Xs=k.useMemo(()=>{var ps;if(_==="all")return Jt;if(_==="tags")return Ms?Jt.filter(Or=>Ms.has(Or.id)):[];if(_==="smartlists"){if(!ts)return[];const Or=(((ps=ts.filters)==null?void 0:ps.search)||"").toLowerCase().trim();return Or?Jt.filter(Qr=>`${Qr.first_name||""} ${Qr.last_name||""}`.toLowerCase().includes(Or)||(Qr.email||"").toLowerCase().includes(Or)):Jt}return Jt.filter(Or=>te.has(Or.id))},[_,Jt,Ms,ts,te]),js=k.useMemo(()=>{if(!ae.trim())return Jt;const ps=ae.toLowerCase();return Jt.filter(Or=>`${Or.first_name||""} ${Or.last_name||""}`.toLowerCase().includes(ps))},[Jt,ae]);k.useEffect(()=>{s&&(N(""),A(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),D(`As always, reach out anytime if I can help. Talk soon!`),F(a||""),y("light"),b("all"),Z([]),W(null),ne(new Set),ue(""),de(!1),B(!0),ze(!0),ve([]),We("now"),qe(""),Oe({sent:0,failed:0,total:0,currentName:""}))},[s,n,a]);const $s=l,Js=!!(j.trim()&&$s&&Xs.length>0&&!fe),or=ps=>{const Or=x==="advanced"||x==="visual"?R:a,Qr=O&&(f!=null&&f.email_signature)?f.email_signature:null;let Tn;return x==="light"?Tn=$7s(Or,C,E,Qr):Tn=Qr?`${Or}
${Qr}
`:Or,Ie&&(Tn+=U7s(f??null,St??null,ps.email)),HGe(Tn,ps,f??null,(St==null?void 0:St.name)??null)},Er=k.useMemo(()=>or({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[x,C,E,R,a,O,f,Ie,St]),Sr=k.useMemo(()=>V7s(j,x==="advanced"||x==="visual"?R:a),[j,x,R,a]),Gr=async()=>{Le(!0),ve([]);try{const ps=x==="advanced"||x==="visual"?R:a,{data:Or,error:Qr}=await U.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:n,bodyHtml:ps,currentSubject:j}});if(Qr)throw Qr;const Tn=Or==null?void 0:Or.subjects;if(!Array.isArray(Tn)||Tn.length===0)throw new Error("No subjects returned");ve(Tn)}catch(ps){const Or=(ps==null?void 0:ps.message)||"Failed to generate subjects";Or.includes("credits exhausted")||Or.includes("402")?he.error("AI credits exhausted. Please add credits to your workspace."):Or.includes("Rate limit")||Or.includes("429")?he.error("Rate limit hit — try again in a moment."):he.error(Or)}finally{Le(!1)}},Yr=ps=>ps?"$"+Number(ps).toLocaleString("en-US"):"",Fn=()=>{var Re,Ke;if(nt.size===0){he.error("Pick at least one listing first.");return}const ps=(Yt==null?void 0:Yt.subdomain_slug)||"",Or=ps?`https://${ps}.relevelup.com`:"https://relevelup.com",Qr=[];for(const at of sr){const Nt=`mls:${at.listing_key}`;if(!nt.has(Nt))continue;const Ft=Array.isArray(at.photos)&&at.photos.length>0?typeof at.photos[0]=="string"?at.photos[0]:((Re=at.photos[0])==null?void 0:Re.MediaURL)||((Ke=at.photos[0])==null?void 0:Ke.url)||"":"",qt=at.bedrooms?`${at.bedrooms} bd`:"",cs=at.bathrooms_total?`${at.bathrooms_total} ba`:"",it=at.living_area?`${Number(at.living_area).toLocaleString()} sqft`:"";Qr.push({url:`${Or}/listings/${at.listing_key}`,photo:Ft,price:Yr(at.list_price),addr:`${at.address||""}${at.city?", "+at.city:""}`,stats:[qt,cs,it].filter(Boolean).join(" • ")})}for(const at of gt){const Nt=`ex:${at.id}`;if(!nt.has(Nt))continue;const Ft=at.bedrooms?`${at.bedrooms} bd`:"",qt=at.bathrooms?`${at.bathrooms} ba`:"",cs=at.square_footage?`${Number(at.square_footage).toLocaleString()} sqft`:"";Qr.push({url:`https://listings.relevelup.com/${at.slug||at.id}`,photo:at._photo||"",price:Yr(at.price),addr:`${at.property_address||""}${at.city?", "+at.city:""}`,stats:[Ft,qt,cs].filter(Boolean).join(" • ")})}const Qt=`

Featured Listings

${Qr.map(at=>`
${at.photo?`${at.addr}`:""}
${at.price}
${at.addr}
${at.stats}
`.trim()).join(` `)}
`.trim();F(at=>(at||a||"")+` `+Qt),y("visual"),Se(new Set),we(!1),he.success(`Added ${Qr.length} listing${Qr.length===1?"":"s"} to your newsletter.`)},sa=()=>or({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}}"),gs=()=>HGe(j,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},f??null,(St==null?void 0:St.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(Js){if(Ge==="later"){if(!Ce){he.error("Pick a date and time to schedule.");return}const ps=new Date(Ce).getTime();if(Number.isNaN(ps)||ps{if(!(!Js||!i)){Ee(!1),je(!0),Oe({sent:0,failed:0,total:Xs.length,currentName:"Preparing campaign…"});try{const Or=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Qr=sa(),Tn=gs(),Qt=Ge==="later",{data:Re,error:Ke}=await U.from("email_campaigns").insert({user_id:m||i.id,name:`Newsletter: ${n}`,subject:Tn,body_html:Qr,from_email:Or,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Xs.length,status:Qt?"scheduled":"draft",scheduled_at:Qt?new Date(Ce).toISOString():null}).select("id").single();if(Ke)throw Ke;Oe(Nt=>({...Nt,currentName:"Adding recipients…"}));const at=Xs.map(Nt=>({campaign_id:Re.id,contact_id:Nt.id,email:Nt.email,name:[Nt.first_name,Nt.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Nt=0;Nt({...cs,sent:Math.min(Nt+Ft.length,at.length)}))}if(Qt){const{error:Nt}=await U.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:Re.id}});if(Nt)throw Nt;he.success(`Newsletter scheduled for ${new Date(Ce).toLocaleString()}.`)}else{const{error:Nt}=await U.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:Re.id}});if(Nt)throw Nt;he.success(`Sending to ${Xs.length} contact${Xs.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(ps){console.error("Newsletter send failed:",ps),he.error(`Failed to send: ${ps.message||"Unknown error"}`)}finally{je(!1)}}},Br=ps=>{ne(Or=>{const Qr=new Set(Or);return Qr.has(ps)?Qr.delete(ps):Qr.add(ps),Qr})};return e.jsxs(vs,{open:s,onOpenChange:ps=>!fe&&t(ps),children:[e.jsxs(ys,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(hn,{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(go,{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(q,{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(ce,{children:"Subject"}),e.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:Gr,disabled:Ve,title:"Generate subject lines with AI",children:[Ve?e.jsx(ls,{className:"h-3 w-3 animate-spin"}):e.jsx(Ir,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(Ne,{value:j,onChange:ps=>N(ps.target.value),placeholder:"Newsletter subject"}),$e.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:"}),$e.map((ps,Or)=>e.jsxs("button",{type:"button",onClick:()=>{N(ps),ve([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(Ir,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),ps]},Or))]}),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}}"})]})]}),Sr.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(YF,{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:Sr.map((ps,Or)=>e.jsx("li",{children:ps},Or))})]}),(es||ht)&&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(Pn,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:es&&ht?"Pick from your live MLS listings or your Listing Exchange listings.":es?"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(q,{type:"button",size:"sm",variant:"outline",onClick:()=>we(!0),children:"Choose listings"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Editing"}),e.jsxs(ta,{value:x,onValueChange:ps=>y(ps),children:[e.jsxs(ea,{className:"grid grid-cols-3 w-full",children:[e.jsxs(rs,{value:"visual",children:[e.jsx(p0,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(rs,{value:"light",children:[e.jsx(En,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(rs,{value:"advanced",children:[e.jsx(Rj,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(fs,{value:"visual",className:"mt-3",children:e.jsx(z0t,{html:R,onChange:F})}),e.jsxs(fs,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(pr,{value:C,onChange:ps=>A(ps.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(pr,{value:E,onChange:ps=>D(ps.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(fs,{value:"advanced",className:"mt-3",children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(pr,{value:R,onChange:ps=>F(ps.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:f!=null&&f.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(Rr,{checked:O&&!!(f!=null&&f.email_signature),disabled:!(f!=null&&f.email_signature),onCheckedChange:B})]}),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(Rr,{checked:Ie,onCheckedChange:ze})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Recipients"}),e.jsxs(ta,{value:_,onValueChange:ps=>b(ps),children:[e.jsxs(ea,{className:"grid grid-cols-4 w-full",children:[e.jsxs(rs,{value:"all",children:[e.jsx(Dr,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(rs,{value:"tags",children:[e.jsx(Fh,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(rs,{value:"smartlists",children:[e.jsx(MF,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(rs,{value:"individual",children:[e.jsx(qi,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(fs,{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:Jt.length})," contact",Jt.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(fs,{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(ui,{className:"h-40 rounded-lg border p-2",children:et.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."}):et.map(ps=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Ri,{checked:K.includes(ps.id),onCheckedChange:Or=>Z(Qr=>Or?[...Qr,ps.id]:Qr.filter(Tn=>Tn!==ps.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:ps.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:ps.name})]},ps.id))})]}),e.jsxs(fs,{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(ui,{className:"h-40 rounded-lg border p-2",children:rt.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):rt.map(ps=>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:Q===ps.id,onChange:()=>W(ps.id)}),e.jsx("span",{className:"text-sm",children:ps.name})]},ps.id))})]}),e.jsxs(fs,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(Ne,{placeholder:"Search contacts...",value:ae,onChange:ps=>ue(ps.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[te.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>ne(new Set),children:"Clear"})]}),e.jsxs(ui,{className:"h-48 rounded-lg border p-2",children:[vt&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!vt&&js.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),js.slice(0,200).map(ps=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Ri,{checked:te.has(ps.id),onCheckedChange:()=>Br(ps.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[ps.first_name," ",ps.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ps.email})]})]},ps.id)),js.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(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(qn,{className:"h-3 w-3"})," ",Xs.length," recipient",Xs.length===1?"":"s"]}),$s&&e.jsxs(Xe,{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(ce,{children:"Preview"}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>de(ps=>!ps),children:me?e.jsxs(e.Fragment,{children:[e.jsx(Wf,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),me?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)."]})]})]}),fe&&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(ls,{className:"h-4 w-4 animate-spin"}),"Sending to ",Me.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[Me.sent+Me.failed," / ",Me.total]})]}),e.jsx(ki,{value:Me.total?(Me.sent+Me.failed)/Me.total*100:0}),Me.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[Me.failed," failed"]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(jn,{className:"h-4 w-4"})," When to send"]}),e.jsxs(u_,{value:Ge,onValueChange:ps=>We(ps),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Du,{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(Du,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Xy,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),Ge==="later"&&e.jsx(Ne,{type:"datetime-local",value:Ce,onChange:ps=>qe(ps.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(q,{variant:"outline",onClick:()=>t(!1),disabled:fe,children:"Cancel"}),e.jsx(q,{onClick:mi,disabled:!Js,children:fe?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):Ge==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Xy,{className:"h-4 w-4 mr-1"}),"Schedule for ",Xs.length]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Send to ",Xs.length]})})]})]})]})]}),e.jsx(el,{open:xe,onOpenChange:Ee,children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:Ge==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Ho,{children:[Ge==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',j,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Xs.length," contact",Xs.length===1?"":"s"]}),Ge==="later"&&Ce?` for ${new Date(Ce).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:In,children:Ge==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Xy,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Send to ",Xs.length]})})]})]})}),e.jsx(vs,{open:Qe,onOpenChange:we,children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 listings. They'll be added as an email-safe grid."}),(ms||Ut)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(ls,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!ms&&!Ut&&sr.length===0&>.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."}),sr.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:sr.map(ps=>{var Qt,Re;const Or=`mls:${ps.listing_key}`,Qr=nt.has(Or),Tn=Array.isArray(ps.photos)&&ps.photos.length>0?typeof ps.photos[0]=="string"?ps.photos[0]:((Qt=ps.photos[0])==null?void 0:Qt.MediaURL)||((Re=ps.photos[0])==null?void 0:Re.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Se(Ke=>{const at=new Set(Ke);return at.has(Or)?at.delete(Or):at.size<6?at.add(Or):he.error("Max 6 listings per newsletter"),at})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Qr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Tn&&e.jsx("img",{src:Tn,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:ps.list_price?`$${Number(ps.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:ps.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[ps.city,ps.state?`, ${ps.state}`:""]})]}),Qr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(qn,{className:"h-4 w-4"})})]},Or)})})]}),gt.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:gt.map(ps=>{const Or=`ex:${ps.id}`,Qr=nt.has(Or);return e.jsxs("button",{type:"button",onClick:()=>{Se(Tn=>{const Qt=new Set(Tn);return Qt.has(Or)?Qt.delete(Or):Qt.size<6?Qt.add(Or):he.error("Max 6 listings per newsletter"),Qt})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Qr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[ps._photo&&e.jsx("img",{src:ps._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:ps.price?`$${Number(ps.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:ps.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[ps.city,ps.state?`, ${ps.state}`:""]})]}),Qr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(qn,{className:"h-4 w-4"})})]},Or)})})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>we(!1),children:"Cancel"}),e.jsxs(q,{onClick:Fn,disabled:nt.size===0,children:["Insert ",nt.size>0?nt.size:""," listing",nt.size===1?"":"s"]})]})]})}),e.jsx(xye,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function H7s(){const{user:s}=Cs(),t=is(),[r,n]=k.useState("starters"),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState(null),[u,m]=k.useState(null),{data:f,isLoading:x}=pt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:R,error:F}=await U.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(F)throw F;return R||[]}}),y=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),_=(f==null?void 0:f.filter(R=>R.user_id===(s==null?void 0:s.id)&&!R.is_template))??[],b=(f==null?void 0:f.filter(R=>R.user_id===(s==null?void 0:s.id)&&R.is_template))??[],j=(f==null?void 0:f.filter(R=>R.user_id!==(s==null?void 0:s.id)&&R.is_template&&(R.share_scope==="team"||R.share_scope==="brokerage"||R.share_scope==="global")))??[],N=(f==null?void 0:f.filter(R=>R.share_scope==="global"&&R.is_template))??[],C=r==="starters"?N:r==="mine"?_:r==="templates"?b:j.filter(R=>R.share_scope!=="global"),A=async R=>{if(!s)return;const{error:F}=await U.from("agent_custom_newsletters").insert({user_id:s.id,title:`${R.title} (Copy)`,description:R.description,html_content:R.html_content,is_template:!1,share_scope:"private"});if(F){he.error(F.message);return}he.success('Duplicated to "My Newsletters"'),y(),n("mine")},E=async R=>{const{error:F}=await U.from("agent_custom_newsletters").delete().eq("id",R);if(F){he.error(F.message);return}he.success("Deleted"),m(null),y()},D=R=>R.share_scope==="global"?e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"}),"Starter"]}):R.share_scope==="brokerage"?e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ga,{className:"h-3 w-3"}),"Brokerage"]}):R.share_scope==="team"?e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Dr,{className:"h-3 w-3"}),"Team"]}):e.jsxs(Xe,{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(q,{variant:r==="starters"?"default":"outline",size:"sm",onClick:()=>n("starters"),className:"gap-1.5",children:[e.jsx(Ir,{className:"h-3.5 w-3.5"}),"Starter Templates (",N.length,")"]}),e.jsxs(q,{variant:r==="mine"?"default":"outline",size:"sm",onClick:()=>n("mine"),children:["My Newsletters (",_.length,")"]}),e.jsxs(q,{variant:r==="templates"?"default":"outline",size:"sm",onClick:()=>n("templates"),children:["My Templates (",b.length,")"]}),e.jsxs(q,{variant:r==="shared"?"default":"outline",size:"sm",onClick:()=>n("shared"),children:["Shared with Me (",j.filter(R=>R.share_scope!=="global").length,")"]})]}),e.jsxs(q,{onClick:()=>{o(null),i(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),x&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((R,F)=>e.jsx(dr,{className:"h-48 w-full"},F))}),r==="starters"&&!x&&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(Ir,{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.']})]}),!x&&C.length===0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(En,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),r==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),r==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),r==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),r==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!x&&C.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:C.map(R=>{const F=R.user_id===(s==null?void 0:s.id);return e.jsxs(ke,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[R.thumbnail_url?e.jsx("img",{src:R.thumbnail_url,alt:R.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full p-3 overflow-hidden pointer-events-none",dangerouslySetInnerHTML:{__html:`
${R.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[R.is_template&&e.jsx(Xe,{className:"bg-primary/90",children:"Template"}),D(R)]})]}),e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:R.title}),R.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:R.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",As(new Date(R.updated_at||R.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(q,{size:"sm",onClick:()=>d(R),className:"flex-1 min-w-[80px]",children:[e.jsx(hn,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),F?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:"sm",variant:"outline",onClick:()=>{o(R),i(!0)},children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>A(R),children:e.jsx(si,{className:"h-3.5 w-3.5"})}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>m(R.id),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]}):e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>A(R),children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},R.id)})}),e.jsx(P7s,{open:a,onOpenChange:i,initial:l,onSaved:y}),c&&e.jsx(i6e,{open:!!c,onOpenChange:R=>!R&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(el,{open:!!u,onOpenChange:R=>!R&&m(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete this newsletter?"}),e.jsx(Ho,{children:"This cannot be undone."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>u&&E(u),children:"Delete"})]})]})})]})}function G7s(){const s=qr(),[t,r]=k.useState(""),[n,a]=k.useState("grid"),[i,l]=k.useState(null),{data:o,isLoading:c}=pt({queryKey:["newsletters"],queryFn:async()=>{const{data:E,error:D}=await U.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(D)throw D;return E}}),{data:d}=pt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:E}=await U.from("newsletter_likes").select("newsletter_id");return E||[]}}),{data:u}=pt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:E}=await U.from("newsletter_comments").select("newsletter_id");return E||[]}}),{data:m}=pt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[E,D,R,F]=await Promise.all([U.from("newsletter_canva_links").select("newsletter_id"),U.from("newsletter_pdfs").select("newsletter_id"),U.from("newsletter_videos").select("newsletter_id"),U.from("newsletter_drive_links").select("newsletter_id")]);return{canva:E.data||[],pdfs:D.data||[],videos:R.data||[],drives:F.data||[]}}}),f=E=>(d==null?void 0:d.filter(D=>D.newsletter_id===E).length)||0,x=E=>(u==null?void 0:u.filter(D=>D.newsletter_id===E).length)||0,y=E=>{var D;return((D=m==null?void 0:m.canva)==null?void 0:D.filter(R=>R.newsletter_id===E).length)||0},_=E=>{var D;return((D=m==null?void 0:m.pdfs)==null?void 0:D.filter(R=>R.newsletter_id===E).length)||0},b=E=>{var D;return((D=m==null?void 0:m.videos)==null?void 0:D.filter(R=>R.newsletter_id===E).length)||0},j=E=>{var D;return((D=m==null?void 0:m.drives)==null?void 0:D.filter(R=>R.newsletter_id===E).length)||0},N=E=>y(E)+_(E)+b(E)+j(E),C=o==null?void 0:o.filter(E=>{var D;return E.title.toLowerCase().includes(t.toLowerCase())||((D=E.description)==null?void 0:D.toLowerCase().includes(t.toLowerCase()))}),A=E=>{s(`/newsletters/${E}`)};return e.jsx(ws,{title:"Newsletter Content",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Newsletter Content"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Monthly templates, plus newsletters you build yourself"})]}),e.jsxs(ta,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"custom",children:"Build & Send"}),e.jsx(rs,{value:"curated",children:"Curated Monthly"})]}),e.jsx(fs,{value:"custom",className:"mt-2",children:e.jsx(H7s,{})}),e.jsxs(fs,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search newsletters...",value:t,onChange:E=>r(E.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(q,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Ep,{className:"h-4 w-4"})}),e.jsx(q,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Zf,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(C==null?void 0:C.length)||0," item",(C==null?void 0:C.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,D)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-0",children:[e.jsx(dr,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(dr,{className:"h-5 w-3/4"}),e.jsx(dr,{className:"h-4 w-full"})]})]})},D))}),!c&&(C==null?void 0:C.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(En,{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(q,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!c&&C&&C.length>0&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-3",children:C.map(E=>{const D=N(E.id),R=y(E.id),F=_(E.id),O=b(E.id);return n==="grid"?e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(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(En,{className:"h-16 w-16"})})}),e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:E.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(vn,{className:"h-3 w-3"}),As(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,"")}),D>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[R>0&&e.jsxs(Xe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(dl,{className:"h-3 w-3"})," ",R," Template",R>1?"s":""]}),F>0&&e.jsxs(Xe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(li,{className:"h-3 w-3"})," ",F," PDF",F>1?"s":""]}),O>0&&e.jsxs(Xe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Al,{className:"h-3 w-3"})," ",O," Video",O>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(wm,{className:"h-3 w-3"})," ",f(E.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gc,{className:"h-3 w-3"})," ",x(E.id)]})]}),E.html_code&&e.jsxs(q,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:B=>{B.stopPropagation(),l(E)},children:[e.jsx(hn,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},E.id):e.jsx(ke,{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(En,{className:"h-10 w-10"})})}),e.jsxs(Pe,{className:"p-4 flex-1 flex flex-col justify-center gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:E.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(vn,{className:"h-3 w-3"}),As(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:[D>0&&e.jsxs("span",{children:[D," resource",D>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wm,{className:"h-3 w-3"})," ",f(E.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gc,{className:"h-3 w-3"})," ",x(E.id)]})]})]}),E.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(q,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:B=>{B.stopPropagation(),l(E)},children:[e.jsx(hn,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},E.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(i6e,{open:!!i,onOpenChange:E=>!E&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function W7s({rows:s}){if(!s||s.length===0)return null;const t=s.filter(r=>r.columns.some(n=>n.title||n.description||n.image_url));return t.length===0?null:e.jsx("div",{className:"space-y-6",children:t.map((r,n)=>{const a=r.columns.filter(i=>i.title||i.description||i.image_url);return a.length===0?null:e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:`repeat(${a.length}, minmax(0, 1fr))`},children:a.map((i,l)=>e.jsxs(ke,{className:"overflow-hidden border-border/50",children:[i.image_url&&e.jsx("img",{src:i.image_url,alt:i.title||"",className:"w-full h-40 object-cover"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[i.title&&e.jsx("h4",{className:"font-semibold text-foreground",children:i.title}),i.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:i.description})]})]},l))},n)})})}function K7s(){const{id:s}=xo(),t=qr(),{user:r}=Cs(),{toast:n}=Ba(),a=is(),{trackEngagement:i}=M8(),[l,o]=k.useState(""),[c,d]=k.useState(!1),{data:u,isLoading:m}=pt({queryKey:["newsletter",s],queryFn:async()=>{const{data:R,error:F}=await U.from("newsletter_content").select("*").eq("id",s).single();if(F)throw F;return R},enabled:!!s});k.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:f}=pt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:R}=await U.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:x}=pt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:R}=await U.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:y}=pt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:R}=await U.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:_}=pt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:R}=await U.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:b}=pt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:R}=await U.from("newsletter_likes").select("*").eq("newsletter_id",s);return R||[]},enabled:!!s}),{data:j}=pt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:R}=await U.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return R||[]},enabled:!!s}),N=b==null?void 0:b.some(R=>R.user_id===(r==null?void 0:r.id)),C=Mt({mutationFn:async()=>{N?await U.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",r==null?void 0:r.id):await U.from("newsletter_likes").insert({newsletter_id:s,user_id:r==null?void 0:r.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),A=Mt({mutationFn:async R=>{const{error:F}=await U.from("newsletter_comments").insert({newsletter_id:s,user_id:r==null?void 0:r.id,content:R});if(F)throw F},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),n({title:"Comment added"})}}),E=Mt({mutationFn:async R=>{const{error:F}=await U.from("newsletter_comments").delete().eq("id",R);if(F)throw F},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),n({title:"Comment deleted"})}}),D=R=>{if(R.includes("player.mediadelivery.net")||R.includes("iframe.mediadelivery.net")){const F=R.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(F)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${F[1]}/${F[2]}?autoplay=false`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}if(R.includes("youtube.com")||R.includes("youtu.be")){const F=R.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(F)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${F[1]}`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}return e.jsxs("a",{href:R,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Al,{className:"h-4 w-4"})," Watch Video"]})};return m?e.jsx(ws,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(dr,{className:"h-8 w-32"}),e.jsx(dr,{className:"h-64 w-full"}),e.jsx(dr,{className:"h-32 w-full"})]})}):u?e.jsx(ws,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(q,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(Aa,{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:As(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(W7s,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(L8,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(q,{variant:N?"default":"outline",size:"sm",onClick:()=>C.mutate(),children:[e.jsx(yi,{className:`h-4 w-4 mr-1 ${N?"fill-current":""}`}),(b==null?void 0:b.length)||0," ",(b==null?void 0:b.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs(q,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(i6e,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),_&&_.length>0&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Pe,{className:"space-y-2",children:_.map(R=>e.jsxs("a",{href:R.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(dl,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:R.title}),e.jsx(un,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},R.id))})]}),f&&f.length>0&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Pe,{className:"space-y-2",children:f.map(R=>e.jsxs("a",{href:R.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(un,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:R.title})]},R.id))})]}),x&&x.length>0&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Pe,{className:"space-y-2",children:x.map(R=>e.jsxs("a",{href:R.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(En,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:R.name}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground"})]},R.id))})]}),y&&y.length>0&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Videos"})}),e.jsx(Pe,{className:"space-y-6",children:y.map(R=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:R.title}),D(R.video_url)]},R.id))})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-lg",children:["Comments (",(j==null?void 0:j.length)||0,")"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(pr,{placeholder:"Write a comment...",value:l,onChange:R=>o(R.target.value),className:"flex-1"}),e.jsx(q,{onClick:()=>l.trim()&&A.mutate(l),disabled:!l.trim()||A.isPending,children:e.jsx(hn,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(R=>{var F,O,B;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wn,{className:"h-8 w-8",children:e.jsx(Kn,{children:((O=(F=R.profiles)==null?void 0:F.name)==null?void 0:O[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:((B=R.profiles)==null?void 0:B.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(R.created_at),"MMM d, yyyy")}),R.user_id===(r==null?void 0:r.id)&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>E.mutate(R.id),children:e.jsx(zr,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:R.content})]})]},R.id)})})]})]})]})}):e.jsx(ws,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx(q,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function Y7s({rows:s,onChange:t}){const[r,n]=k.useState(null),[a,i]=k.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=m=>{t(s.filter((f,x)=>x!==m))},c=(m,f,x,y)=>{const _=[...s];_[m]={..._[m],columns:_[m].columns.map((b,j)=>j===f?{...b,[x]:y}:b)},t(_)},d=async(m,f,x)=>{var b;const y=(b=x.target.files)==null?void 0:b[0];if(!y)return;const _=`${m}-${f}`;n(_);try{const j=`content-blocks/${Date.now()}-${y.name}`,{error:N}=await U.storage.from("newsletter-content").upload(j,y);if(!N){const{data:C}=U.storage.from("newsletter-content").getPublicUrl(j);c(m,f,"image_url",C.publicUrl)}}finally{n(null)}},u=(m,f)=>{c(m,f,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(Ys,{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((m,f)=>e.jsxs(ke,{className:"relative",children:[e.jsx(q,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>o(f),children:e.jsx($r,{className:"h-4 w-4"})}),e.jsxs(Pe,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",f+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:m.columns.map((x,y)=>{const _=`${f}-${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]}),x.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:x.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(q,{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(f,y),children:e.jsx($r,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(Ne,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${_}`,onChange:b=>d(f,y,b)}),e.jsx(q,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:r===_,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${_}`,className:"cursor-pointer",children:r===_?"...":e.jsxs(e.Fragment,{children:[e.jsx(zo,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:f,col:y}),children:[e.jsx(nS,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(Ne,{placeholder:"Title",value:x.title,onChange:b=>c(f,y,"title",b.target.value),className:"h-8 text-sm"}),e.jsx(pr,{placeholder:"Description",value:x.description,onChange:b=>c(f,y,"description",b.target.value),className:"text-sm min-h-[60px] resize-none"})]},y)})})]})]},f)),e.jsx(vs,{open:!!a,onOpenChange:m=>!m&&i(null),children:e.jsxs(ys,{className:"sm:max-w-2xl",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Choose a Graphic"})}),e.jsx(F0t,{onSelect:m=>{a&&(c(a.row,a.col,"image_url",m.image_url),i(null))}})]})})]})}function Z7s(){const{toast:s}=Ba(),t=is(),[r,n]=k.useState(!1),[a,i]=k.useState(null),[l,o]=k.useState({title:"",description:"",publish_date:As(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=k.useState(null),[u,m]=k.useState(null),[f,x]=k.useState([]),[y,_]=k.useState([]),[b,j]=k.useState([]),[N,C]=k.useState([]),[A,E]=k.useState([]),[D,R]=k.useState(""),[F,O]=k.useState([]),[B,K]=k.useState(!1),{data:Z,isLoading:Q}=pt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Ie,error:ze}=await U.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(ze)throw ze;return Ie}}),W=Mt({mutationFn:async Ie=>{const{data:ze,error:Ve}=await U.from("newsletter_content").insert({title:Ie.title,description:Ie.description||null,preview_image_url:Ie.preview_image_url,publish_date:Ie.publish_date,is_published:Ie.is_published,content_blocks:Ie.content_blocks,html_code:Ie.html_code}).select().single();if(Ve)throw Ve;return ze},onSuccess:async Ie=>{await ae(Ie.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Ie.is_published&&nxs(Ie.title,Ie.id),de()},onError:Ie=>{s({title:"Error creating newsletter",description:Ie.message,variant:"destructive"})}}),te=Mt({mutationFn:async Ie=>{const{error:ze}=await U.from("newsletter_content").update({title:Ie.title,description:Ie.description||null,preview_image_url:Ie.preview_image_url,publish_date:Ie.publish_date,is_published:Ie.is_published,content_blocks:Ie.content_blocks,html_code:Ie.html_code}).eq("id",Ie.id);if(ze)throw ze;return Ie.id},onSuccess:async Ie=>{await ae(Ie),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),de()},onError:Ie=>{s({title:"Error updating newsletter",description:Ie.message,variant:"destructive"})}}),ne=Mt({mutationFn:async Ie=>{const{error:ze}=await U.from("newsletter_content").delete().eq("id",Ie);if(ze)throw ze},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Ie=>{s({title:"Error deleting newsletter",description:Ie.message,variant:"destructive"})}}),ae=async Ie=>{await U.from("newsletter_drive_links").delete().eq("newsletter_id",Ie),await U.from("newsletter_pdfs").delete().eq("newsletter_id",Ie),await U.from("newsletter_videos").delete().eq("newsletter_id",Ie),await U.from("newsletter_canva_links").delete().eq("newsletter_id",Ie);for(const ze of F){const Ve=`${Ie}/${Date.now()}-${ze.file.name}`,{error:Le}=await U.storage.from("newsletter-content").upload(Ve,ze.file);if(!Le){const{data:$e}=U.storage.from("newsletter-content").getPublicUrl(Ve);y.push({name:ze.name,file_url:$e.publicUrl,file_size:ze.file.size,sort_order:y.length})}}f.length>0&&await U.from("newsletter_drive_links").insert(f.map((ze,Ve)=>({newsletter_id:Ie,title:ze.title,drive_url:ze.drive_url,sort_order:Ve}))),y.length>0&&await U.from("newsletter_pdfs").insert(y.map((ze,Ve)=>({newsletter_id:Ie,name:ze.name,file_url:ze.file_url,file_size:ze.file_size||null,sort_order:Ve}))),b.length>0&&await U.from("newsletter_videos").insert(b.map((ze,Ve)=>({newsletter_id:Ie,title:ze.title,video_url:ze.video_url,sort_order:Ve}))),N.length>0&&await U.from("newsletter_canva_links").insert(N.map((ze,Ve)=>({newsletter_id:Ie,title:ze.title,canva_share_link:ze.canva_share_link,sort_order:Ve})))},ue=async Ie=>{i(Ie),o({title:Ie.title,description:Ie.description||"",publish_date:As(new Date(Ie.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Ie.is_published}),m(Ie.preview_image_url),E(Ie.content_blocks||[]),R(Ie.html_code||"");const[ze,Ve,Le,$e]=await Promise.all([U.from("newsletter_drive_links").select("*").eq("newsletter_id",Ie.id).order("sort_order"),U.from("newsletter_pdfs").select("*").eq("newsletter_id",Ie.id).order("sort_order"),U.from("newsletter_videos").select("*").eq("newsletter_id",Ie.id).order("sort_order"),U.from("newsletter_canva_links").select("*").eq("newsletter_id",Ie.id).order("sort_order")]);x(ze.data||[]),_(Ve.data||[]),j(Le.data||[]),C($e.data||[]),O([]),n(!0)},me=async Ie=>{const[ze,Ve,Le,$e]=await Promise.all([U.from("newsletter_drive_links").select("*").eq("newsletter_id",Ie.id).order("sort_order"),U.from("newsletter_pdfs").select("*").eq("newsletter_id",Ie.id).order("sort_order"),U.from("newsletter_videos").select("*").eq("newsletter_id",Ie.id).order("sort_order"),U.from("newsletter_canva_links").select("*").eq("newsletter_id",Ie.id).order("sort_order")]);i(null),o({title:`${Ie.title} (Copy)`,description:Ie.description||"",publish_date:As(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),m(Ie.preview_image_url),E(Ie.content_blocks||[]),R(Ie.html_code||""),x((ze.data||[]).map(({id:ve,...Qe})=>Qe)),_((Ve.data||[]).map(({id:ve,...Qe})=>Qe)),j((Le.data||[]).map(({id:ve,...Qe})=>Qe)),C(($e.data||[]).map(({id:ve,...Qe})=>Qe)),O([]),n(!0)},de=()=>{n(!1),i(null),o({title:"",description:"",publish_date:As(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),m(null),x([]),_([]),j([]),C([]),E([]),R(""),O([])},fe=async Ie=>{var Ve;const ze=(Ve=Ie.target.files)==null?void 0:Ve[0];ze&&(d(ze),m(URL.createObjectURL(ze)))},je=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}K(!0);let Ie=u;if(c){const ze=`previews/${Date.now()}-${c.name}`,{error:Ve}=await U.storage.from("newsletter-content").upload(ze,c);if(!Ve){const{data:Le}=U.storage.from("newsletter-content").getPublicUrl(ze);Ie=Le.publicUrl}}a?te.mutate({id:a.id,...l,preview_image_url:Ie,content_blocks:A,html_code:D||null}):W.mutate({...l,preview_image_url:Ie,content_blocks:A,html_code:D||null}),K(!1)},xe=()=>x([...f,{title:"",drive_url:"",sort_order:f.length}]),Ee=()=>j([...b,{title:"",video_url:"",sort_order:b.length}]),Me=()=>C([...N,{title:"",canva_share_link:"",sort_order:N.length}]),Oe=Ie=>{const ze=Ie.target.files;if(!ze)return;const Ve=Array.from(ze).map(Le=>({file:Le,name:Le.name.replace(/\.[^/.]+$/,"")}));O([...F,...Ve])};return e.jsx(ws,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources"}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(Z==null?void 0:Z.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(Z==null?void 0:Z.filter(Ie=>Ie.is_published).length)||0})})]})]}),e.jsxs(vs,{open:r,onOpenChange:Ie=>!Ie&&de(),children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{onClick:()=>n(!0),children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(ys,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{children:"Title *"}),e.jsx(Ne,{value:l.title,onChange:Ie=>o({...l,title:Ie.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Publish Date"}),e.jsx(Ne,{type:"datetime-local",value:l.publish_date,onChange:Ie=>o({...l,publish_date:Ie.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(V1,{content:l.description,onChange:Ie=>o({...l,description:Ie}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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(q,{type:"button",variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{d(null),m(null)},children:e.jsx($r,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(Ne,{type:"file",accept:"image/*",onChange:fe,className:"hidden",id:"preview-upload"}),e.jsx(q,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{checked:l.is_published,onCheckedChange:Ie=>o({...l,is_published:Ie})}),e.jsx(ce,{children:"Published"})]}),e.jsx(Y7s,{rows:A,onChange:E}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{className:"text-base font-medium",children:"HTML Code (for agent send)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:'When provided, agents see a "Send Newsletter" button on this newsletter.'})]}),e.jsx("textarea",{value:D,onChange:Ie=>R(Ie.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(ce,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:Me,children:[e.jsx(Ys,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),N.map((Ie,ze)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Ne,{placeholder:"Link title",value:Ie.title,onChange:Ve=>{const Le=[...N];Le[ze].title=Ve.target.value,C(Le)},className:"w-1/3"}),e.jsx(Ne,{placeholder:"Canva share link",value:Ie.canva_share_link,onChange:Ve=>{const Le=[...N];Le[ze].canva_share_link=Ve.target.value,C(Le)},className:"flex-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>C(N.filter((Ve,Le)=>Le!==ze)),children:e.jsx($r,{className:"h-4 w-4"})})]},ze))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:xe,children:[e.jsx(Ys,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),f.map((Ie,ze)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Ne,{placeholder:"Link title",value:Ie.title,onChange:Ve=>{const Le=[...f];Le[ze].title=Ve.target.value,x(Le)},className:"w-1/3"}),e.jsx(Ne,{placeholder:"Google Drive URL",value:Ie.drive_url,onChange:Ve=>{const Le=[...f];Le[ze].drive_url=Ve.target.value,x(Le)},className:"flex-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>x(f.filter((Ve,Le)=>Le!==ze)),children:e.jsx($r,{className:"h-4 w-4"})})]},ze))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(Ne,{type:"file",accept:".pdf",multiple:!0,onChange:Oe,className:"hidden",id:"pdf-upload"}),e.jsx(q,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(ka,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),y.map((Ie,ze)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Ie.name}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>_(y.filter((Ve,Le)=>Le!==ze)),children:e.jsx($r,{className:"h-4 w-4"})})]},`existing-${ze}`)),F.map((Ie,ze)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:Ie.name,onChange:Ve=>{const Le=[...F];Le[ze].name=Ve.target.value,O(Le)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>O(F.filter((Ve,Le)=>Le!==ze)),children:e.jsx($r,{className:"h-4 w-4"})})]},`pending-${ze}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:Ee,children:[e.jsx(Ys,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),b.map((Ie,ze)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Ne,{placeholder:"Video title",value:Ie.title,onChange:Ve=>{const Le=[...b];Le[ze].title=Ve.target.value,j(Le)},className:"w-1/3"}),e.jsx(Ne,{placeholder:"Video URL",value:Ie.video_url,onChange:Ve=>{const Le=[...b];Le[ze].video_url=Ve.target.value,j(Le)},className:"flex-1"}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>j(b.filter((Ve,Le)=>Le!==ze)),children:e.jsx($r,{className:"h-4 w-4"})})]},ze))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(q,{variant:"outline",onClick:de,children:"Cancel"}),e.jsx(q,{onClick:je,disabled:B||W.isPending||te.isPending,children:B?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:Q?e.jsx(Ws,{children:e.jsx(xt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(Z==null?void 0:Z.length)===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):Z==null?void 0:Z.map(Ie=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ie.preview_image_url?e.jsx("img",{src:Ie.preview_image_url,alt:Ie.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(En,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ie.title}),Ie.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ie.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(xt,{children:As(new Date(Ie.publish_date),"MMM d, yyyy")}),e.jsx(xt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Ie.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:Ie.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>ue(Ie),title:"Edit",children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>me(Ie),title:"Duplicate",children:e.jsx(si,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&ne.mutate(Ie.id)},children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},Ie.id))})]})})})]})})}const X7s=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function Q7s(){const s=is(),t=k.useRef(null),[r,n]=k.useState(""),[a,i]=k.useState("all"),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,m]=k.useState(!1),[f,x]=k.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:y=[],isLoading:_}=pt({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:K,error:Z}=await U.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(Z)throw Z;return K||[]}}),b=k.useMemo(()=>{const K=new Set(X7s);return y.forEach(Z=>K.add(Z.category)),Array.from(K).sort()},[y]),j=k.useMemo(()=>{const K=r.trim().toLowerCase();return y.filter(Z=>a!=="all"&&Z.category!==a?!1:K?Z.title.toLowerCase().includes(K)||(Z.description||"").toLowerCase().includes(K)||Z.tags.some(Q=>Q.toLowerCase().includes(K)):!0)},[y,r,a]),N=()=>{x({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},C=()=>{N(),d(!0)},A=K=>{o(K),x({title:K.title,description:K.description||"",image_url:K.image_url,category:K.category,tags:K.tags.join(", "),is_active:K.is_active,is_featured:K.is_featured}),d(!0)},E=async K=>{var Z;if(!K.type.startsWith("image/")){he.error("Please choose an image file");return}if(K.size>15*1024*1024){he.error("Image must be under 15MB");return}m(!0);try{const Q=((Z=K.name.split(".").pop())==null?void 0:Z.toLowerCase())||"png",W=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${Q}`,{error:te}=await U.storage.from("newsletter-content").upload(W,K,{cacheControl:"31536000",upsert:!1,contentType:K.type});if(te)throw te;const{data:ne}=U.storage.from("newsletter-content").getPublicUrl(W);x(ae=>({...ae,image_url:ne.publicUrl,title:ae.title||K.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),he.success("Uploaded")}catch(Q){he.error(Q.message||"Upload failed")}finally{m(!1),t.current&&(t.current.value="")}},D=Mt({mutationFn:async()=>{var Q;if(!f.image_url)throw new Error("Please upload an image");if(!f.title.trim())throw new Error("Please add a title");const K=f.tags.split(",").map(W=>W.trim()).filter(Boolean),Z={title:f.title.trim(),description:f.description.trim()||null,image_url:f.image_url,category:f.category||"General",tags:K,is_active:f.is_active,is_featured:f.is_featured};if(l){const{error:W}=await U.from("newsletter_graphics").update(Z).eq("id",l.id);if(W)throw W}else{const{data:W}=await U.auth.getUser(),{error:te}=await U.from("newsletter_graphics").insert({...Z,created_by:(Q=W.user)==null?void 0:Q.id});if(te)throw te}},onSuccess:()=>{he.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),N()},onError:K=>he.error(K.message||"Save failed")}),R=Mt({mutationFn:async K=>{const{error:Z}=await U.from("newsletter_graphics").delete().eq("id",K);if(Z)throw Z},onSuccess:()=>{he.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:K=>he.error(K.message||"Delete failed")}),F=async K=>{const{error:Z}=await U.from("newsletter_graphics").update({is_active:!K.is_active}).eq("id",K.id);Z?he.error(Z.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},O=async K=>{const{error:Z}=await U.from("newsletter_graphics").update({is_featured:!K.is_featured}).eq("id",K.id);Z?he.error(Z.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},B=K=>{navigator.clipboard.writeText(K),he.success("URL copied")};return e.jsxs(ws,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Uh,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(ke,{children:e.jsxs(Pe,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:r,onChange:K=>n(K.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(Ds,{value:a,onValueChange:i,children:[e.jsx(Ps,{className:"w-full md:w-56",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All categories"}),b.map(K=>e.jsx(lt,{value:K,children:K},K))]})]}),e.jsxs(q,{onClick:C,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(Qy,{className:"h-4 w-4"})," Add Graphic"]})]})}),_?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-16 text-center",children:[e.jsx(zo,{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(q,{onClick:C,className:"gap-1.5",children:[e.jsx(Qy,{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(K=>e.jsxs(ke,{className:`overflow-hidden group ${K.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:K.image_url,alt:K.title,loading:"lazy",className:"w-full h-full object-cover"}),K.is_featured&&e.jsxs(Xe,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(fa,{className:"h-3 w-3 fill-current"})," Featured"]}),!K.is_active&&e.jsx(Xe,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:K.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:K.category})]}),K.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:K.tags.slice(0,3).map(Z=>e.jsx(Xe,{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(q,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>A(K),title:"Edit",children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>O(K),title:K.is_featured?"Unfeature":"Feature",children:e.jsx(fa,{className:`h-3.5 w-3.5 ${K.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>B(K.image_url),title:"Copy URL",children:e.jsx(si,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{checked:K.is_active,onCheckedChange:()=>F(K)}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete "${K.title}"?`)&&R.mutate(K.id)},children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})]})]},K.id))})]}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:K=>{var Q;const Z=(Q=K.target.files)==null?void 0:Q[0];Z&&E(Z)}}),f.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:f.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx(q,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>x(K=>({...K,image_url:""})),children:e.jsx($r,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var K;return(K=t.current)==null?void 0:K.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(ls,{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(ka,{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(ce,{htmlFor:"g-title",children:"Title *"}),e.jsx(Ne,{id:"g-title",value:f.title,onChange:K=>x(Z=>({...Z,title:K.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"g-desc",children:"Description"}),e.jsx(pr,{id:"g-desc",value:f.description,onChange:K=>x(Z=>({...Z,description:K.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(ce,{children:"Category"}),e.jsxs(Ds,{value:f.category,onValueChange:K=>x(Z=>({...Z,category:K})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:b.map(K=>e.jsx(lt,{value:K,children:K},K))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(Ne,{id:"g-tags",value:f.tags,onChange:K=>x(Z=>({...Z,tags:K.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(Rr,{checked:f.is_featured,onCheckedChange:K=>x(Z=>({...Z,is_featured:K}))})]}),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(Rr,{checked:f.is_active,onCheckedChange:K=>x(Z=>({...Z,is_active:K}))})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(q,{onClick:()=>D.mutate(),disabled:D.isPending,children:[D.isPending&&e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const GGe={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 J7s(){const{user:s}=Cs(),{toast:t}=Ba(),r=qr(),n=is(),[a,i]=k.useState(""),[l,o]=k.useState("popular"),[c,d]=k.useState(!1),[u,m]=k.useState(""),[f,x]=k.useState(""),[y,_]=k.useState(!1),{data:b=[],isLoading:j}=pt({queryKey:["wishlist-items",l,y],queryFn:async()=>{let D=U.from("wishlist_items").select("*");y&&s&&(D=D.eq("user_id",s.id)),l==="latest"?D=D.order("created_at",{ascending:!1}):l==="popular"?D=D.order("vote_count",{ascending:!1}):l==="trending"&&(D=D.order("vote_count",{ascending:!1}));const{data:R,error:F}=await D;if(F)throw F;const O=[...new Set((R==null?void 0:R.map(ne=>ne.user_id))||[])],{data:B}=await U.from("profiles").select("id, name").in("id",O),K=new Map((B==null?void 0:B.map(ne=>[ne.id,ne]))||[]);let Z=[];if(s){const{data:ne}=await U.from("wishlist_votes").select("item_id").eq("user_id",s.id);Z=(ne==null?void 0:ne.map(ae=>ae.item_id))||[]}const Q=(R==null?void 0:R.map(ne=>ne.id))||[],{data:W}=await U.from("wishlist_comments").select("item_id").in("item_id",Q),te=new Map;return W==null||W.forEach(ne=>{te.set(ne.item_id,(te.get(ne.item_id)||0)+1)}),R==null?void 0:R.map(ne=>{const ae=K.get(ne.user_id),ue=(ae==null?void 0:ae.name)||"Unknown";return{...ne,user_name:ue,user_initials:ue.split(" ").map(me=>me[0]).join("").toUpperCase().slice(0,2),has_voted:Z.includes(ne.id),comment_count:te.get(ne.id)||0}})}}),N=Mt({mutationFn:async({title:D,description:R})=>{const{error:F}=await U.from("wishlist_items").insert({user_id:s.id,title:D,description:R});if(F)throw F},onSuccess:()=>{n.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),m(""),x(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),C=Mt({mutationFn:async({itemId:D,hasVoted:R})=>{if(R){const{error:F}=await U.from("wishlist_votes").delete().eq("item_id",D).eq("user_id",s.id);if(F)throw F;return{itemId:D,wasAdded:!1}}else{const{error:F}=await U.from("wishlist_votes").insert({item_id:D,user_id:s.id});if(F)throw F;return{itemId:D,wasAdded:!0}}},onSuccess:async D=>{if(n.invalidateQueries({queryKey:["wishlist-items"]}),D!=null&&D.wasAdded){const R=b.find(O=>O.id===D.itemId),F=((R==null?void 0:R.vote_count)||0)+1;U.functions.invoke("wishlist-notify",{body:{itemId:D.itemId,voteCount:F}}).catch(console.error)}},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),A=b.filter(D=>D.title.toLowerCase().includes(a.toLowerCase())||D.description.toLowerCase().includes(a.toLowerCase())),E=()=>{if(!u.trim()||!f.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}N.mutate({title:u.trim(),description:f.trim()})};return e.jsx(ws,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(o2,{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(vs,{open:c,onOpenChange:d,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:D=>m(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:f,onChange:D=>x(D.target.value),rows:4})]}),e.jsx(q,{onClick:E,className:"w-full",disabled:N.isPending,children:N.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search ideas...",value:a,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ta,{value:l,onValueChange:D=>o(D),children:e.jsxs(ea,{children:[e.jsx(rs,{value:"popular",children:"Most Popular"}),e.jsx(rs,{value:"latest",children:"Latest"}),e.jsx(rs,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(q,{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(ls,{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(o2,{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(q,{onClick:()=>d(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:A.map(D=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>r(`/wishlist/${D.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:R=>{R.stopPropagation(),C.mutate({itemId:D.id,hasVoted:D.has_voted||!1})},className:zt("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",D.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(qu,{className:zt("h-4 w-4",D.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:D.vote_count})]}),e.jsx(Wn,{className:"h-10 w-10 bg-primary/20",children:e.jsx(Kn,{className:"bg-primary/20 text-primary text-sm font-medium",children:D.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:D.title}),e.jsx(Xe,{className:zt("text-xs",GGe[D.status].color),children:GGe[D.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:D.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:D.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(D.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ui,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:D.comment_count})]})]})},D.id))})]})})}const WGe={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 e9s(){const{itemId:s}=xo(),t=qr(),{user:r}=Cs(),{toast:n}=Ba(),a=is(),[i,l]=k.useState(""),{data:o=!1}=pt({queryKey:["user-is-admin",r==null?void 0:r.id],queryFn:async()=>{if(!r)return!1;const{data:b,error:j}=await U.from("user_roles").select("role").eq("user_id",r.id).eq("role","admin").maybeSingle();return!j&&!!b},enabled:!!r}),{data:c,isLoading:d}=pt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:b,error:j}=await U.from("wishlist_items").select("*").eq("id",s).single();if(j)throw j;const{data:N}=await U.from("profiles").select("name").eq("id",b.user_id).single();let C=!1;if(r){const{data:A}=await U.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",r.id).maybeSingle();C=!!A}return{...b,user_name:(N==null?void 0:N.name)||"Unknown",user_initials:((N==null?void 0:N.name)||"U").split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),has_voted:C}}}),{data:u=[],isLoading:m}=pt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:b,error:j}=await U.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(j)throw j;const N=[...new Set((b==null?void 0:b.map(E=>E.user_id))||[])],{data:C}=await U.from("profiles").select("id, name").in("id",N),A=new Map((C==null?void 0:C.map(E=>[E.id,E]))||[]);return b==null?void 0:b.map(E=>{const D=A.get(E.user_id),R=(D==null?void 0:D.name)||"Unknown";return{...E,user_name:R,user_initials:R.split(" ").map(F=>F[0]).join("").toUpperCase().slice(0,2)}})}}),f=Mt({mutationFn:async b=>{if(b){const{error:j}=await U.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",r.id);if(j)throw j;return{wasAdded:!1}}else{const{error:j}=await U.from("wishlist_votes").insert({item_id:s,user_id:r.id});if(j)throw j;return{wasAdded:!0}}},onSuccess:async b=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),b!=null&&b.wasAdded&&c){const j=(c.vote_count||0)+1;U.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:j}}).catch(console.error)}},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),x=Mt({mutationFn:async b=>{const{error:j}=await U.from("wishlist_comments").insert({item_id:s,user_id:r.id,content:b});if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),n({title:"Comment added!"})},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),y=Mt({mutationFn:async b=>{const{error:j}=await U.from("wishlist_comments").delete().eq("id",b);if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),n({title:"Comment deleted"})},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),_=()=>{i.trim()&&x.mutate(i.trim())};return d?e.jsx(ws,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(dr,{className:"h-8 w-32 mb-6"}),e.jsx(dr,{className:"h-48 w-full mb-6"}),e.jsx(dr,{className:"h-32 w-full"})]})}):c?e.jsx(ws,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(Aa,{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:()=>f.mutate(c.has_voted),className:zt("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(qu,{className:zt("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(Xe,{className:zt("text-xs",WGe[c.status].color),children:WGe[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(Wn,{className:"h-6 w-6",children:e.jsx(Kn,{className:"bg-primary/20 text-primary text-xs",children:c.user_initials})}),e.jsx("span",{children:c.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(c.created_at).toLocaleDateString()})]})]})]})}),e.jsxs("div",{className:"bg-card border rounded-lg p-6",children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4",children:["Comments (",u.length,")"]}),e.jsxs("div",{className:"flex gap-3 mb-6",children:[e.jsx(Tfe,{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(q,{onClick:_,disabled:!i.trim()||x.isPending,size:"icon",className:"h-auto",children:x.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"})})]}),m?e.jsx("div",{className:"space-y-4",children:[1,2].map(b=>e.jsx(dr,{className:"h-20 w-full"},b))}):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(b=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Wn,{className:"h-8 w-8",children:e.jsx(Kn,{className:"bg-primary/20 text-primary text-xs",children:b.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm",children:b.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(b.created_at).toLocaleDateString()})]}),e.jsx(qAe,{content:b.content,className:"text-sm text-foreground"})]}),(r==null?void 0:r.id)===b.user_id&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>y.mutate(b.id),children:e.jsx(zr,{className:"h-4 w-4"})})]},b.id))})]})]})}):e.jsx(ws,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx(q,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const KGe={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"}},YGe=["open","under_review","planned","in_progress","launched","declined"];function t9s(){const{toast:s}=Ba(),t=qr(),r=is(),[n,a]=k.useState(""),[i,l]=k.useState("all"),[o,c]=k.useState(!1),[d,u]=k.useState(null),{data:m=[],isLoading:f}=pt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:j,error:N}=await U.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(N)throw N;const C=[...new Set((j==null?void 0:j.map(O=>O.user_id))||[])],{data:A}=await U.from("profiles").select("id, name, email").in("id",C),E=new Map((A==null?void 0:A.map(O=>[O.id,O]))||[]),D=(j==null?void 0:j.map(O=>O.id))||[],{data:R}=await U.from("wishlist_comments").select("item_id").in("item_id",D),F=new Map;return R==null||R.forEach(O=>{F.set(O.item_id,(F.get(O.item_id)||0)+1)}),j==null?void 0:j.map(O=>{const B=E.get(O.user_id);return{...O,user_name:(B==null?void 0:B.name)||"Unknown",user_email:(B==null?void 0:B.email)||"",comment_count:F.get(O.id)||0}})}}),x=Mt({mutationFn:async({itemId:j,status:N})=>{const{error:C}=await U.from("wishlist_items").update({status:N}).eq("id",j);if(C)throw C},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),y=Mt({mutationFn:async j=>{const{error:N}=await U.from("wishlist_items").delete().eq("id",j);if(N)throw N},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),_=m.filter(j=>{const N=j.title.toLowerCase().includes(n.toLowerCase())||j.description.toLowerCase().includes(n.toLowerCase())||j.user_name.toLowerCase().includes(n.toLowerCase()),C=i==="all"||j.status===i;return N&&C}),b={total:m.length,open:m.filter(j=>j.status==="open").length,inProgress:m.filter(j=>j.status==="in_progress").length,launched:m.filter(j=>j.status==="launched").length,highVotes:m.filter(j=>j.vote_count>=10).length};return e.jsx(ws,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Wishlist Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Review and manage community ideas"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Ideas"}),e.jsx("p",{className:"text-2xl font-bold",children:b.total})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:b.open})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"In Progress"}),e.jsx("p",{className:"text-2xl font-bold text-orange-600",children:b.inProgress})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Launched"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:b.launched})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"10+ Votes"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:b.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search ideas, users...",value:n,onChange:j=>a(j.target.value),className:"pl-10"})]}),e.jsxs(Ds,{value:i,onValueChange:j=>l(j),children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{placeholder:"Filter by status"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Statuses"}),YGe.map(j=>e.jsx(lt,{value:j,children:KGe[j].label},j))]})]})]}),f?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(j=>e.jsx(dr,{className:"h-16 w-full"},j))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-[60px]",children:"Votes"}),e.jsx(At,{children:"Title"}),e.jsx(At,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(At,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(ha,{children:_.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):_.map(j=>e.jsxs(Ws,{className:zt(j.vote_count>=10&&"bg-primary/5"),children:[e.jsx(xt,{children:e.jsx(Xe,{variant:j.vote_count>=10?"default":"secondary",children:j.vote_count})}),e.jsx(xt,{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(xt,{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(xt,{className:"hidden sm:table-cell",children:j.comment_count}),e.jsx(xt,{children:e.jsxs(Ds,{value:j.status,onValueChange:N=>x.mutate({itemId:j.id,status:N}),children:[e.jsx(Ps,{className:"w-[140px] h-8",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:YGe.map(N=>e.jsx(lt,{value:N,children:KGe[N].label},N))})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${j.id}`,"_blank"),children:e.jsx(un,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(j.id),c(!0)},children:e.jsx(zr,{className:"h-4 w-4"})})]})})]},j.id))})]})}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{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(q,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(q,{variant:"destructive",onClick:()=>d&&y.mutate(d),disabled:y.isPending,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function s9s(){const{user:s}=Cs(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState(!1),[m,f]=k.useState(null),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState(""),[E,D]=k.useState(""),[R,F]=k.useState(!1),[O,B]=k.useState(""),[K,Z]=k.useState("once"),[Q,W]=k.useState([]),[te,ne]=k.useState([]),[ae,ue]=k.useState(!1),[me,de]=k.useState(!1),[fe,je]=k.useState([]),[xe,Ee]=k.useState({total:0,dismissed:0});k.useEffect(()=>{Me()},[]);const Me=async()=>{const{data:rt,error:ct}=await U.from("levelup_briefs").select("*").order("created_at",{ascending:!1});ct?(he.error("Failed to fetch briefs"),console.error(ct)):r(rt||[]),a(!1)},Oe=()=>{y(""),b(""),N(""),A(""),D(""),F(!1),B(new Date().toISOString().slice(0,16)),Z("once"),W([]),ne([]),c(null)},Ie=()=>{Oe(),l(!0)},ze=async rt=>{c(rt),y(rt.title),b(rt.description||""),N(rt.video_url||""),A(rt.graphic_url||""),D(rt.graphic_link_url||""),F(rt.is_published),B(rt.publish_date.slice(0,16)),Z(rt.show_frequency);const{data:ct}=await U.from("levelup_brief_links").select("*").eq("brief_id",rt.id).order("sort_order");W((ct==null?void 0:ct.map(kt=>({title:kt.title,url:kt.url})))||[]);const{data:vt}=await U.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(vt){const kt=[];for(const St of vt){const{data:Yt}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",St.id).order("sort_order");kt.push({question:St.question,poll_type:St.poll_type,options:(Yt==null?void 0:Yt.map(es=>es.option_text))||[]})}ne(kt)}l(!0)},Ve=async rt=>{var vt;const ct=(vt=rt.target.files)==null?void 0:vt[0];if(ct){ue(!0);try{const kt=await U.functions.invoke("bunny-upload",{body:{action:"create",title:ct.name.replace(/\.[^/.]+$/,"")}});if(kt.error)throw kt.error;const{videoId:St,libraryId:Yt}=kt.data,es=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:St}});if(es.error)throw es.error;const{uploadUrl:zs,apiKey:sr}=es.data,ms=new XMLHttpRequest;await new Promise((Ut,ht)=>{ms.upload.addEventListener("progress",Jt=>{if(Jt.lengthComputable){const Ms=Math.round(Jt.loaded/Jt.total*100);console.log("Upload progress:",Ms)}}),ms.addEventListener("load",()=>{ms.status>=200&&ms.status<300?Ut():ht(new Error(`Upload failed with status ${ms.status}`))}),ms.addEventListener("error",()=>ht(new Error("Upload failed"))),ms.open("PUT",zs),ms.setRequestHeader("AccessKey",sr),ms.send(ct)});const gt=`https://player.mediadelivery.net/embed/${Yt}/${St}`;N(gt),he.success("Video uploaded successfully! It may take a few minutes to process.")}catch(kt){console.error("Upload error:",kt),he.error("Failed to upload video")}finally{ue(!1)}}},Le=async()=>{if(!x.trim()){he.error("Title is required");return}try{let rt;if(o){const{error:ct}=await U.from("levelup_briefs").update({title:x,description:_||null,video_url:j||null,graphic_url:C||null,graphic_link_url:E||null,is_published:R,publish_date:O,show_frequency:K}).eq("id",o.id);if(ct)throw ct;rt=o.id,await U.from("levelup_brief_links").delete().eq("brief_id",rt);const{data:vt}=await U.from("levelup_brief_polls").select("id").eq("brief_id",rt);if(vt)for(const kt of vt)await U.from("levelup_brief_poll_options").delete().eq("poll_id",kt.id);await U.from("levelup_brief_polls").delete().eq("brief_id",rt)}else{const{data:ct,error:vt}=await U.from("levelup_briefs").insert({title:x,description:_||null,video_url:j||null,graphic_url:C||null,graphic_link_url:E||null,is_published:R,publish_date:O,show_frequency:K,created_by:s==null?void 0:s.id}).select().single();if(vt)throw vt;rt=ct.id}if(Q.length>0){const ct=Q.map((vt,kt)=>({brief_id:rt,title:vt.title,url:vt.url,sort_order:kt}));await U.from("levelup_brief_links").insert(ct)}for(let ct=0;ct0){const Yt=vt.options.map((es,zs)=>({poll_id:kt.id,option_text:es,sort_order:zs}));await U.from("levelup_brief_poll_options").insert(Yt)}}he.success(o?"Brief updated":"Brief created"),l(!1),Oe(),Me()}catch(rt){console.error("Error saving brief:",rt),he.error("Failed to save brief")}},$e=async rt=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:ct}=await U.from("levelup_briefs").delete().eq("id",rt);if(ct)throw ct;he.success("Brief deleted"),Me()}catch(ct){console.error("Error deleting brief:",ct),he.error("Failed to delete brief")}},ve=async rt=>{f(rt);const{count:ct}=await U.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",rt.id),{count:vt}=await U.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",rt.id).not("dismissed_at","is",null);Ee({total:ct||0,dismissed:vt||0});const{data:kt}=await U.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(kt){const St=[];for(const Yt of kt){const{data:es}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",Yt.id).order("sort_order"),{data:zs}=await U.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",Yt.id),sr=[...new Set((zs==null?void 0:zs.map(Jt=>Jt.user_id))||[])];let ms={};if(sr.length>0){const{data:Jt}=await U.from("profiles").select("id, name, email").in("id",sr);Jt&&Jt.forEach(Ms=>{ms[Ms.id]=Ms.name||Ms.email||"Unknown"})}const gt=(zs||[]).map(Jt=>({optionId:Jt.option_id,userName:ms[Jt.user_id]||"Unknown",userId:Jt.user_id})),Ut={};let ht=0;es&&es.forEach(Jt=>{const Ms=(zs==null?void 0:zs.filter(ts=>ts.option_id===Jt.id).length)||0;Ut[Jt.id]=Ms,ht+=Ms}),St.push({...Yt,options:es||[],results:Ut,respondents:gt,totalResponses:Yt.poll_type==="single"?new Set(zs==null?void 0:zs.map(Jt=>Jt.user_id)).size:ht})}je(St)}u(!0)},Qe=()=>{W([...Q,{title:"",url:""}])},we=(rt,ct,vt)=>{const kt=[...Q];kt[rt][ct]=vt,W(kt)},nt=rt=>{W(Q.filter((ct,vt)=>vt!==rt))},Se=()=>{ne([...te,{question:"",poll_type:"single",options:["",""]}])},Ge=(rt,ct)=>{const vt=[...te];vt[rt].question=ct,ne(vt)},We=(rt,ct)=>{const vt=[...te];vt[rt].poll_type=ct,ne(vt)},Ce=rt=>{const ct=[...te];ct[rt].options.push(""),ne(ct)},qe=(rt,ct,vt)=>{const kt=[...te];kt[rt].options[ct]=vt,ne(kt)},et=(rt,ct)=>{const vt=[...te];vt[rt].options=vt[rt].options.filter((kt,St)=>St!==ct),ne(vt)},Ze=rt=>{ne(te.filter((ct,vt)=>vt!==rt))};return e.jsxs(ws,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(q,{onClick:Ie,children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Frequency"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:n?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(rt=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:rt.title}),e.jsx(xt,{children:e.jsx(Xe,{variant:rt.is_published?"default":"secondary",children:rt.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"capitalize",children:rt.show_frequency.replace("_"," ")}),e.jsx(xt,{children:As(new Date(rt.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>ve(rt),children:e.jsx(Mo,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>ze(rt),children:e.jsx(iu,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>$e(rt.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},rt.id))})]})})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(ta,{defaultValue:"content",className:"w-full",children:[e.jsxs(ea,{className:"grid w-full grid-cols-4",children:[e.jsx(rs,{value:"content",children:"Content"}),e.jsx(rs,{value:"media",children:"Media"}),e.jsx(rs,{value:"links",children:"Links"}),e.jsx(rs,{value:"polls",children:"Polls"})]}),e.jsxs(fs,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Title *"}),e.jsx(Ne,{value:x,onChange:rt=>y(rt.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(V1,{content:_,onChange:rt=>b(rt),placeholder:"Brief overview for agents...",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Publish Date"}),e.jsx(Ne,{type:"datetime-local",value:O,onChange:rt=>B(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Show Frequency"}),e.jsxs(Ds,{value:K,onValueChange:Z,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"once",children:"Once (until dismissed)"}),e.jsx(lt,{value:"every_login",children:"Every login"}),e.jsx(lt,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Rr,{checked:R,onCheckedChange:F}),e.jsx(ce,{children:"Publish immediately"})]})]}),e.jsxs(fs,{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(ce,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Ne,{type:"file",accept:"video/*",onChange:Ve,disabled:ae})}),ae&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Or paste embed URL"}),e.jsx(Ne,{value:j,onChange:rt=>N(rt.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(ce,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Ne,{type:"file",accept:"image/*",onChange:async rt=>{var vt;const ct=(vt=rt.target.files)==null?void 0:vt[0];if(ct){de(!0);try{const kt=ct.name.split(".").pop(),St=`brief-graphics/${Date.now()}.${kt}`,{error:Yt}=await U.storage.from("banner-images").upload(St,ct,{upsert:!0});if(Yt)throw Yt;const{data:es}=U.storage.from("banner-images").getPublicUrl(St);A(es.publicUrl),he.success("Image uploaded!")}catch(kt){console.error(kt),he.error("Failed to upload image")}finally{de(!1)}}},disabled:me})}),me&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Or paste Image URL"}),e.jsx(Ne,{value:C,onChange:rt=>A(rt.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Click-through Link (optional)"}),e.jsx(Ne,{value:E,onChange:rt=>D(rt.target.value),placeholder:"https://example.com/landing-page"})]}),C&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:C,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(fs,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ce,{children:"Quick Links"}),e.jsxs(q,{variant:"outline",size:"sm",onClick:Qe,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),Q.map((rt,ct)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(Ne,{value:rt.title,onChange:vt=>we(ct,"title",vt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(Ne,{value:rt.url,onChange:vt=>we(ct,"url",vt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>nt(ct),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]},ct)),Q.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(fs,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ce,{children:"Polls"}),e.jsxs(q,{variant:"outline",size:"sm",onClick:Se,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),te.map((rt,ct)=>e.jsx(ke,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(Ne,{value:rt.question,onChange:vt=>Ge(ct,vt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(Ds,{value:rt.poll_type,onValueChange:vt=>We(ct,vt),children:[e.jsx(Ps,{className:"w-32",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"single",children:"Single"}),e.jsx(lt,{value:"multi",children:"Multi-select"})]})]}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>Ze(ct),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[rt.options.map((vt,kt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:vt,onChange:St=>qe(ct,kt,St.target.value),placeholder:`Option ${kt+1}`}),rt.options.length>2&&e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>et(ct,kt),children:e.jsx(zr,{className:"h-4 w-4 text-muted-foreground"})})]},kt)),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>Ce(ct),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},ct)),te.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(q,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(q,{onClick:Le,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(vs,{open:d,onOpenChange:u,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsxs(bs,{children:["Results: ",m==null?void 0:m.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-2xl font-bold",children:xe.total})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-2xl font-bold",children:xe.dismissed})})]})]}),fe.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),fe.map(rt=>e.jsxs(ke,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:rt.question}),e.jsx("div",{className:"space-y-2",children:rt.options.map(ct=>{const vt=rt.results[ct.id]||0,kt=rt.totalResponses>0?Math.round(vt/rt.totalResponses*100):0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:ct.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[vt," (",kt,"%)"]})]}),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:`${kt}%`}})}),vt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(rt.respondents||[]).filter(St=>St.optionId===ct.id).map((St,Yt)=>e.jsx(Xe,{variant:"secondary",className:"text-xs font-normal",children:St.userName},Yt))})]},ct.id)})})]},rt.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const r9s=()=>{const{user:s}=Cs(),{toast:t}=Ba(),r=is(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=k.useState(null),[m,f]=k.useState(""),{data:x=[],isLoading:y}=pt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:E,error:D}=await U.from("additional_services").select("*").order("publish_date",{ascending:!1});if(D)throw D;return E}}),_=Mt({mutationFn:async E=>{let D=E.existingImageUrl;if(E.image){const F=E.image.name.split(".").pop(),O=`${Date.now()}-${Math.random().toString(36).substring(7)}.${F}`,{error:B}=await U.storage.from("service-images").upload(O,E.image);if(B)throw B;const{data:K}=U.storage.from("service-images").getPublicUrl(O);D=K.publicUrl}const R={name:E.item.name,description:E.item.description||null,preview_image_url:D,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:F}=await U.from("additional_services").update(R).eq("id",E.itemId);if(F)throw F}else{const{error:F}=await U.from("additional_services").insert(R);if(F)throw F}},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.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"})}}),b=Mt({mutationFn:async E=>{const{error:D}=await U.from("additional_services").delete().eq("id",E);if(D)throw D},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.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),f(""),l(null)},N=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}),f(E.preview_image_url||""),a(!0)},C=E=>{var R;const D=(R=E.target.files)==null?void 0:R[0];D&&(u(D),f(URL.createObjectURL(D)))},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(ws,{title:"Manage Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:x.length})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:x.filter(E=>E.is_published).length})})]})]}),e.jsxs(vs,{open:n,onOpenChange:E=>{a(E),E||j()},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{htmlFor:"name",children:"Name *"}),e.jsx(Ne,{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(ce,{children:"Description"}),e.jsx(V1,{content:o.description,onChange:E=>c({...o,description:E}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(Ne,{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(ce,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{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(Rr,{id:"is_published",checked:o.is_published,onCheckedChange:E=>c({...o,is_published:E})}),e.jsx(ce,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Preview Image"}),m?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:m,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(q,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),f("")},children:e.jsx($r,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(zo,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:C,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:_.isPending,children:_.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{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"})}):x.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-16",children:"Preview"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Signup Link"}),e.jsx(At,{children:"Publish Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:x.map(E=>e.jsxs(Ws,{children:[e.jsx(xt,{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(zo,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(xt,{className:"font-medium",children:E.name}),e.jsx(xt,{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(un,{className:"h-3 w-3"}),"Link"]})}),e.jsx(xt,{children:new Date(E.publish_date).toLocaleDateString()}),e.jsx(xt,{children:e.jsx(Xe,{variant:E.is_published?"default":"secondary",children:E.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>N(E),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&b.mutate(E.id)},children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},E.id))})]})})})]})})};function n9s(){const{toast:s}=Ba(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});k.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:b,error:j}=await U.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(j)throw j;r(b.coupons||[])}catch(b){console.error("Error fetching coupons:",b),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},f=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const b={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?b.percent_off=parseFloat(d.percentOff):(b.amount_off=Math.round(parseFloat(d.amountOff)*100),b.currency="usd"),d.duration==="repeating"&&(b.duration_in_months=parseInt(d.durationInMonths));const{data:j,error:N}=await U.functions.invoke("stripe-manage-coupons",{body:b});if(N)throw N;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),m()}catch(b){console.error("Error creating coupon:",b),s({title:"Error",description:b.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},x=async b=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:j}=await U.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:b}});if(j)throw j;s({title:"Success",description:"Coupon deleted successfully"}),m()}catch(j){console.error("Error deleting coupon:",j),s({title:"Error",description:j.message||"Failed to delete coupon",variant:"destructive"})}},y=b=>b.percent_off?`${b.percent_off}% off`:b.amount_off?`$${(b.amount_off/100).toFixed(2)} off`:"N/A",_=b=>{switch(b.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${b.duration_in_months} months`;default:return b.duration}};return e.jsx(ws,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create New Coupon"}),e.jsx(an,{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(ce,{children:"Promotion Code (what users will type)"}),e.jsx(Ne,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:b=>u({...d,promotionCode:b.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Coupon Name (internal label)"}),e.jsx(Ne,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:b=>u({...d,name:b.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Discount Type"}),e.jsxs(Ds,{value:d.discountType,onValueChange:b=>{const j=b==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:b,duration:j})},children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(UE,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(lt,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Xl,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:b=>u({...d,percentOff:b.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Amount Off (USD)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(Ne,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:b=>u({...d,amountOff:b.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Duration"}),e.jsxs(Ds,{value:d.duration,onValueChange:b=>u({...d,duration:b}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"once",children:"Once (first payment only)"}),e.jsx(lt,{value:"repeating",children:"Multiple months"}),e.jsxs(lt,{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(ce,{children:"Number of Months"}),e.jsx(Ne,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:b=>u({...d,durationInMonths:b.target.value})})]}),e.jsx(q,{onClick:f,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Active Coupons"}),e.jsx(Ur,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Pe,{children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):t.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No coupons created yet. Create your first coupon to get started."}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Promo Code"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Discount"}),e.jsx(At,{children:"Duration"}),e.jsx(At,{children:"Redemptions"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:t.map(b=>{var j;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-mono font-medium",children:((j=b.promotion_codes)==null?void 0:j.length)>0?b.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(xt,{children:b.name||"-"}),e.jsx(xt,{children:y(b)}),e.jsx(xt,{children:_(b)}),e.jsx(xt,{children:b.times_redeemed}),e.jsx(xt,{children:e.jsx(Xe,{variant:b.valid?"default":"secondary",children:b.valid?"Active":"Inactive"})}),e.jsx(xt,{className:"text-right",children:e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>x(b.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})})]},b.id)})})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"How to Use Coupons"})}),e.jsxs(Pe,{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"1. Create a coupon above with your desired discount."}),e.jsx("p",{children:'2. Share the coupon code (shown in the "Code" column) with users.'}),e.jsx("p",{children:"3. Users can enter the code during checkout to receive the discount."}),e.jsx("p",{children:"4. Alternatively, you can create a promotion code in Stripe dashboard for public-facing promotions."})]})]})]})})}const Qwe={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 a9s(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("all"),[l,o]=k.useState(null),{data:c,isLoading:d,refetch:u}=pt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:j,error:N}=await U.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(N)throw N;return j}}),{data:m}=pt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:j,error:N}=await U.from("brokerages").select("*").order("name");if(N)throw N;return await Promise.all((j||[]).map(async A=>{const{data:E}=await U.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",A.id),{data:D}=await U.from("user_roles").select("user_id").eq("role","brokerage_manager"),R=(D==null?void 0:D.map(B=>B.user_id))||[],F=(E==null?void 0:E.filter(B=>R.includes(B.id)))||[],O=(E==null?void 0:E.length)||0;return{...A,managers:F,agentCount:O}}))}}),{data:f}=pt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:j,error:N}=await U.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(N)throw N;return j}}),x=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 N=Qwe[j.subscription_product_id];return{status:(N==null?void 0:N.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 C,A;if(!(((C=j.name)==null?void 0:C.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(x(j),r){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},b=j=>{window.open(`https://dashboard.stripe.com/customers/${j}`,"_blank")};return e.jsx(ws,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(q,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(lo,{className:"h-4 w-4 mr-2"}),"Refresh"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{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(ke,{className:"border-green-500/50",children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(S0,{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(ke,{className:"border-blue-500/50",children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{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(ke,{className:"border-purple-500/50",children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gf,{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(ke,{className:"border-orange-500/50",children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M1,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{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(ta,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"users",children:"All Users"}),e.jsx(rs,{value:"brokerages",children:"Brokerages"}),e.jsxs(rs,{value:"websites",className:"gap-2",children:[e.jsx(Ql,{className:"h-4 w-4"}),"Website Subscriptions",f&&f.length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1",children:f.length})]})]}),e.jsxs(fs,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:s,onChange:j=>t(j.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:a,onValueChange:j=>i(j),children:[e.jsx(Ps,{className:"w-[200px]",children:e.jsx(Fs,{placeholder:"Source"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Sources"}),e.jsx(lt,{value:"platform",children:"Platform"}),e.jsx(lt,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(Ds,{value:r,onValueChange:j=>n(j),children:[e.jsx(Ps,{className:"w-[200px]",children:e.jsx(Fs,{placeholder:"Filter by status"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Statuses"}),e.jsx(lt,{value:"active",children:"Active Subscriptions"}),e.jsx(lt,{value:"trialing",children:"Trials"}),e.jsx(lt,{value:"grandfathered",children:"Grandfathered"}),e.jsx(lt,{value:"brokerage",children:"Brokerage Members"}),e.jsx(lt,{value:"expired",children:"Expired/Canceled"}),e.jsx(lt,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"User"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Plan"}),e.jsx(At,{children:"Brokerage"}),e.jsx(At,{children:"End Date"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:d?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(y==null?void 0:y.length)===0?e.jsx(Ws,{children:e.jsx(xt,{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 N=x(j),C=Qwe[j.subscription_product_id];return e.jsxs(Ws,{children:[e.jsx(xt,{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(xt,{children:e.jsx(Xe,{variant:N.variant,children:N.badge})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm",children:j.is_grandfathered?"Legacy Access":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(C==null?void 0:C.name)||N.status})}),e.jsx(xt,{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(xt,{children:j.subscription_end_date?e.jsx("span",{className:"text-sm",children:As(new Date(j.subscription_end_date),"MMM d, yyyy")}):j.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",As(new Date(j.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[j.stripe_customer_id&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>b(j.stripe_customer_id),children:e.jsx(un,{className:"h-4 w-4"})}),e.jsxs(vs,{children:[e.jsx(Yi,{asChild:!0,children:e.jsx(q,{variant:"outline",size:"sm",onClick:()=>o(j),children:"Details"})}),e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Subscription Details"}),e.jsxs(an,{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(Xe,{variant:N.variant,className:"mt-1",children:N.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":(C==null?void 0:C.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:As(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:As(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(q,{className:"w-full",onClick:()=>b(j.stripe_customer_id),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},j.id)})})]})})})]}),e.jsx(fs,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:m==null?void 0:m.map(j=>{var C,A;const N=(C=j.managers)==null?void 0:C.some(E=>E.subscription_status==="active"&&(E.subscription_product_id==="prod_Tc08MupgoVySDG"||E.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(ke,{children:[e.jsx(Pt,{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(Ga,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:j.name}),e.jsxs(Ur,{children:[j.agentCount," agents"]})]})]}),e.jsx(Xe,{variant:N?"default":"outline",children:N?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Pe,{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 D=Qwe[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:D?e.jsxs("div",{children:[e.jsx(Xe,{variant:"default",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:D.price})]}):e.jsx(Xe,{variant:"outline",children:"No Subscription"})})]},E.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},j.id)})})}),e.jsx(fs,{value:"websites",className:"space-y-4",children:e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ql,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Ur,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Setup Fee"}),e.jsx(At,{children:"Monthly"}),e.jsx(At,{children:"Next Renewal"}),e.jsx(At,{children:"Started"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:f?f.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):f.map(j=>e.jsxs(Ws,{children:[e.jsx(xt,{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(xt,{children:e.jsx(Xe,{variant:j.status==="active"?"default":j.status==="canceled"?"destructive":"outline",children:j.status})}),e.jsx(xt,{children:j.setup_fee_paid?e.jsxs(Xe,{variant:"secondary",children:["Paid · $",(j.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(Xe,{variant:"outline",children:"Unpaid"})}),e.jsxs(xt,{className:"font-medium",children:["$",(j.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(xt,{children:j.current_period_end?e.jsx("span",{className:"text-sm",children:As(new Date(j.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm",children:As(new Date(j.created_at),"MMM d, yyyy")})}),e.jsx(xt,{className:"text-right",children:j.stripe_customer_id&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>b(j.stripe_customer_id),children:e.jsx(un,{className:"h-4 w-4"})})})]},j.id)):e.jsx(Ws,{children:e.jsx(xt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function i9s(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(""),[l,o]=k.useState("all"),[c,d]=k.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});k.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:y,error:_}=await U.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(_)throw _;t(y||[]);const b=(y==null?void 0:y.filter(C=>C.status==="qualified").length)||0,j=(y==null?void 0:y.filter(C=>C.status==="pending").length)||0,N=(y==null?void 0:y.filter(C=>C.status==="cancelled").length)||0;d({total:(y==null?void 0:y.length)||0,qualified:b,pending:j,cancelled:N,totalDiscounts:b*25})}catch(y){console.error("Error fetching referrals:",y),he.error("Failed to load referrals")}finally{n(!1)}},m=async()=>{try{he.loading("Processing qualifications...");const{error:y}=await U.functions.invoke("process-referral-qualifications");if(y)throw y;he.dismiss(),he.success("Qualifications processed successfully"),u()}catch(y){he.dismiss(),console.error("Error processing qualifications:",y),he.error("Failed to process qualifications")}},f=s.filter(y=>{var j,N,C,A,E,D;const _=((N=(j=y.referrer_brokerage)==null?void 0:j.name)==null?void 0:N.toLowerCase().includes(a.toLowerCase()))||((A=(C=y.referred_brokerage)==null?void 0:C.name)==null?void 0:A.toLowerCase().includes(a.toLowerCase()))||((D=(E=y.referred_user)==null?void 0:E.email)==null?void 0:D.toLowerCase().includes(a.toLowerCase())),b=l==="all"||y.status===l;return _&&b}),x=y=>{switch(y){case"qualified":return e.jsxs(Xe,{className:"bg-green-100 text-green-800",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(Xe,{variant:"secondary",children:[e.jsx(jn,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(Xe,{variant:"destructive",children:[e.jsx(ad,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(Xe,{children:y})}};return e.jsx(ws,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(q,{onClick:m,variant:"outline",children:[e.jsx(lo,{className:"h-4 w-4 mr-2"}),"Process Qualifications"]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Referrals"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ti,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.qualified}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-5 w-5 text-amber-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ad,{className:"h-5 w-5 text-red-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.cancelled}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cancelled"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xl,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:["$",c.totalDiscounts]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Discounts"})]})]})})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"All Referrals"}),e.jsx(Ur,{children:"View and manage all referral relationships"})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by brokerage or email...",value:a,onChange:y=>i(y.target.value),className:"pl-10"})]}),e.jsxs(Ds,{value:l,onValueChange:o,children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{placeholder:"Filter by status"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Statuses"}),e.jsx(lt,{value:"pending",children:"Pending"}),e.jsx(lt,{value:"qualified",children:"Qualified"}),e.jsx(lt,{value:"cancelled",children:"Cancelled"})]})]})]}),r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Referrer"}),e.jsx(At,{children:"Referred"}),e.jsx(At,{children:"Signup Date"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Qualified Date"}),e.jsx(At,{children:"Discount"})]})}),e.jsx(ha,{children:f.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):f.map(y=>{var _,b,j,N;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:((_=y.referrer_brokerage)==null?void 0:_.name)||"Unknown"}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((b=y.referred_brokerage)==null?void 0:b.name)||((j=y.referred_user)==null?void 0:j.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(N=y.referred_user)==null?void 0:N.email})]})}),e.jsx(xt,{children:As(new Date(y.signup_date),"MMM d, yyyy")}),e.jsx(xt,{children:x(y.status)}),e.jsx(xt,{children:y.qualified_date?As(new Date(y.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(xt,{children:y.discount_applied?e.jsx(Xe,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},y.id)})})]})]})]})]})})}const Jwe=[{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"}],o9s=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function l9s(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});k.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:N,error:C}=await U.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(C)throw C;t(N||[])}catch(N){console.error("Error fetching checklist items:",N),he.error("Failed to load checklist items")}finally{n(!1)}},m=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},f=N=>{o(N),d({title:N.title,description:N.description||"",action_type:N.action_type,target_role:N.target_role,is_active:N.is_active}),i(!0)},x=async()=>{if(!c.title.trim()){he.error("Title is required");return}try{if(l){const{error:N}=await U.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(N)throw N;he.success("Checklist item updated")}else{const N=s.filter(A=>A.target_role===c.target_role).reduce((A,E)=>Math.max(A,E.sort_order),-1),{error:C}=await U.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:N+1});if(C)throw C;he.success("Checklist item created")}i(!1),u()}catch(N){console.error("Error saving checklist item:",N),he.error("Failed to save checklist item")}},y=async N=>{if(confirm("Are you sure you want to delete this checklist item?"))try{const{error:C}=await U.from("onboarding_checklist_items").delete().eq("id",N);if(C)throw C;he.success("Checklist item deleted"),u()}catch(C){console.error("Error deleting checklist item:",C),he.error("Failed to delete checklist item")}},_=async N=>{try{const{error:C}=await U.from("onboarding_checklist_items").update({is_active:!N.is_active}).eq("id",N.id);if(C)throw C;he.success(N.is_active?"Item deactivated":"Item activated"),u()}catch(C){console.error("Error toggling item:",C),he.error("Failed to update item")}},b=s.filter(N=>N.target_role==="brokerage_manager"),j=s.filter(N=>N.target_role==="agent");return e.jsxs(ws,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs(q,{onClick:m,className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Xe,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Pe,{children:b.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-12",children:"#"}),e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Action Type"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:b.map((N,C)=>{var A;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"text-muted-foreground",children:C+1}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:N.title}),N.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:N.description})]})}),e.jsx(xt,{children:e.jsx(Xe,{variant:"outline",children:((A=Jwe.find(E=>E.value===N.action_type))==null?void 0:A.label)||N.action_type})}),e.jsx(xt,{children:e.jsx(Rr,{checked:N.is_active,onCheckedChange:()=>_(N)})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>f(N),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>y(N.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},N.id)})})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Xe,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Pe,{children:j.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-12",children:"#"}),e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Action Type"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:j.map((N,C)=>{var A;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"text-muted-foreground",children:C+1}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:N.title}),N.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:N.description})]})}),e.jsx(xt,{children:e.jsx(Xe,{variant:"outline",children:((A=Jwe.find(E=>E.value===N.action_type))==null?void 0:A.label)||N.action_type})}),e.jsx(xt,{children:e.jsx(Rr,{checked:N.is_active,onCheckedChange:()=>_(N)})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>f(N),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>y(N.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},N.id)})})]})})]})]}),e.jsx(vs,{open:a,onOpenChange:i,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:c.title,onChange:N=>d({...c,title:N.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",value:c.description,onChange:N=>d({...c,description:N.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(ce,{children:"Target Role"}),e.jsxs(Ds,{value:c.target_role,onValueChange:N=>d({...c,target_role:N}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:o9s.map(N=>e.jsx(lt,{value:N.value,children:N.label},N.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Action Type"}),e.jsxs(Ds,{value:c.action_type,onValueChange:N=>d({...c,action_type:N}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:Jwe.map(N=>e.jsx(lt,{value:N.value,children:N.label},N.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{id:"is_active",checked:c.is_active,onCheckedChange:N=>d({...c,is_active:N})}),e.jsx(ce,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(q,{onClick:x,children:l?"Save Changes":"Create Item"})]})]})})]})}function c9s(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("name"),[l,o]=k.useState("asc"),[c,d]=k.useState(""),[u,m]=k.useState(""),[f,x]=k.useState(""),[y,_]=k.useState(""),{data:b}=pt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:B,error:K}=await U.from("brokerages").select("id, name").order("name");if(K)throw K;return B}}),j=async B=>{let Z=[],Q=0,W=!0;for(;W;){const{data:te,error:ne}=await B(Q,Q+1e3-1);if(ne)throw ne;te&&te.length>0?(Z=[...Z,...te],Q+=1e3,W=te.length===1e3):W=!1}return Z},{data:N,isLoading:C}=pt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const B=await j((ze,Ve)=>U.from("profiles").select("id, name, email, brokerage_id, created_at").range(ze,Ve)),{data:K}=await U.from("brokerages").select("id, name"),Z=new Map((K==null?void 0:K.map(ze=>[ze.id,ze.name]))||[]),[{data:Q},{data:W},{data:te},{data:ne},{data:ae},{data:ue},{data:me}]=await Promise.all([U.rpc("get_admin_contact_counts"),U.rpc("get_admin_video_counts"),U.rpc("get_admin_popby_counts"),U.rpc("get_admin_listing_counts"),U.rpc("get_admin_deal_counts"),U.rpc("get_admin_portal_counts"),U.rpc("get_admin_sendable_card_counts")]),de=new Map;Q==null||Q.forEach(ze=>de.set(ze.owner_user_id,ze.contact_count));const fe=new Map;W==null||W.forEach(ze=>fe.set(ze.owner_user_id,ze.video_count));const je=new Map;te==null||te.forEach(ze=>je.set(ze.owner_user_id,ze.popby_count));const xe=new Map;ne==null||ne.forEach(ze=>xe.set(ze.agent_id,ze.listing_count));const Ee=new Map;ae==null||ae.forEach(ze=>Ee.set(ze.owner_user_id,ze.deal_count));const Me=new Map;ue==null||ue.forEach(ze=>Me.set(ze.owner_user_id,{total:ze.portal_count,active:ze.active_portal_count}));const Oe=new Map;return me==null||me.forEach(ze=>Oe.set(ze.owner_user_id,{total:ze.card_count,sent:ze.sent_card_count,views:ze.total_card_views})),B.map(ze=>{const Ve=Me.get(ze.id),Le=Oe.get(ze.id);return{id:ze.id,name:ze.name||"Unknown",email:ze.email||"",brokerage_id:ze.brokerage_id,brokerage_name:ze.brokerage_id&&Z.get(ze.brokerage_id)||null,contact_count:de.get(ze.id)||0,video_count:fe.get(ze.id)||0,popby_count:je.get(ze.id)||0,listing_count:xe.get(ze.id)||0,deal_count:Ee.get(ze.id)||0,portal_count:(Ve==null?void 0:Ve.total)||0,active_portal_count:(Ve==null?void 0:Ve.active)||0,card_count:(Le==null?void 0:Le.total)||0,sent_card_count:(Le==null?void 0:Le.sent)||0,total_card_views:(Le==null?void 0:Le.views)||0,created_at:ze.created_at}})}}),A=k.useMemo(()=>{if(!N)return[];let B=N.filter(K=>{const Z=s.toLowerCase(),Q=!s||K.name.toLowerCase().includes(Z)||K.email.toLowerCase().includes(Z),W=r==="all"||r==="none"&&!K.brokerage_id||K.brokerage_id===r,te=parseInt(c)||0,ne=parseInt(u)||0,ae=parseInt(f)||0,ue=parseInt(y)||0,me=K.contact_count>=te&&K.video_count>=ne&&K.popby_count>=ae&&K.listing_count>=ue;return Q&&W&&me});return B.sort((K,Z)=>{let Q=0;return a==="name"?Q=K.name.localeCompare(Z.name):Q=K[a]-Z[a],l==="asc"?Q:-Q}),B},[N,s,r,a,l,c,u,f,y]),E=B=>{a===B?o(l==="asc"?"desc":"asc"):(i(B),o("desc"))},D=()=>{const B=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],K=A.map(ne=>[ne.name,ne.email,ne.brokerage_name||"None",ne.contact_count,ne.video_count,ne.popby_count,ne.listing_count,ne.deal_count,`${ne.portal_count} (${ne.active_portal_count})`,ne.card_count,ne.sent_card_count,ne.total_card_views]),Z=[B.join(","),...K.map(ne=>ne.map(ae=>`"${ae}"`).join(","))].join(` `),Q=new Blob([Z],{type:"text/csv"}),W=URL.createObjectURL(Q),te=document.createElement("a");te.href=W,te.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,te.click(),URL.revokeObjectURL(W)},R=k.useMemo(()=>A.length?A.reduce((B,K)=>({contacts:B.contacts+K.contact_count,videos:B.videos+K.video_count,popbys:B.popbys+K.popby_count,listings:B.listings+K.listing_count,deals:B.deals+K.deal_count,portals:B.portals+K.portal_count,activePortals:B.activePortals+K.active_portal_count,cards:B.cards+K.card_count,sentCards:B.sentCards+K.sent_card_count,cardViews:B.cardViews+K.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]),F=k.useMemo(()=>A.length?{portals:A.filter(B=>B.portal_count>0).length,cards:A.filter(B=>B.card_count>0).length}:{portals:0,cards:0},[A]),O=({field:B,children:K})=>e.jsx(At,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>E(B),children:e.jsxs("div",{className:"flex items-center gap-1",children:[K,e.jsx(Uu,{className:`h-3 w-3 ${a===B?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(J_,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ke,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(w_,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:F.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:R.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Portals"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:R.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(ke,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ks,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:F.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:R.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Created"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:R.sentCards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Sent"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:R.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Ur,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:D,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-6",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:s,onChange:B=>t(B.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(Ds,{value:r,onValueChange:n,children:[e.jsxs(Ps,{children:[e.jsx(Ga,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(Fs,{placeholder:"Brokerage"})]}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Brokerages"}),e.jsx(lt,{value:"none",children:"No Brokerage"}),b==null?void 0:b.map(B=>e.jsx(lt,{value:B.id,children:B.name},B.id))]})]})}),e.jsx("div",{children:e.jsx(Ne,{type:"number",placeholder:"Min contacts",value:c,onChange:B=>d(B.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(Ne,{type:"number",placeholder:"Min videos",value:u,onChange:B=>m(B.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(Ne,{type:"number",placeholder:"Min popbys",value:f,onChange:B=>x(B.target.value),min:"0"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-8 text-sm",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:A.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.contacts.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.videos.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Videos"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.popbys.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Popbys"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.listings.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Listings"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.deals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{className:"bg-blue-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.portals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Portals"})]}),e.jsxs("div",{className:"bg-violet-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:R.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),C?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(O,{field:"name",children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Brokerage"}),e.jsx(O,{field:"contact_count",children:"Contacts"}),e.jsx(O,{field:"video_count",children:"Videos"}),e.jsx(O,{field:"popby_count",children:"Popbys"}),e.jsx(O,{field:"listing_count",children:"Listings"}),e.jsx(O,{field:"deal_count",children:"Deals"}),e.jsx(O,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(w_,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(O,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ks,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(ha,{children:A.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):A.map(B=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:B.name}),e.jsx(xt,{className:"text-muted-foreground",children:B.email}),e.jsx(xt,{children:B.brokerage_name?e.jsx(Xe,{variant:"secondary",children:B.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(xt,{children:e.jsx(Xe,{variant:B.contact_count>0?"default":"outline",children:B.contact_count})}),e.jsx(xt,{children:e.jsx(Xe,{variant:B.video_count>0?"default":"outline",children:B.video_count})}),e.jsx(xt,{children:e.jsx(Xe,{variant:B.popby_count>0?"default":"outline",children:B.popby_count})}),e.jsx(xt,{children:e.jsx(Xe,{variant:B.listing_count>0?"default":"outline",children:B.listing_count})}),e.jsx(xt,{children:e.jsx(Xe,{variant:B.deal_count>0?"default":"outline",children:B.deal_count})}),e.jsx(xt,{children:B.portal_count>0?e.jsxs(Oc,{children:[e.jsx(Fc,{children:e.jsxs(Xe,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[B.portal_count,B.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",B.active_portal_count," active)"]})]})}),e.jsxs(Sc,{children:[e.jsxs("p",{children:[B.portal_count," total portals"]}),e.jsxs("p",{children:[B.active_portal_count," currently active"]})]})]}):e.jsx(Xe,{variant:"outline",children:"0"})}),e.jsx(xt,{children:B.card_count>0?e.jsxs(Oc,{children:[e.jsx(Fc,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Xe,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:B.card_count}),B.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(hn,{className:"h-3 w-3"}),B.sent_card_count]}),B.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),B.total_card_views]})]})}),e.jsxs(Sc,{children:[e.jsxs("p",{children:[B.card_count," cards created"]}),e.jsxs("p",{children:[B.sent_card_count," sent"]}),e.jsxs("p",{children:[B.total_card_views," total views"]})]})]}):e.jsx(Xe,{variant:"outline",children:"0"})})]},B.id))})]})})]})]})]})})}function d9s(){Ba(),is();const[s,t]=k.useState("user-analytics"),{data:r}=pt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:x,error:y}=await U.from("feature_flags").select("*").order("key");if(y)throw y;return x}}),{data:n,isLoading:a}=pt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:x,error:y}=await U.from("relationship_types").select("*").order("sort_order");if(y)throw y;return x}}),{data:i,isLoading:l}=pt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:x,error:y}=await U.from("action_types").select("*").order("sort_order");if(y)throw y;return x}}),{data:o,isLoading:c}=pt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:x,error:y}=await U.from("action_scripts").select("*, action_type:action_types(*)");if(y)throw y;return x}}),{data:d,isLoading:u}=pt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:x,error:y}=await U.from("touchpoint_plans").select("*").order("name");if(y)throw y;return x}}),{data:m,isLoading:f}=pt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:x,error:y}=await U.from("popby_items").select("*").is("owner_user_id",null).order("name");if(y)throw y;return x}});return e.jsx(ws,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(ta,{value:s,onValueChange:t,children:[e.jsxs(ea,{className:"grid w-full grid-cols-9",children:[e.jsxs(rs,{value:"user-analytics",className:"gap-2",children:[e.jsx(Mo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(rs,{value:"relationship-types",className:"gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(rs,{value:"action-types",className:"gap-2",children:[e.jsx(Mn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(rs,{value:"scripts",className:"gap-2",children:[e.jsx(En,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(rs,{value:"video-scripts",className:"gap-2",children:[e.jsx(rf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(rs,{value:"plans",className:"gap-2",children:[e.jsx(vn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(rs,{value:"popbys",className:"gap-2",children:[e.jsx(Di,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(rs,{value:"settings",className:"gap-2",children:[e.jsx(Bo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(rs,{value:"feature-flags",className:"gap-2",children:[e.jsx(r2,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(fs,{value:"user-analytics",className:"mt-6",children:e.jsx(c9s,{})}),e.jsx(fs,{value:"relationship-types",className:"mt-6",children:e.jsx(u9s,{types:n||[],isLoading:a})}),e.jsx(fs,{value:"action-types",className:"mt-6",children:e.jsx(h9s,{types:i||[],isLoading:l})}),e.jsx(fs,{value:"scripts",className:"mt-6",children:e.jsx(m9s,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(fs,{value:"video-scripts",className:"mt-6",children:e.jsx(g9s,{})}),e.jsx(fs,{value:"plans",className:"mt-6",children:e.jsx(f9s,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(fs,{value:"popbys",className:"mt-6",children:e.jsx(x9s,{items:m||[],isLoading:f})}),e.jsx(fs,{value:"settings",className:"mt-6",children:e.jsx(y9s,{})}),e.jsx(fs,{value:"feature-flags",className:"mt-6",children:e.jsx(p9s,{flags:r||[]})})]})]})})}function u9s({types:s,isLoading:t}){const{toast:r}=Ba(),n=is(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Mt({mutationFn:async u=>{if(u.id){const{error:m}=await U.from("relationship_types").update({name:u.name,description:u.description,icon:u.icon}).eq("id",u.id);if(m)throw m}else{const{error:m}=await U.from("relationship_types").insert([{name:u.name,description:u.description,icon:u.icon,sort_order:s.length}]);if(m)throw m}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:u=>{r({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await U.from("relationship_types").update({active:!u.active}).eq("id",u.id),n.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Relationship Types"}),e.jsx(Ur,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(q,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Pe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-12"}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(u=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsx(Vu,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(xt,{className:"font-medium",children:u.name}),e.jsx(xt,{className:"text-muted-foreground",children:u.description}),e.jsx(xt,{children:e.jsx(Rr,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(xt,{children:e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Ua,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsxs(bs,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const m=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description"),icon:m.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"icon",children:"Icon"}),e.jsx(Ne,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(fn,{className:"mt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function h9s({types:s,isLoading:t}){const{toast:r}=Ba(),n=is(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Mt({mutationFn:async u=>{if(u.id){const{error:m}=await U.from("action_types").update({name:u.name,description:u.description,icon:u.icon,color:u.color}).eq("id",u.id);if(m)throw m}else{const{error:m}=await U.from("action_types").insert([{name:u.name,description:u.description,icon:u.icon,color:u.color,sort_order:s.length}]);if(m)throw m}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:u=>{r({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await U.from("action_types").update({active:!u.active}).eq("id",u.id),n.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Action Types"}),e.jsx(Ur,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(q,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Pe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Color"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(u=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:u.name}),e.jsx(xt,{className:"text-muted-foreground",children:u.description}),e.jsx(xt,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(xt,{children:e.jsx(Rr,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(xt,{children:e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Ua,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsxs(bs,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const m=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description"),icon:m.get("icon"),color:m.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"icon",children:"Icon"}),e.jsx(Ne,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"color",children:"Color"}),e.jsx(Ne,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(fn,{className:"mt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function m9s({scripts:s,actionTypes:t,isLoading:r}){const{toast:n}=Ba(),a=is(),[i,l]=k.useState(null),[o,c]=k.useState(!1),d=Mt({mutationFn:async m=>{if(m.id){const{error:f}=await U.from("action_scripts").update({title:m.title,action_type_id:m.action_type_id,tone:m.tone,script_body:m.script_body,active:m.active}).eq("id",m.id);if(f)throw f}else{const{error:f}=await U.from("action_scripts").insert([{title:m.title,action_type_id:m.action_type_id,tone:m.tone,script_body:m.script_body,active:!0}]);if(f)throw f}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),n({title:"Saved successfully"})},onError:m=>{n({title:"Error",description:m.message,variant:"destructive"})}}),u=Mt({mutationFn:async m=>{const{error:f}=await U.from("action_scripts").delete().eq("id",m);if(f)throw f},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),n({title:"Deleted successfully"})}});return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Script Library"}),e.jsx(Ur,{children:"Create and manage scripts for each action type"})]}),e.jsxs(q,{onClick:()=>{l(null),c(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Pe,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Action Type"}),e.jsx(At,{children:"Tone"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(m=>{var f;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:m.title}),e.jsx(xt,{children:e.jsx(Xe,{variant:"outline",children:((f=m.action_type)==null?void 0:f.name)||"Unknown"})}),e.jsx(xt,{className:"text-muted-foreground",children:m.tone}),e.jsx(xt,{children:e.jsx(Xe,{variant:m.active?"default":"secondary",children:m.active?"Active":"Inactive"})}),e.jsxs(xt,{className:"flex gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{l(m),c(!0)},children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>u.mutate(m.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})]},m.id)})})]})}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsxs(bs,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:m=>{m.preventDefault();const f=new FormData(m.currentTarget);d.mutate({id:i==null?void 0:i.id,title:f.get("title"),action_type_id:f.get("action_type_id"),tone:f.get("tone"),script_body:f.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(ce,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(Ds,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select action type"})}),e.jsx(Ls,{children:t.map(m=>e.jsx(lt,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(Ne,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"script_body",children:"Script Body"}),e.jsx(pr,{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(fn,{className:"mt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function f9s({plans:s,actionTypes:t,scripts:r,isLoading:n}){const{toast:a}=Ba(),i=is(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,m]=k.useState(null),[f,x]=k.useState(!1),[y,_]=k.useState(null),[b,j]=k.useState(null),{data:N}=pt({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:O,error:B}=await U.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(B)throw B;return O},enabled:!!u}),C=Mt({mutationFn:async O=>{if(O.id){const{error:B}=await U.from("touchpoint_plans").update({name:O.name,description:O.description,active:O.active}).eq("id",O.id);if(B)throw B}else{const{error:B}=await U.from("touchpoint_plans").insert([{name:O.name,description:O.description,active:!0}]);if(B)throw B}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:O=>{a({title:"Error",description:O.message,variant:"destructive"})}}),A=Mt({mutationFn:async O=>{if(O.id){const{error:B}=await U.from("touchpoint_plan_items").update({action_type_id:O.action_type_id,default_script_id:O.default_script_id,notes:O.notes}).eq("id",O.id);if(B)throw B}else{const{error:B}=await U.from("touchpoint_plan_items").insert([{plan_id:O.plan_id,month_number:O.month_number,action_type_id:O.action_type_id,default_script_id:O.default_script_id,notes:O.notes}]);if(B)throw B}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),E=Mt({mutationFn:async O=>{const{error:B}=await U.from("touchpoint_plan_items").delete().eq("id",O);if(B)throw B},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),D=Mt({mutationFn:async O=>{const{data:B,error:K}=await U.from("action_scripts").insert([{...O,active:!0}]).select().single();if(K)throw K;return B},onSuccess:async O=>{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:O.id}),x(!1),_(null),a({title:"Script created and assigned"})},onError:O=>{a({title:"Error",description:O.message,variant:"destructive"})}}),R=(O,B,K)=>{_({month:O,actionTypeId:B,itemId:K}),x(!0)},F=O=>r.find(B=>B.id===O);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Touchpoint Plans"}),e.jsx(Ur,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(q,{onClick:()=>{o(null),d(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Pe,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{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(O=>e.jsxs(ke,{className:`cursor-pointer transition-colors ${u===O.id?"border-primary":""}`,onClick:()=>m(O.id),children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Dt,{className:"text-base",children:O.name}),e.jsx(q,{variant:"ghost",size:"icon",onClick:B=>{B.stopPropagation(),o(O),d(!0)},children:e.jsx(Ua,{className:"h-4 w-4"})})]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:O.description}),e.jsx(Xe,{variant:O.active?"default":"secondary",className:"mt-2",children:O.active?"Active":"Inactive"})]})]},O.id))})})]}),u&&e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Plan Schedule"}),e.jsx(Ur,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Pe,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(O,B)=>B+1).map(O=>{const B=N==null?void 0:N.find(Q=>Q.month_number===O),K=B!=null&&B.default_script_id?F(B.default_script_id):null,Z=r.filter(Q=>Q.action_type_id===(B==null?void 0:B.action_type_id)&&Q.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 ",O]}),e.jsxs(Ds,{value:(B==null?void 0:B.action_type_id)||"none",onValueChange:Q=>{Q==="none"&&B?E.mutate(B.id):Q!=="none"&&A.mutate({id:B==null?void 0:B.id,plan_id:u,month_number:O,action_type_id:Q,default_script_id:null})},children:[e.jsx(Ps,{className:"w-40",children:e.jsx(Fs,{placeholder:"No action"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No action"}),t.filter(Q=>Q.active).map(Q=>e.jsx(lt,{value:Q.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Q.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Q.color}}),Q.name]})},Q.id))]})]}),B&&e.jsxs(e.Fragment,{children:[e.jsxs(Ds,{value:B.default_script_id||"none",onValueChange:Q=>{j(null),A.mutate({id:B.id,default_script_id:Q==="none"?null:Q})},children:[e.jsx(Ps,{className:"w-56",children:e.jsx(Fs,{placeholder:"Select script"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No default script"}),Z.map(Q=>e.jsxs(lt,{value:Q.id,children:[Q.title," ",Q.tone&&`(${Q.tone})`]},Q.id))]})]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>R(O,B.action_type_id,B.id),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"}),"New Script"]}),K&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>j((b==null?void 0:b.id)===K.id?null:K),children:(b==null?void 0:b.id)===K.id?"Hide":"Preview"})]})]}),b&&(B==null?void 0:B.default_script_id)===b.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Xe,{variant:"outline",children:b.title}),b.tone&&e.jsx(Xe,{variant:"secondary",children:b.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:b.script_body})]})]},O)})})})]}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsxs(bs,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:O=>{O.preventDefault();const B=new FormData(O.currentTarget);C.mutate({id:l==null?void 0:l.id,name:B.get("name"),description:B.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(fn,{className:"mt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:C.isPending,children:[C.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(vs,{open:f,onOpenChange:x,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create New Script"}),e.jsxs(an,{children:["Create a script for Month ",y==null?void 0:y.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:O=>{O.preventDefault();const B=new FormData(O.currentTarget);D.mutate({title:B.get("title"),action_type_id:y.actionTypeId,tone:B.get("tone"),script_body:B.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(ce,{htmlFor:"script_title",children:"Title"}),e.jsx(Ne,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"script_tone",children:"Tone"}),e.jsx(Ne,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"script_body",children:"Script Body"}),e.jsx(pr,{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(fn,{className:"mt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:D.isPending,children:[D.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function p9s({flags:s}){const{toast:t}=Ba(),r=is(),n=async(a,i)=>{const{error:l}=await U.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(r.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Feature Flags"}),e.jsx(Ur,{children:"Control which features are enabled for members"})]}),e.jsx(Pe,{children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Flag"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Notes"}),e.jsx(At,{children:"Last Updated"})]})}),e.jsx(ha,{children:s.map(a=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-mono text-sm",children:a.key}),e.jsx(xt,{children:e.jsx(Rr,{checked:a.enabled,onCheckedChange:i=>n(a,{enabled:i})})}),e.jsx(xt,{children:e.jsx(Ne,{defaultValue:a.notes||"",placeholder:"Add notes...",className:"max-w-xs",onBlur:i=>{i.target.value!==a.notes&&n(a,{notes:i.target.value})}})}),e.jsx(xt,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function x9s({items:s,isLoading:t}){const{toast:r}=Ba(),n=is(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Mt({mutationFn:async m=>{if(m.id){const{error:f}=await U.from("popby_items").update({name:m.name,description:m.description}).eq("id",m.id);if(f)throw f}else{const{error:f}=await U.from("popby_items").insert([{name:m.name,description:m.description,owner_user_id:null}]);if(f)throw f}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:m=>{r({title:"Error",description:m.message,variant:"destructive"})}}),d=async m=>{await U.from("popby_items").update({is_active:!m.is_active}).eq("id",m.id),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]})},u=async m=>{await U.from("popby_items").delete().eq("id",m),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),r({title:"Deleted successfully"})};return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Popby Ideas"}),e.jsx(Ur,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(q,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Pe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{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(Di,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No popby ideas yet. Add your first one!"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:s.map(m=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:m.name}),e.jsx(xt,{className:"text-muted-foreground",children:m.description}),e.jsx(xt,{children:e.jsx(Rr,{checked:m.is_active,onCheckedChange:()=>d(m)})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{i(m),o(!0)},children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>u(m.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},m.id))})]})}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsxs(bs,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:m=>{m.preventDefault();const f=new FormData(m.currentTarget);c.mutate({id:a==null?void 0:a.id,name:f.get("name"),description:f.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(fn,{className:"mt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function g9s(){var x;const{toast:s}=Ba(),t=is(),[r,n]=k.useState(null),[a,i]=k.useState(!1),{data:l,isLoading:o}=pt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:y,error:_}=await U.from("video_script_categories").select("*").order("sort_order");if(_)throw _;return y}}),{data:c,isLoading:d}=pt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:y,error:_}=await U.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(_)throw _;return y}}),u=Mt({mutationFn:async y=>{var _,b;if(y.id){const{error:j}=await U.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(N=>N.trim()).filter(Boolean))||[]}).eq("id",y.id);if(j)throw j}else{const{error:j}=await U.from("video_scripts").insert([{title:y.title,script_text:y.script_text,category_id:y.category_id||null,tags:((b=y.tags)==null?void 0:b.split(",").map(N=>N.trim()).filter(Boolean))||[]}]);if(j)throw j}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),n(null),s({title:"Video script saved!"})},onError:y=>s({title:"Error",description:y.message,variant:"destructive"})}),m=async y=>{await U.from("video_scripts").update({is_active:!y.is_active}).eq("id",y.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},f=async y=>{confirm("Delete this video script?")&&(await U.from("video_scripts").delete().eq("id",y),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Video Scripts"}),e.jsx(Ur,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(q,{onClick:()=>{n(null),i(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Pe,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Title"}),e.jsx(At,{children:"Category"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"w-24",children:"Actions"})]})}),e.jsx(ha,{children:c==null?void 0:c.map(y=>{var _;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:y.title}),e.jsx(xt,{className:"text-muted-foreground",children:((_=y.category)==null?void 0:_.name)||"Uncategorized"}),e.jsx(xt,{children:e.jsx(Rr,{checked:y.is_active,onCheckedChange:()=>m(y)})}),e.jsxs(xt,{className:"flex gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{n(y),i(!0)},children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>f(y.id),children:e.jsx(zr,{className:"h-4 w-4"})})]})]},y.id)})})]})}),e.jsx(vs,{open:a,onOpenChange:i,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsxs(bs,{children:[r?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault();const _=new FormData(y.currentTarget);u.mutate({id:r==null?void 0:r.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(ce,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",name:"title",defaultValue:r==null?void 0:r.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"category_id",children:"Category"}),e.jsxs(Ds,{name:"category_id",defaultValue:(r==null?void 0:r.category_id)||"",children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select category"})}),e.jsx(Ls,{children:l==null?void 0:l.map(y=>e.jsx(lt,{value:y.id,children:y.name},y.id))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"script_text",children:"Script Text"}),e.jsx(pr,{id:"script_text",name:"script_text",defaultValue:r==null?void 0:r.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(Ne,{id:"tags",name:"tags",defaultValue:((x=r==null?void 0:r.tags)==null?void 0:x.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(fn,{className:"mt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function y9s(){const{toast:s}=Ba(),[t,r]=k.useState(""),[n,a]=k.useState(!0),[i,l]=k.useState(!1);k.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&r(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await U.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return n?e.jsx(ke,{children:e.jsx(Pe,{className:"flex justify-center py-8",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ma,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Ur,{children:"Configure the map feature for popbys"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(Ne,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>r(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),e.jsxs(q,{onClick:o,disabled:i,children:[i&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(Xe,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const v9s=()=>{const[s,t]=k.useState(""),[r,n]=k.useState("grid"),a=qr(),{data:i=[],isLoading:l}=pt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await U.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(ws,{title:"Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search services...",value:s,onChange:c=>t(c.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx(q,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>n("grid"),className:"rounded-full",children:e.jsx(Ep,{className:"h-4 w-4"})}),e.jsx(q,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>n("list"),className:"rounded-full",children:e.jsx(Zf,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," service",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(4)].map((c,d)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(dr,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(dr,{className:"h-5 w-3/4 mb-2"}),e.jsx(dr,{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(q,{variant:"outline",onClick:()=>t(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(c=>e.jsxs(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:c.preview_image_url?e.jsx("img",{src:c.preview_image_url,alt:c.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Ir,{className:"h-8 w-8"})})}),e.jsxs(Pe,{className:`p-4 flex flex-col ${r==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:c.name}),c.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:x9(c.description)})]})]},c.id))})]})})},b9s=()=>{const{serviceId:s}=xo(),t=qr(),{data:r,isLoading:n}=pt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await U.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return n?e.jsx(ws,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(dr,{className:"h-8 w-48"}),e.jsx(dr,{className:"h-64 w-full rounded-lg"}),e.jsx(dr,{className:"h-24 w-full"})]})}):r?e.jsx(ws,{title:r.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(q,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(ke,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:r.preview_image_url?e.jsx("img",{src:r.preview_image_url,alt:r.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):e.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:e.jsx(Ir,{className:"h-16 w-16"})})})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:r.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(vn,{className:"h-4 w-4 mr-1"}),"Published ",As(new Date(r.publish_date),"MMMM d, yyyy")]})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:r.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(q,{size:"lg",className:"gap-2",onClick:()=>window.open(r.signup_link_url,"_blank"),children:[e.jsx(un,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(ws,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs(q,{onClick:()=>t("/additional-services"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},hO=[{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 _9s(){const[s,t]=k.useState(hO[0].id),r=hO.find(n=>n.id===s)||hO[0];return e.jsx(ws,{title:"AI Toolkit",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(eS,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"AI Toolkit"}),e.jsx("p",{className:"text-muted-foreground",children:"Powerful AI tools to boost your real estate business"})]})]}),e.jsx("div",{className:"md:hidden",children:e.jsxs(Ds,{value:s,onValueChange:t,children:[e.jsx(Ps,{className:"w-full",children:e.jsx(Fs,{placeholder:"Select a tool"})}),e.jsx(Ls,{children:hO.map(n=>e.jsx(lt,{value:n.id,children:n.name},n.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(ta,{value:s,onValueChange:t,className:"w-full",children:e.jsx(ea,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:hO.map(n=>e.jsx(rs,{value:n.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:n.name},n.id))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:r.iframe}})})]})})}const ZGe="agent-os-onboarding-completed",gV=[{icon:C_,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:zh,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:Dr,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:xu,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:Di,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:Mo,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"]}],w9s=()=>{const[s,t]=k.useState(!1),[r,n]=k.useState(0),[a,i]=k.useState(!1);k.useEffect(()=>{if(!localStorage.getItem(ZGe)){const y=setTimeout(()=>t(!0),500);return()=>clearTimeout(y)}},[]);const l=()=>{r{n(r+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(ZGe,"true"),t(!1)},d=gV[r],u=d.icon,m=r===gV.length-1,f=x=>{x||c(),t(x)};return e.jsx(vs,{open:s,onOpenChange:f,children:e.jsxs(ys,{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`})})]}),r===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Ir,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(_s,{className:"text-center sm:text-center pb-2",children:[e.jsx(bs,{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(an,{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((x,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(la,{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:x})]},y))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:gV.map((x,y)=>e.jsx("button",{onClick:()=>{y!==r&&(i(!0),setTimeout(()=>{n(y),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${y===r?"w-8 bg-gradient-to-r "+d.bgGradient:y{const{user:s}=Cs();return pt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(r)throw r;return t},enabled:!!s})},N9s=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async({contactId:r,days:n})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Dc(new Date,n);await U.from("contact_snoozes").delete().eq("contact_id",r);const{error:i}=await U.from("contact_snoozes").insert({contact_id:r,owner_user_id:t.id,snoozed_until:a.toISOString()});if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Dn({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:r=>{Dn({title:"Error snoozing contact",description:r.message,variant:"destructive"})}})},k9s=()=>{const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("contact_snoozes").delete().eq("contact_id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),Dn({title:"Snooze cancelled"})},onError:t=>{Dn({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},S9s=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function yye({open:s,onOpenChange:t,contactId:r,contactName:n}){const[a,i]=k.useState(null),l=N9s(),o=async()=>{a&&(await l.mutateAsync({contactId:r,days:a}),i(null),t(!1))},c=d=>As(Dc(new Date,d),"MMM d, yyyy");return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(an,{children:["Postpone the next scheduled touch for ",n,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:S9s.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:zt("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(vn,{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(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const C9s={Crown:Gf,FileText:En,Users:Dr,Globe:Ql,Star:fa,Phone:Mn,MessageSquare:Ui,PenTool:oS,Video:bn,Gift:Di};function T9s({actions:s,onMarkComplete:t,onViewScript:r,isLoading:n,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=qr(),[c,d]=k.useState("name"),[u,m]=k.useState("asc"),[f,x]=k.useState(null),[y,_]=k.useState(""),b=E=>{c===E?m(D=>D==="asc"?"desc":"asc"):(d(E),m("asc"))},j=k.useMemo(()=>[...s].sort((E,D)=>{var F,O;let R=0;switch(c){case"name":{const B=`${E.contact.first_name} ${E.contact.last_name||""}`.toLowerCase(),K=`${D.contact.first_name} ${D.contact.last_name||""}`.toLowerCase();R=B.localeCompare(K);break}case"relationship_type":R=(E.relationshipTypeName||"").localeCompare(D.relationshipTypeName||"");break;case"action_type":R=(((F=E.actionType)==null?void 0:F.name)||"").localeCompare(((O=D.actionType)==null?void 0:O.name)||"");break;case"last_touch":R=(E.monthNumber||0)-(D.monthNumber||0);break}return u==="asc"?R:-R}),[s,c,u]),N=E=>C9s[E||"Phone"]||Mn,C=({field:E,children:D})=>e.jsxs(q,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>b(E),children:[D,c===E?u==="asc"?e.jsx(qu,{className:"ml-2 h-4 w-4"}):e.jsx(gm,{className:"ml-2 h-4 w-4"}):e.jsx(Uu,{className:"ml-2 h-4 w-4 opacity-50"})]}),A=(E,D,R)=>{x(E),_(`${D} ${R||""}`.trim())};return s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/50",children:[e.jsx(At,{className:"w-[180px]",children:e.jsx(C,{field:"name",children:"Contact"})}),e.jsx(At,{className:"w-[130px]",children:e.jsx(C,{field:"relationship_type",children:"Type"})}),e.jsx(At,{className:"w-[120px]",children:e.jsx(C,{field:"action_type",children:"Action"})}),e.jsx(At,{className:"w-[130px]",children:"Phone"}),e.jsx(At,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(ha,{children:j.map((E,D)=>{var Z,Q,W,te,ne,ae;const R=E.isSpecialDate,F=E.specialDateType,O=R?F==="birthday"?_m:Pn:N(((Z=E.actionType)==null?void 0:Z.icon)||null),B=E.contact.phone,K=E.contact.email;return e.jsxs(Ws,{className:zt("hover:bg-muted/50 transition-colors",R&&F==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",R&&F==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(xt,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${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(xt,{children:E.relationshipTypeName?e.jsx(Xe,{variant:"secondary",className:"text-xs",children:E.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:R?e.jsx(Xe,{className:zt("gap-1",F==="birthday"&&"bg-pink-500 hover:bg-pink-600",F==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:F==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(_m,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pn,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(O,{className:"h-3 w-3"}),(Q=E.actionType)==null?void 0:Q.name]})})}),e.jsx(xt,{children:B?e.jsx("span",{className:"text-sm font-mono",children:E.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[B&&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(Mn,{className:"h-3.5 w-3.5"})}),B&&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(Ui,{className:"h-3.5 w-3.5"})}),K&&(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(Ks,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(E.contact.email,(te=E.script)==null?void 0:te.script_body,(ne=E.script)==null?void 0:ne.email_subject,(ae=E.actionType)==null?void 0:ae.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(Ks,{className:"h-3.5 w-3.5"})})),R&&e.jsxs("button",{onClick:()=>{const ue=`${E.contact.first_name}${E.contact.last_name?" "+E.contact.last_name:""}`,me=F==="birthday"?"birthday":"home_anniversary",de=new URLSearchParams({cardType:me,contactId:E.contact.id,name:ue,...E.contact.address?{address:E.contact.address}:{},...F==="anniversary"&&E.contact.home_anniversary?{date:E.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${de.toString()}`)},className:zt("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",F==="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 ${F==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(Ks,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(q,{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(Xf,{className:"h-3.5 w-3.5"})}),e.jsxs(q,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var ue;return t(E.contact.id,E.actionType.id,(ue=E.script)==null?void 0:ue.id)},disabled:n,children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${E.contact.id}-${D}`)})})]})}),e.jsx(yye,{open:!!f,onOpenChange:E=>!E&&x(null),contactId:f||"",contactName:y})]})}function E9s({onSelect:s}){const{user:t}=Cs(),[r,n]=k.useState("root"),[a,i]=k.useState(null),{data:l=[],isLoading:o}=pt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:j,error:N}=await U.from("email_template_categories").select("*").order("sort_order");if(N)throw N;return j}}),{data:c=[],isLoading:d}=pt({queryKey:["agent-email-templates",a],enabled:r==="category"&&!!a,queryFn:async()=>{const{data:j,error:N}=await U.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(N)throw N;return j}}),{data:u=[],isLoading:m}=pt({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:j,error:N}=await U.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(N)throw N;return j}}),f=u.filter(j=>j.user_id===(t==null?void 0:t.id)&&!j.is_shared),x=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(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const _=j=>{s({title:j.name,subject:j.subject,body:j.body_html})};if(r==="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:()=>n("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(qi,{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:[f.length," template",f.length===1?"":"s"," you've created"]})]})]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),e.jsxs("button",{onClick:()=>n("shared"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-400 flex items-center justify-center",children:e.jsx(Ql,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x.length," team template",x.length===1?"":"s"]})]})]}),e.jsx(Ia,{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),n("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(Ia,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},j.id))})]})]});const b=e.jsxs("button",{onClick:()=>{n("root"),i(null)},className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(jl,{className:"h-3.5 w-3.5"}),"Back"]});return r==="my"?e.jsxs("div",{className:"space-y-2",children:[b,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(qi,{className:"h-3.5 w-3.5"})," My Saved Templates"]}),m?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):f.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(Ir,{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(ui,{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.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))})})]}):r==="shared"?e.jsxs("div",{className:"space-y-2",children:[b,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"})," Shared Library"]}),m?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):x.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(ui,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:x.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(Xe,{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:[b,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(ls,{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(ui,{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(Xe,{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 vye(){const{user:s}=Cs(),t=is(),{data:r,isLoading:n}=pt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:u}=await U.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=Mt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:m}=await U.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(m)throw m;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),he.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?he.error("That slug is already taken. Try another."):he.error("Failed to create page")}}),i=Mt({mutationFn:async d=>{if(!(r!=null&&r.id))throw new Error("No intake page");const{error:u}=await U.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",r.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),he.success("Page updated!")},onError:()=>he.error("Failed to update page")}),{data:l=[],isLoading:o}=pt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await U.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=Mt({mutationFn:async d=>{if(!(r!=null&&r.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:m}=await U.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:r.id}).select("token").single();if(m)throw m;return`${window.location.origin}/connect/${r.slug}?t=${u.token}`}});return{intakePage:r,isLoading:n,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function U0t({value:s,onChange:t,userId:r,placeholder:n}){const[a,i]=k.useState(!1),[l,o]=k.useState([]),[c,d]=k.useState(!1),[u,m]=k.useState(0),f=k.useRef(null),x=k.useRef(null);k.useEffect(()=>{const _=b=>{f.current&&!f.current.contains(b.target)&&i(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]),k.useEffect(()=>{x.current&&clearTimeout(x.current);const _=s.trim();if(!r||_.length<1||_.includes("@")&&_.indexOf("@")>0&&/\S+@\S+\.\S+/.test(_)){o([]);return}return x.current=setTimeout(async()=>{d(!0);const b=`%${_}%`,j=U,{data:N,error:C}=await j.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r).not("email","is",null).or(`first_name.ilike.${b},last_name.ilike.${b},email.ilike.${b}`).order("first_name",{ascending:!0}).limit(8);d(!1),!C&&N&&(o(N),m(0),i(N.length>0))},180),()=>{x.current&&clearTimeout(x.current)}},[s,r]);const y=_=>{_.email&&(t(_.email),i(!1))};return e.jsxs("div",{ref:f,className:"relative",children:[e.jsx(Ne,{id:"gmail-to",value:s,onChange:_=>t(_.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:_=>{!a||l.length===0||(_.key==="ArrowDown"?(_.preventDefault(),m(b=>Math.min(b+1,l.length-1))):_.key==="ArrowUp"?(_.preventDefault(),m(b=>Math.max(b-1,0))):_.key==="Enter"?(_.preventDefault(),y(l[u])):_.key==="Escape"&&i(!1))},placeholder:n||"Start typing a name or email...",autoComplete:"off"}),a&&e.jsx("div",{className:"absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-72 overflow-y-auto",children:c&&l.length===0?e.jsxs("div",{className:"px-3 py-2 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(ls,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((_,b)=>{const j=[_.first_name,_.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>m(b),onClick:()=>y(_),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${b===u?"bg-accent":"bg-popover"}`,children:[e.jsx(qi,{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)})})]})}const eje=25*1024*1024,XGe=Math.floor(6.5*1024*1024),A9s=750*1024,vj=50,M9s=["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 yV(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function I9s(s){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>{const a=n.result;t(a.split(",")[1])},n.onerror=r,n.readAsDataURL(s)})}function bj(s,t){let r=s.replace(/\{\{first_name\}\}/gi,t.first_name).replace(/\{\{last_name\}\}/gi,t.last_name||"").replace(/\{\{full_name\}\}/gi,`${t.first_name} ${t.last_name||""}`.trim());return t.updateLink&&(r=r.replace(/\{\{update_link\}\}/gi,t.updateLink)),r}function uw({open:s,onOpenChange:t,contact:r,bulkContacts:n,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o}){const{user:c}=Cs(),d=is(),{isReady:u,settings:m}=tD(),{data:f}=pye(),[x,y]=k.useState(!1),{intakePage:_}=vye(),b=_?`https://contacts.relevelup.com/${_.slug}`:null,j=!!n&&n.length>0,N=u,C=j?n:r?[r]:[],A=C[0],E=j?Math.ceil(C.length/vj):1,D=j&&C.length>vj,[R,F]=k.useState((A==null?void 0:A.email)||""),[O,B]=k.useState(a),[K,Z]=k.useState(i),[Q,W]=k.useState(!1),[te,ne]=k.useState(!1),[ae,ue]=k.useState([]),me=k.useRef(new Map),[de,fe]=k.useState(a),[je,xe]=k.useState(i),[Ee,Me]=k.useState("composing"),[Oe,Ie]=k.useState(0),[ze,Ve]=k.useState(0),[Le,$e]=k.useState(0),[ve,Qe]=k.useState(0),we=k.useRef(!1),[nt,Se]=k.useState(null);k.useEffect(()=>{s&&(F((A==null?void 0:A.email)||""),fe(a),xe(i),B(bj(a,A||{first_name:""})),Z(bj(i,A||{first_name:""})),ne(!a&&!i),ue([]),me.current=new Map,et.current=null,Me("composing"),Ie(0),Ve(0),$e(0),Qe(0),we.current=!1,Se(null))},[s,A,a,i]);const Ge=async Ut=>{const ht=Ut.target.files;if(!ht)return;const Jt=ae.reduce((Xs,js)=>Xs+js.size,0),Ms=[];let ts=Jt;for(const Xs of Array.from(ht)){if(!M9s.includes(Xs.type)){he.error(`${Xs.name}: Unsupported file type`);continue}if(ts+Xs.size>eje){he.error(`Total attachments exceed ${yV(eje)} limit`);break}try{const js=await I9s(Xs);Ms.push({name:Xs.name,type:Xs.type,size:Xs.size,data:js}),ts+=Xs.size}catch{he.error(`Failed to read ${Xs.name}`)}}ue(Xs=>[...Xs,...Ms]),Ut.target.value=""},We=Ut=>{const ht=ae[Ut];ht&&me.current.delete(`${ht.name}::${ht.size}`),ue(Jt=>Jt.filter((Ms,ts)=>ts!==Ut))},Ce=async()=>{if(ae.length===0||!c)return{inline:[],paths:[]};const Ut=[],ht=[];for(const Jt of ae){const Ms=`${Jt.name}::${Jt.size}`,ts=me.current.get(Ms);if(ts){ht.push(ts);continue}if(Jt.size<=A9s){Ut.push(Jt);continue}const Xs=Jt.name.replace(/[^a-zA-Z0-9._-]/g,"_"),js=`${c.id}/${Date.now()}-${Xs}`,$s=atob(Jt.data),Js=new Uint8Array($s.length);for(let Er=0;Er<$s.length;Er++)Js[Er]=$s.charCodeAt(Er);const{error:or}=await U.storage.from("campaign-attachments").upload(js,new Blob([Js],{type:Jt.type}),{contentType:Jt.type,upsert:!1});if(or)throw new Error(`Failed to upload ${Jt.name}: ${or.message}`);me.current.set(Ms,js),ht.push(js)}return{inline:Ut,paths:ht}},qe=Ut=>{if(!/<[a-z][\s\S]*>/i.test(Ut)||typeof window>"u")return Ut;const ht=Ut.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,""),Jt=document.createElement("div");return Jt.innerHTML=ht,(Jt.textContent||Jt.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},et=k.useRef(null),Ze=Ut=>{const ht=/<[a-z][\s\S]*>/i.test(Ut.body),Jt=ht?qe(Ut.body):Ut.body;et.current=ht?{plain:Jt,html:Ut.body}:null,fe(Ut.subject),xe(Jt),B(bj(Ut.subject,A||{first_name:""})),Z(bj(Jt,A||{first_name:""})),ne(!1)},rt=Ut=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(Ut)?Ut:Ut.split(/\n\n+/).map(ht=>`

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

`).join(""),ct=(Ut,ht)=>{const Jt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let Ms=Ut.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(Xs,js,$s,Js,or)=>{if(!Js||/^(mailto:|tel:|#)/i.test(Js)||Js.includes("/bulk-email-track")||Js.includes("/ses-campaign-track"))return Xs;const Er=`${Jt}?s=${ht}&t=click&u=${encodeURIComponent(Js)}`;return``});const ts=``;return/<\/body>/i.test(Ms)?Ms=Ms.replace(/<\/body>/i,`${ts}`):Ms=`${Ms}${ts}`,Ms},vt=async Ut=>{if(!(Ut!=null&&Ut.email))return he.error("Please enter a recipient email"),!1;const ht=Ut||{first_name:""},Jt=bj(de,ht),Ms=et.current,ts=Ms&&je===Ms.plain,Xs=bj(ts?Ms.html:je,ht);let js=ts?Xs:rt(Xs);const $s=c&&Ut.id?crypto.randomUUID():null;$s&&(js=ct(js,$s));try{if(c&&Ut.email){const Er=new Date(Date.now()-6e5).toISOString(),{data:Sr}=await U.from("bulk_email_sends").select("id").eq("user_id",c.id).eq("contact_email",Ut.email).eq("subject",Jt).gte("sent_at",Er).limit(1);if(Sr&&Sr.length>0)return console.log(`Skipping duplicate send to ${Ut.email} (same subject within 10 min)`),he.info(`Skipped ${Ut.first_name||Ut.email} — already sent this in the last 10 min`),!0}const{inline:Js,paths:or}=await Ce();if(N){const Er=(m==null?void 0:m.display_name)||"ReLevelUp",Sr=`${Er.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Gr=`${Er} <${Sr}>`;let Yr=or[0];if(!Yr&&Js.length>0&&c){const gs=Js[0],mi=gs.name.replace(/[^a-zA-Z0-9._-]/g,"_"),In=`${c.id}/${Date.now()}-${mi}`,Br=atob(gs.data),ps=new Uint8Array(Br.length);for(let Qr=0;Qr({name:Gr,type:Yr,data:Fn})),attachment_paths:or}});if(Sr)throw Sr;if(!(Er!=null&&Er.success))throw new Error((Er==null?void 0:Er.error)||"Failed to send")}if(c&&Ut.id&&$s){await U.from("bulk_email_sends").insert({id:$s,user_id:c.id,contact_id:Ut.id,contact_email:Ut.email,subject:Jt,source:N?"ses_bulk":"sphere_gaps"});try{await U.from("contact_touch_logs").insert({owner_user_id:c.id,contact_id:Ut.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Jt}`,completed_at:new Date().toISOString()})}catch(Er){console.warn("touch log insert failed",Er)}}return!0}catch(Js){return console.error("Send error:",Js),he.error("Failed to send to "+Ut.first_name+": "+(Js instanceof Error?Js.message:"Unknown error")),!1}},kt=()=>{const Ut=Oe*vj;return C.slice(Ut,Ut+vj)},St=async()=>{if(!O||!K){he.error("Please fill in subject and message");return}const Ut=kt();W(!0),Me("sending");let ht=0,Jt=0;for(let ts=0;tssetTimeout(js,150));Ve(ts=>ts+ht),$e(ts=>ts+Jt),W(!1),d.invalidateQueries({queryKey:["bulk-email-sends"]}),d.invalidateQueries({queryKey:["contact-touch-logs"]}),d.invalidateQueries({queryKey:["contacts-last-touch"]}),Oe>=E-1||we.current?Me("all_done"):Me("batch_complete")},Yt=async()=>{if(!O||!K){he.error("Please fill in subject and message");return}if(N&&f&&!f.hasVerifiedSes&&!f.hasGmail){y(!0);return}if(!j){const Ut=A||{id:"",first_name:"",last_name:"",email:R.trim()};if(!Ut.email){he.error("Please enter a recipient email");return}W(!0);try{await vt(Ut)&&(d.invalidateQueries({queryKey:["bulk-email-sends"]}),he.success("Email sent successfully!"),t(!1),o==null||o())}finally{W(!1)}return}await St()},es=async()=>{Ie(Ut=>Ut+1),Qe(0),await new Promise(Ut=>setTimeout(Ut,50)),await St()};k.useEffect(()=>{},[Oe]);const zs=()=>{if(Q){we.current=!0;return}t(!1),o==null||o()},sr=Oe*vj,ms=Math.min(sr+vj,C.length),gt=j&&C.length>0?Math.round((ze+Le)/C.length*100):0;return e.jsxs(vs,{open:s,onOpenChange:zs,children:[e.jsxs(ys,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:`h-5 w-5 ${N?"text-orange-500":"text-red-500"}`}),j?`Send to ${C.length} Contacts`:"Compose Email"]}),N?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",m==null?void 0:m.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,j&&Ee==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[C.length," contacts"]}),". You'll review each personalized email before sending."]})]}),Ee==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(ls,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",Oe+1," of ",E,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ve," of ",kt().length," in this batch"]})]}),e.jsx(ki,{value:ve/kt().length*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",ze+Le," / ",C.length]}),e.jsxs("span",{children:[ze," sent • ",Le," failed"]})]}),e.jsx(q,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{we.current=!0},children:"Stop Sending"})]}),Ee==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(qn,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Batch ",Oe+1," Complete!"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ze," sent, ",Le," failed so far"]})]}),e.jsx(ki,{value:gt,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[C.length-ze-Le," contacts remaining (",E-Oe-1," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",className:"flex-1",onClick:zs,children:"Done for Now"}),e.jsxs(q,{className:"flex-1 gap-2",onClick:es,children:[e.jsx(hn,{className:"h-4 w-4"}),"Send Next ",Math.min(vj,C.length-ms)," Contacts"]})]})]}),Ee==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(qn,{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:[ze," emails sent successfully",Le>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Le," failed"]})]})]}),e.jsx(q,{className:"w-full",onClick:zs,children:"Close"})]}),Ee==="composing"&&e.jsxs("div",{className:"space-y-4",children:[te?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(En,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>ne(!1),className:"h-7 px-2 text-xs",children:[e.jsx($r,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(E9s,{onSelect:Ze})]}):e.jsxs(q,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ne(!0),children:[e.jsx(En,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(cl,{}),!j&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"gmail-to",children:"To"}),e.jsx(U0t,{value:R,onChange:F,userId:c==null?void 0:c.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(Ne,{id:"gmail-subject",value:O,onChange:Ut=>{B(Ut.target.value),fe(Ut.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(ce,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{Z(Ut=>Ut+"{{first_name}}"),xe(Ut=>Ut+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(Xe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{Z(Ut=>Ut+"{{last_name}}"),xe(Ut=>Ut+"{{last_name}}")},children:"{{last_name}}"}),b&&e.jsx(Xe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const Ut=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;Z(ht=>ht+Ut),xe(ht=>ht+Ut)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(pr,{id:"gmail-body",value:K,onChange:Ut=>{Z(Ut.target.value),xe(Ut.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),j&&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(q,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var Ut;return(Ut=document.getElementById("gmail-attachments"))==null?void 0:Ut.click()},disabled:Q,children:[e.jsx(iS,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",yV(eje)," 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:Ge})]}),ae.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ae.map((Ut,ht)=>e.jsxs(Xe,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(iS,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:Ut.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",yV(Ut.size),")"]}),e.jsx("button",{type:"button",onClick:()=>We(ht),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx($r,{className:"h-3 w-3"})})]},ht))}),N&&ae.some(Ut=>Ut.size>XGe)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",yV(XGe)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),j?e.jsxs(q,{onClick:()=>{Se(C[0]||null),Me("reviewing")},disabled:!O||!K,className:"gap-2",children:["Review Emails",e.jsx(ci,{className:"h-4 w-4"})]}):e.jsxs(q,{onClick:Yt,disabled:Q||!O||!K||!R.trim(),className:"gap-2",children:[Q?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"}),Q?"Sending...":"Send Email"]})]})]}),Ee==="reviewing"&&j&&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."]}),D&&e.jsxs("p",{className:"text-xs text-amber-600 bg-amber-500/10 rounded-md px-2.5 py-1.5",children:["📦 ",C.length," contacts will be sent in ",E," batches of up to ",vj,". You'll confirm before each batch."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ce,{children:["Recipients (",C.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:C.map(Ut=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(nt==null?void 0:nt.id)===Ut.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>Se(Ut),children:[Ut.first_name," ",Ut.last_name," — ",Ut.email]},Ut.id))})]}),nt&&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(Ks,{className:"h-3.5 w-3.5"}),"Preview for ",nt.first_name," ",nt.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:"})," ",nt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",bj(de,nt)]})]}),e.jsx(cl,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:bj(je,nt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(q,{variant:"outline",onClick:()=>{Me("composing"),Se(null)},children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(q,{onClick:Yt,disabled:Q,className:"gap-2",children:[Q?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"}),D?`Send First ${vj}`:`Send to ${C.length}`]})]})]})]}),e.jsx(xye,{open:x,onOpenChange:y,hasPending:!!(f!=null&&f.hasPendingSes),pendingEmails:f==null?void 0:f.pendingEmails})]})}function P9s(){const s=qr(),{data:t}=Lp(),{data:r}=TB(),n=Rge(),{isGmailConnected:a,gmailEmail:i}=Cm(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,m]=k.useState(new Set),f=Ax(new Date),x=Dc(f,30),y=E=>{if(!E)return null;const D=E.split(/[-/T]/);if(D.length<3)return null;const R=parseInt(D[1],10)-1,F=parseInt(D[2],10);return isNaN(R)||isNaN(F)?null:new Date(f.getFullYear(),R,F)},_=k.useMemo(()=>{if(!t)return[];const E=[];for(const D of t){if(D.birthday){const R=y(D.birthday);R&&(pc(R,f)||xS(R,f)&&gS(R,x))&&E.push({contact:D,type:"birthday",date:R,daysUntil:cg(R,f),dateStr:D.birthday})}if(D.home_anniversary){const R=y(D.home_anniversary);R&&(pc(R,f)||xS(R,f)&&gS(R,x))&&E.push({contact:D,type:"anniversary",date:R,daysUntil:cg(R,f),dateStr:D.home_anniversary})}if(D.wedding_anniversary){const R=y(D.wedding_anniversary);R&&(pc(R,f)||xS(R,f)&&gS(R,x))&&E.push({contact:D,type:"wedding_anniversary",date:R,daysUntil:cg(R,f),dateStr:D.wedding_anniversary})}}return E.sort((D,R)=>D.daysUntil-R.daysUntil),E},[t]),b=E=>E==="birthday"?"Birthday":E==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",j=async E=>{const D=(r==null?void 0:r.find(R=>R.name==="Call"))||(r==null?void 0:r[0]);if(D)try{await n.mutateAsync({contactId:E.contact.id,actionTypeId:D.id,notes:`${b(E.type)} outreach`}),m(R=>new Set(R).add(`${E.contact.id}-${E.type}`)),Dn({title:"Touch logged!",description:`Logged outreach for ${E.contact.first_name}`})}catch{Dn({title:"Error",description:"Failed to log touch",variant:"destructive"})}},N=E=>{const D=`${E.contact.first_name}${E.contact.last_name?" "+E.contact.last_name:""}`,R=E.type==="birthday"?"birthday":E.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",F=new URLSearchParams({cardType:R,contactId:E.contact.id,name:D,...E.contact.address?{address:E.contact.address}:{},...(E.type==="anniversary"||E.type==="wedding_anniversary")&&E.dateStr?{date:E.dateStr}:{}});s(`/mission-control/card-studio?${F.toString()}`)},C=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(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(xu,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(Xe,{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(Pe,{className:"space-y-2",children:[_.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(_m,{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,D)=>{var B,K;const R=`${E.contact.id}-${E.type}`,F=u.has(R),O=`${((B=E.contact.first_name)==null?void 0:B[0])||""}${((K=E.contact.last_name)==null?void 0:K[0])||""}`.toUpperCase();return e.jsxs("div",{className:zt("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(Wn,{className:zt("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(Kn,{className:zt("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:O})}),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(Xe,{variant:"outline",className:zt("text-[10px] shrink-0 whitespace-nowrap",A(E.daysUntil)),children:C(E.daysUntil)})]}),e.jsxs("div",{className:zt("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(_m,{className:"h-3 w-3"})," Birthday"]}):E.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(yi,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pn,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:As(E.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[E.contact.phone&&e.jsx(q,{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(Mn,{className:"h-3.5 w-3.5"})})}),E.contact.phone&&e.jsx(q,{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(Ui,{className:"h-3.5 w-3.5"})})}),E.contact.email&&e.jsx(q,{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(Ks,{className:"h-3.5 w-3.5"})}),e.jsx(q,{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(bn,{className:"h-3.5 w-3.5"})}),e.jsxs(q,{variant:"ghost",size:"sm",className:zt("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:()=>N(E),children:[e.jsx(Ir,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(q,{variant:"ghost",size:"icon",className:zt("h-7 w-7",F&&"text-green-600"),title:"Log a touch",disabled:F||n.isPending,onClick:()=>j(E),children:e.jsx(qn,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${E.contact.id}`),children:e.jsx(Nn,{className:"h-3.5 w-3.5"})})]})]},`${R}-${D}`)})]})]}),a&&l&&e.jsx(uw,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function L9s(s){const[t,r]=k.useState([]),[n,a]=k.useState(!1),{data:i,isLoading:l}=pt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await U.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await U.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const m=u.map(y=>y.contact_id).filter(Boolean);let f={};if(m.length>0){const{data:y}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",m);(y||[]).forEach(_=>{f[_.id]=_})}const x=u.map(y=>y.auth_user_id).filter(Boolean);if(x.length>0){const{data:y}=await U.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",x);(y||[]).forEach(_=>{const b=u.find(j=>j.auth_user_id===_.user_id);b&&!b.contact_id&&_.contact_id&&(b.contact_id=_.contact_id),b&&!f[b.contact_id||""]&&_.name&&(f[b.contact_id||b.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 _,b;return{...y,contact_name:f[y.contact_id||y.auth_user_id||""]?`${f[y.contact_id||y.auth_user_id||""].first_name} ${f[y.contact_id||y.auth_user_id||""].last_name||""}`.trim():null,contact_email:((_=f[y.contact_id||y.auth_user_id||""])==null?void 0:_.email)||null,contact_phone:((b=f[y.contact_id||y.auth_user_id||""])==null?void 0:b.phone)||null}})},enabled:!!s,refetchInterval:6e4});k.useEffect(()=>{if(!s)return;const u=U.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},m=>{m.eventType==="INSERT"?r(f=>f.find(y=>y.id===m.new.id)?f:[m.new,...f]):m.eventType==="UPDATE"?r(f=>f.map(x=>x.id===m.new.id?{...x,...m.new}:x)):m.eventType==="DELETE"&&r(f=>f.filter(x=>x.id!==m.old.id))}).subscribe(m=>{m==="SUBSCRIBED"&&a(!0)});return()=>{U.removeChannel(u)}},[s]);const o=n&&t.length>0?D9s([...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 D9s(s){const t=new Set;return s.filter(r=>t.has(r.id)?!1:(t.add(r.id),!0))}const R9s={property_view:{label:"Viewed",icon:Nn,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:xl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:yi,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function O9s(){const{user:s}=Cs(),t=qr(),{isGmailConnected:r,gmailEmail:n}=Cm(),{leadSite:a}=hf(),{count:i}=L9s(a==null?void 0:a.id),[l,o]=k.useState(!1),[c,d]=k.useState(null),{data:u,isLoading:m}=pt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:j,error:N}=await U.rpc("get_lead_site_activity",{_user_id:s.id});if(N)throw N;return j},enabled:!!s,refetchInterval:6e4});if(m||!(u!=null&&u.has_site))return null;const f=(u.activities||[]).filter(j=>j.visitor_name&&j.visitor_name!=="Site Visitor"),x=f.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,b=j=>{if(j.visitor_email)if(r){const N=(j.visitor_name||"").split(" ");d({id:j.contact_id||"",first_name:N[0]||"",last_name:N.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(Ql,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Website Activity"}),i>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[11px] font-semibold",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"})]}),i," Live"]})]})]}),e.jsxs(q,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(ci,{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(xl,{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:x.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(Nn,{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(yi,{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"})]})]})]}),f.length>0?e.jsxs("div",{className:"space-y-2",children:[f.slice(0,5).map((j,N)=>{const C=R9s[j.activity_type],A=C.icon,E=Nl(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 ${C.bgColor}`,children:e.jsx(A,{className:`h-3.5 w-3.5 ${C.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:C.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(q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>b(j),children:e.jsx(Ks,{className:"h-3.5 w-3.5"})}),j.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${j.visitor_phone}`,children:e.jsx(Mn,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${j.visitor_phone}`,children:e.jsx(Ui,{className:"h-3.5 w-3.5"})})]}),j.contact_id&&e.jsx(q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${j.contact_id}`),children:e.jsx(Ia,{className:"h-3.5 w-3.5"})})]})]},`${j.activity_type}-${j.occurred_at}-${N}`)}),f.length>5&&e.jsxs(q,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",f.length-5," more activities",e.jsx(ci,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 text-center",children:[e.jsx(xm,{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(q,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(ci,{className:"h-3.5 w-3.5 ml-1"})]})]})}),r&&c&&e.jsx(uw,{open:l,onOpenChange:o,contact:c,gmailEmail:n})]})}const QGe={Crown:Gf,FileText:En,Users:Dr,Globe:Ql,Star:fa,Phone:Mn,MessageSquare:Ui,PenTool:oS,Video:bn,Gift:Di},F9s={"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 z9s(){var qe,et,Ze,rt,ct,vt;const s=qr(),{user:t}=Cs(),{data:r}=H0(),{data:n}=Ect(),{data:a}=Lp(),{data:i}=TB(),{data:l}=Lct(),o=yQt(),c=_Ee(),d=xQt(90),u=Rge(),[m,f]=k.useState(null),[x,y]=k.useState(null),[_,b]=k.useState(!1),[j,N]=k.useState(""),[C,A]=k.useState(!1),[E,D]=k.useState(""),[R,F]=k.useState(Ime()),[O,B]=k.useState("cards"),[K,Z]=k.useState(!1),[Q,W]=k.useState(null),[te,ne]=k.useState(null),[ae,ue]=k.useState(""),{isGmailConnected:me,gmailEmail:de}=Cm(),fe=()=>{const kt=parseInt(E,10);if(isNaN(kt)||kt<1){Dn({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}F(kt),Pct(kt),A(!1),Dn({title:"Goal updated",description:`Weekly touch goal set to ${kt}`})},je=()=>{D(R.toString()),A(!0)};k.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:St}=await U.from("profiles").select("name").eq("id",t.id).single();St!=null&&St.name&&N(St.name.split(" ")[0])})()},[t==null?void 0:t.id]),k.useEffect(()=>{o.mutate()},[]);const xe=Ax(new Date),Ee=Dc(xe,7),Me=kt=>{if(!kt)return null;const St=kt.split(/[-/T]/);if(St.length<3)return null;const Yt=parseInt(St[1],10)-1,es=parseInt(St[2],10);return isNaN(Yt)||isNaN(es)?null:new Date(xe.getFullYear(),Yt,es)},Oe=(a==null?void 0:a.filter(kt=>{const St=Me(kt.birthday),Yt=Me(kt.home_anniversary);return St&&pc(St,xe)||Yt&&pc(Yt,xe)}))||[];a!=null&&a.filter(kt=>{if(!kt.birthday&&!kt.home_anniversary)return!1;const St=Yt=>{if(!Yt)return!1;const es=Me(Yt);return es?xS(es,xe)&&gS(es,Ee):!1};return St(kt.birthday)||St(kt.home_anniversary)}).slice(0,5);const Ie=[],ze=(i==null?void 0:i.find(kt=>kt.name==="Call"))||(i==null?void 0:i[0]);for(const kt of Oe){const St=Me(kt.birthday),Yt=Me(kt.home_anniversary),es=St&&pc(St,xe),zs=Yt&&pc(Yt,xe);es&&Ie.push({contact:kt,actionType:ze||{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:((Ze=(et=(qe=kt.tags)==null?void 0:qe[0])==null?void 0:et.relationship_type)==null?void 0:Ze.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),zs&&Ie.push({contact:kt,actionType:ze||{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:((vt=(ct=(rt=kt.tags)==null?void 0:rt[0])==null?void 0:ct.relationship_type)==null?void 0:vt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Le=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((kt,St)=>{var es,zs,sr;const Yt=i==null?void 0:i[St%((i==null?void 0:i.length)||1)];return Yt?{contact:kt,actionType:Yt,planName:"Quick Touch",relationshipTypeName:((sr=(zs=(es=kt.tags)==null?void 0:es[0])==null?void 0:zs.relationship_type)==null?void 0:sr.name)||"",monthNumber:0}:null}).filter(Boolean))||[],$e=[...Ie,...Le],ve=async(kt,St,Yt)=>{await u.mutateAsync({contactId:kt,actionTypeId:St,scriptUsedId:Yt}),b(!1),y(null)},Qe=kt=>{kt.script?(y(kt),b(!0)):ve(kt.contact.id,kt.actionType.id)},we=kt=>QGe[kt||"Phone"]||Mn,nt=kt=>QGe[kt||"Users"]||Dr,Se=(kt,St)=>kt.replace(/\{\{FirstName\}\}/g,St.first_name).replace(/\{\{LastName\}\}/g,St.last_name||"").replace(/\{\{AgentName\}\}/g,j||"there"),Ge=(kt,St)=>({Call:`Thinking of you, ${St}!`,Text:`Quick hello, ${St}`,Email:`Checking in, ${St}`,"Handwritten Note":`A note for ${St}`,Video:`Video message for ${St}`,Gift:`Something special for you, ${St}`})[kt]||`Hello ${St}!`,We=(kt,St,Yt)=>{const es=`sms:${kt}`;if(St&&Yt){const zs=Se(St,Yt);return`${es}?body=${encodeURIComponent(zs)}`}return es},Ce=(kt,St,Yt,es,zs)=>{const sr=`mailto:${kt}`,ms=[];if(zs){const gt=Yt||Ge(es||"Email",zs.first_name);if(ms.push(`subject=${encodeURIComponent(gt)}`),St){const Ut=Se(St,zs);ms.push(`body=${encodeURIComponent(Ut)}`)}}return ms.length>0?`${sr}?${ms.join("&")}`:sr};return e.jsxs(e.Fragment,{children:[e.jsxs(ws,{title:"Mission Control",description:"Your relationship-first contact system",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Mission Control"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsx(O9s,{}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-4",children:"Your Sphere"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:r==null?void 0:r.filter(kt=>kt.active).map(kt=>{const St=nt(kt.icon),Yt=(n==null?void 0:n[kt.id])||0,es=m===kt.id,zs=F9s[kt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{es?(f(null),s("/mission-control/contacts")):(f(kt.id),s(`/mission-control/contacts?type=${kt.id}`))},className:` flex items-center gap-2 px-4 py-3 rounded-lg border transition-all ${es?zs:"bg-card hover:bg-accent"} `,children:[e.jsx(St,{className:"h-5 w-5"}),e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:kt.name}),e.jsxs("div",{className:`text-sm ${es?"opacity-90":"text-muted-foreground"}`,children:[Yt," Contacts"]})]})]},kt.id)})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs(q,{onClick:()=>s("/mission-control/video/record"),className:"w-full bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(rf,{className:"h-4 w-4 mr-1"}),"Quick Video"]}),e.jsxs(q,{onClick:()=>s("/mission-control/contacts"),className:"w-full",variant:"outline",children:["View Contacts",e.jsx(Ia,{className:"h-4 w-4 ml-1"})]}),e.jsx(q,{variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"w-full",children:"Video Library"}),e.jsx(q,{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(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Ir,{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(q,{variant:O==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>B("cards"),title:"Card view",children:e.jsx(Ep,{className:"h-4 w-4"})}),e.jsx(q,{variant:O==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>B("table"),title:"Table view",children:e.jsx(Zf,{className:"h-4 w-4"})})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:$e.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(q,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):O==="table"?e.jsx(T9s,{actions:$e,onMarkComplete:ve,onViewScript:Qe,isLoading:u.isPending,buildSmsLink:We,buildEmailLink:Ce,onGmailCompose:me?kt=>{W(kt),Z(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[$e.map((kt,St)=>{var ht,Jt,Ms,ts,Xs,js,$s;const Yt=kt.isSpecialDate,es=kt.specialDateType,zs=Yt?es==="birthday"?_m:Pn:we(((ht=kt.actionType)==null?void 0:ht.icon)||null),sr=kt.contact.phone,ms=kt.contact.email,gt=Yt?es==="birthday"?"#EC4899":"#8B5CF6":((Jt=kt.actionType)==null?void 0:Jt.color)||"#3B82F6",Ut=Yt?es==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(Ms=kt.actionType)==null?void 0:Ms.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${Yt?"ring-2 ring-offset-2":""}`,style:Yt?{"--tw-ring-color":gt}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:gt},children:[e.jsx(zs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Ut})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${kt.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[kt.contact.first_name," ",kt.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[sr&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${kt.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(Mn,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:We(kt.contact.phone,(ts=kt.script)==null?void 0:ts.script_body,kt.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(Ui,{className:"h-3 w-3"}),"Text"]})]}),ms&&(me?e.jsxs("button",{onClick:()=>{W({id:kt.contact.id,first_name:kt.contact.first_name,last_name:kt.contact.last_name,email:kt.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(Ks,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Ce(kt.contact.email,(Xs=kt.script)==null?void 0:Xs.script_body,(js=kt.script)==null?void 0:js.email_subject,($s=kt.actionType)==null?void 0:$s.name,kt.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(Ks,{className:"h-3 w-3"}),"Email"]}))]}),Yt&&e.jsxs("button",{onClick:()=>{const Js=`${kt.contact.first_name}${kt.contact.last_name?" "+kt.contact.last_name:""}`,or=es==="birthday"?"birthday":"home_anniversary",Er=new URLSearchParams({cardType:or,contactId:kt.contact.id,name:Js,...kt.contact.address?{address:kt.contact.address}:{},...es==="anniversary"&&kt.contact.home_anniversary?{date:kt.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(Ks,{className:"h-3 w-3"}),"Send ",es==="birthday"?"Birthday":"Anniversary"," Card"]}),!sr&&!ms&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[kt.relationshipTypeName&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:kt.relationshipTypeName}),kt.monthNumber>0&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:["Month ",kt.monthNumber]})]}),kt.script&&e.jsx(q,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Qe(kt),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(q,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{ne(kt.contact.id),ue(`${kt.contact.first_name} ${kt.contact.last_name||""}`.trim())},children:[e.jsx(Xf,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(q,{size:"sm",className:"flex-1",onClick:()=>{var Js;return ve(kt.contact.id,kt.actionType.id,(Js=kt.script)==null?void 0:Js.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},kt.contact.id+St)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{variant:"ghost",className:"h-full w-full",children:[e.jsx(f0,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Sd,{children:e.jsx(ti,{onClick:()=>s("/mission-control/contacts"),children:"View all contacts"})})]})})]})})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"text-lg",children:"Momentum"}),e.jsxs(vs,{open:C,onOpenChange:A,children:[e.jsx(Yi,{asChild:!0,children:e.jsx("button",{onClick:je,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(Bo,{className:"h-4 w-4 text-muted-foreground hover:text-primary"})})}),e.jsxs(ys,{className:"sm:max-w-[360px]",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Set Weekly Goal"}),e.jsx(an,{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(ce,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(Ne,{id:"weekly-goal-ic",type:"number",min:"1",value:E,onChange:kt=>D(kt.target.value),placeholder:"20",onKeyDown:kt=>{kt.key==="Enter"&&fe()}})]}),e.jsx(q,{onClick:fe,className:"w-full",children:"Save Goal"})]})]})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx(ki,{value:Math.min(c.actionsThisWeek/R*100,100),className:"h-3 w-full max-w-full"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ld,{className:"h-5 w-5 text-orange-500"}),e.jsxs("span",{className:"font-medium",children:[c.actionsThisWeek," / ",R]}),e.jsx("span",{className:"text-muted-foreground",children:"Actions Completed This Week"})]}),c.streak>0&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-lg",children:"🔥"}),e.jsx("span",{className:"font-medium",children:"Great Job!"}),e.jsxs("span",{className:"text-muted-foreground",children:["Keep Your Streak Going! (",c.streak," days)"]})]}),d.count>0&&e.jsxs("button",{onClick:()=>s("/mission-control/contacts?filter=not-touched-90"),className:"flex items-start gap-2 text-sm pt-2 border-t w-full text-left hover:bg-accent/50 -mx-4 px-4 py-2 rounded-md transition-colors",children:[e.jsx(jn,{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(Ia,{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(Kct,{}),e.jsx(P9s,{})]})]}),e.jsx(vs,{open:_,onOpenChange:b,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{className:"flex items-center gap-2",children:x&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:x.actionType.color||"#3B82F6"}}),x.actionType.name," Script"]})})}),x&&x.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:[x.contact.first_name," ",x.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:Se(x.script.script_body,x.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",className:"flex-1",onClick:()=>b(!1),children:"Close"}),e.jsx(q,{className:"flex-1",onClick:()=>{var kt;return ve(x.contact.id,x.actionType.id,(kt=x.script)==null?void 0:kt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(w9s,{})]}),me&&Q&&e.jsx(uw,{open:K,onOpenChange:Z,contact:Q,gmailEmail:de}),e.jsx(yye,{open:!!te,onOpenChange:kt=>!kt&&ne(null),contactId:te||"",contactName:ae})]})}const B9s=[{value:"bidirectional",label:"Two-Way",icon:Uu,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:qu,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:gm,tooltip:"Only pull BoldTrail → Agent OS"}];function uCe({value:s,onChange:t,size:r="default"}){const n=r==="sm"?"text-xs":"text-sm";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:`font-medium ${n} text-muted-foreground`,children:"Sync Direction"}),e.jsx(SP,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:B9s.map(a=>e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(tA,{value:a.value,"aria-label":a.tooltip,className:`gap-1.5 ${n} border border-transparent data-[state=on]:!bg-primary data-[state=on]:!text-primary-foreground data-[state=on]:!border-primary data-[state=on]:shadow-sm`,children:[e.jsx(a.icon,{className:r==="sm"?"h-3 w-3":"h-4 w-4"}),a.label]})}),e.jsx(Sc,{children:a.tooltip})]},a.value))})]})}function JGe(){const s=is(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(null),[m,f]=k.useState(null),[x,y]=k.useState(0),_=k.useRef(!1),{data:b}=pt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:O,error:B}=await U.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(B)throw B;return O}}),j=(b==null?void 0:b.sync_direction)||"bidirectional",N=d??j,C=Mt({mutationFn:async()=>{const{data:O,error:B}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(B)throw B;if(O!=null&&O.error)throw new Error(O.error);return O},onSuccess:O=>{u(null),a(O),r(!0)},onError:O=>{he.error(O.message||"Failed to generate sync preview")}}),A=Mt({mutationFn:async()=>{_.current=!1,f("Initializing sync..."),y(5);const{data:O,error:B}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:N}});if(B)throw B;if(O!=null&&O.error)throw new Error(O.error);const K=O;let Z=K.sync_log_id,Q=K.next_phase,W=K.next_offset,te=K.push_total||0,ne=K.pull_total||0,ae=K.update_total||0,ue=0,me=0,de=0;for(;Q!=="finalize"&&!_.current;){const xe=te+ne+ae;Q==="fetch_bt"?f("Fetching BoldTrail contacts..."):Q==="analyze"?(f("Analyzing contacts..."),y(15)):Q==="push"?(f(`Pushing contacts to BoldTrail... (${ue}/${te})`),y(xe>0?ue/xe*90:0)):Q==="pull"?(f(`Pulling contacts from BoldTrail... (${me}/${ne})`),y(xe>0?(te+me)/xe*90:0)):Q==="update"&&(f(`Updating existing contacts... (${de}/${ae})`),y(xe>0?(te+ne+de)/xe*90:0));const{data:Ee,error:Me}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:Q,offset:W,sync_log_id:Z,sync_direction:N}});if(Me)throw Me;if(Ee!=null&&Ee.error)throw new Error(Ee.error);const Oe=Ee;ue+=Oe.chunk_pushed||0,me+=Oe.chunk_pulled||0,de+=Oe.chunk_updated||0,Oe.push_total!==void 0&&(te=Oe.push_total||0),Oe.pull_total!==void 0&&(ne=Oe.pull_total||0),Oe.update_total!==void 0&&(ae=Oe.update_total||0),Oe.progress&&f(Oe.progress),Q=Oe.next_phase,W=Oe.next_offset}f("Finalizing sync..."),y(95);const{data:fe,error:je}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:Z,sync_direction:N}});if(je)throw je;return y(100),fe},onSuccess:O=>{f(null),y(0),r(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const B=[`Pushed ${O.contacts_pushed||0}`,`pulled ${O.contacts_pulled||0}`,`updated ${O.contacts_updated||0}`,`skipped ${O.contacts_skipped||0} duplicates`];he.success(`Sync complete! ${B.join(", ")}.`)},onError:O=>{f(null),y(0),he.error(O.message||"Sync failed")}});if(!(b!=null&&b.connected))return null;const E=N==="pull_only"?0:(n==null?void 0:n.to_push)??0,D=N==="push_only"?0:(n==null?void 0:n.to_pull)??0,R=(n==null?void 0:n.to_update)??0,F=E>0||D>0||R>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{variant:"outline",size:"icon",onClick:()=>C.mutate(),disabled:C.isPending,className:"shrink-0",children:C.isPending?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Uu,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Sc,{children:"Sync with BoldTrail"})]}),e.jsx(vs,{open:t,onOpenChange:O=>{A.isPending||r(O)},children:e.jsxs(ys,{className:"sm:max-w-lg",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Uu,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(an,{children:"Review what will happen when you sync your contacts."})]}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(uCe,{value:N,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 ${N==="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(qu,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${N==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:D}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(gm,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-amber-600",children:R}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(aP,{className:"h-3 w-3"})," To update"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:n.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Dr,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",n.agent_os_total," contacts · BoldTrail: ",n.boldtrail_total," contacts"]}),R>0&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center bg-amber-50 dark:bg-amber-950/30 rounded-md p-2",children:[e.jsx(aP,{className:"h-3 w-3 inline mr-1"}),R," contacts have missing fields that will be filled from the other system"]}),E>0&&e.jsxs(E0,{open:i,onOpenChange:l,children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qu,{className:"h-3 w-3 text-emerald-600"}),E," contacts to push to BoldTrail"]}),e.jsx(Co,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(M0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[n.push_preview.map((O,B)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:O.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:O.email})]},B)),n.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",n.to_push-20," more"]})]})})]}),D>0&&e.jsxs(E0,{open:o,onOpenChange:c,children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gm,{className:"h-3 w-3 text-blue-600"}),D," contacts to pull from BoldTrail"]}),e.jsx(Co,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(M0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[n.pull_preview.map((O,B)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:O.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:O.email})]},B)),n.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",n.to_pull-20," more"]})]})})]}),!F&&!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(ki,{value:x||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:m||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(q,{variant:"outline",onClick:()=>r(!1),disabled:A.isPending,children:"Cancel"}),e.jsxs(q,{onClick:()=>A.mutate(),disabled:A.isPending||!F,className:"gap-2",children:[A.isPending?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Uu,{className:"h-4 w-4"}),A.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const $9s=()=>{const{user:s}=Cs();return pt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(r)throw r;return t},enabled:!!s})},bye=s=>{const{user:t}=Cs();return pt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let r=U.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),r=r.gte("completed_at",i.toISOString())}const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})},o6e=()=>{const{user:s}=Cs();return pt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("relationship_type_popby_defaults").select("*");if(r)throw r;return t},enabled:!!s})},q0t=()=>{const{user:s}=Cs();return pt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_popby_settings").select("*");if(r)throw r;return t},enabled:!!s})},U9s=()=>{const{data:s}=Lp();H0();const{data:t}=bye(),{data:r}=q0t(),{data:n}=o6e(),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;n==null||n.forEach(d=>i.set(d.relationship_type_id,d.frequency_days));const l=new Map;r==null||r.filter(d=>d.is_active).forEach(d=>{l.set(d.contact_id,d.frequency_days)});const o=Ax(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(b=>i.get(b.relationship_type_id)).filter(b=>b!==void 0);_.length>0&&(u=Math.min(..._))}const m=a.get(d.id)||null,f=m?lv(o,Ax(new Date(m))):null,x=f===null||f>=u,y=x&&f!==null?f-u:0;return{...d,lastPopby:m,daysSinceLastPopby:f,frequencyDays:u,isDue:x,daysOverdue:y}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},V0t=()=>U9s().filter(t=>t.isDue),q9s=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{const{error:n}=await U.from("popby_items").insert({...r,owner_user_id:t==null?void 0:t.id});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),Dn({title:"Popby item created!"})},onError:r=>{Dn({title:"Error creating popby item",description:r.message,variant:"destructive"})}})},V9s=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{const n=new Date().toISOString(),{error:a}=await U.from("popby_logs").insert({...r,owner_user_id:t==null?void 0:t.id,completed_at:n});if(a)throw a;try{const{data:i}=await U.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await U.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:r.contact_id,action_type_id:i.id,notes:r.notes??"Pop-by logged",completed_at:n})}catch(i){console.error("Failed to log corresponding touch for popby",i)}},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-logs"]}),s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),Dn({title:"Popby logged!"})},onError:r=>{Dn({title:"Error logging popby",description:r.message,variant:"destructive"})}})},H9s=()=>{const s=is(),{user:t}=Cs();return Mt({mutationFn:async r=>{const{error:n}=await U.from("relationship_type_popby_defaults").upsert({...r,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),Dn({title:"Frequency updated!"})},onError:r=>{Dn({title:"Error updating frequency",description:r.message,variant:"destructive"})}})},G9s=()=>{const{data:s}=bye(30),t=V0t(),r=new Date;r.setDate(r.getDate()-7);const n=(s==null?void 0:s.filter(i=>new Date(i.completed_at)>=r).length)||0,a=(s==null?void 0:s.length)||0;return{thisWeekCount:n,thisMonthCount:a,dueCount:t.length}};function W9s(){const{user:s}=Cs();return pt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function H0t(s){const{data:t}=W9s(),{data:r}=q0t(),{data:n}=o6e(),{data:a}=j9s();return k.useMemo(()=>{const i=a==null?void 0:a.find(b=>b.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=Ax(new Date);if(l&&!gS(l,o))return{nextTouchDate:l,daysUntil:lv(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(b=>b.contact_id===s.id))||[]).sort((b,j)=>new Date(j.completed_at).getTime()-new Date(b.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let m=90;const f=r==null?void 0:r.find(b=>b.contact_id===s.id&&b.is_active);if(f)m=f.frequency_days;else if(s.tags&&s.tags.length>0){const b=s.tags.map(j=>{const N=n==null?void 0:n.find(C=>C.relationship_type_id===j.relationship_type_id);return N==null?void 0:N.frequency_days}).filter(j=>j!==void 0);b.length>0&&(m=Math.min(...b))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:m,lastTouchDate:null,snoozedUntil:null};const x=Dc(Ax(u),m),y=lv(x,o);let _;return y<0?_="overdue":y<=7?_="due-soon":_="on-track",{nextTouchDate:x,daysUntil:y,status:_,frequencyDays:m,lastTouchDate:u,snoozedUntil:null}},[s,t,r,n,a])}function hCe({contact:s}){const t=H0t(s),n=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:go,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:jn,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:qn,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:Xf,text:`Snoozed until ${As(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:vn,text:"Never touched",className:"border-dashed"}}})(),a=n.icon;return e.jsxs(Xe,{variant:n.variant,className:zt("gap-1",n.className),children:[e.jsx(a,{className:"h-3 w-3"}),n.text]})}function K9s({contact:s,onLogTouch:t,onSnooze:r}){const n=H0t(s),a=k9s(),[i,l]=k.useState(!1),o=()=>{switch(n.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(n.status){case"overdue":return e.jsx(go,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(jn,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(qn,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(Xf,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(vn,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(n.status){case"overdue":return`${Math.abs(n.daysUntil)} days overdue`;case"due-soon":return n.daysUntil===0?"Due today!":`Due in ${n.daysUntil} days`;case"on-track":return`On track - ${n.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${n.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},u=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:zt("font-medium",o()),children:d()})]}),n.status==="snoozed"&&n.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",As(n.snoozedUntil,"MMMM d, yyyy")]}),n.status!=="snoozed"&&n.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",As(n.nextTouchDate,"MMMM d, yyyy")]}),n.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",As(n.lastTouchDate,"MMM d, yyyy")]}),n.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",n.frequencyDays," days"]}),n.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(q,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(q,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),n.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(q,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(Xf,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(n.status==="overdue"||n.status==="due-soon"||n.status==="never-touched")&&t&&e.jsx(q,{size:"sm",className:"flex-1",variant:n.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(yye,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const tje=768;function rD(){const[s,t]=k.useState(void 0);return k.useEffect(()=>{const r=window.matchMedia(`(max-width: ${tje-1}px)`),n=()=>{t(window.innerWidthr.removeEventListener("change",n)},[]),!!s}function Y9s(){const{user:s}=Cs(),{hasLeadSite:t,leadSite:r}=hf(),{data:n,isLoading:a}=pt({queryKey:["website-active-contacts",s==null?void 0:s.id,r==null?void 0:r.id],queryFn:async()=>{if(!r)return new Set;const{data:i}=await U.from("lead_site_visitors").select("contact_id").eq("lead_site_id",r.id).not("contact_id","is",null),{data:l}=await U.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",r.id).not("contact_id","is",null),o=new Set;return(i||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),(l||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),o},enabled:!!s&&t,staleTime:5*60*1e3});return{activeContactIds:n??new Set,hasLeadSite:t,isLoading:a}}const Z9s={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"}},X9s={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 G7({score:s,showScore:t=!1,showTooltip:r=!0,size:n="sm",className:a}){const i=Z9s[s.status],l=X9s[n],o=e.jsxs("div",{className:zt("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:zt("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return r?e.jsx(J_,{children:e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:o}),e.jsx(Sc,{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:zt("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(ki,{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 Q9s=[{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}],vV=s=>{if(!s||!s.trim())return null;const t=s.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;const r=t.match(/^(\d{1,2})[\/\-](\d{1,2})(?:[\/\-](\d{2,4}))?$/);if(r){const a=r[1].padStart(2,"0"),i=r[2].padStart(2,"0");let l="2000";r[3]&&(l=r[3].length===2?(parseInt(r[3])>50?"19":"20")+r[3]:r[3]);const o=parseInt(a),c=parseInt(i);if(o>=1&&o<=12&&c>=1&&c<=31)return`${l}-${a}-${i}`}const n=new Date(t);return isNaN(n.getTime())?null:n.toISOString().split("T")[0]},J9s=({open:s,onOpenChange:t,relationshipTypes:r,onSuccess:n})=>{const{user:a}=Cs(),{toast:i}=Ba(),l=k.useRef(null),[o,c]=k.useState("upload"),[d,u]=k.useState([]),[m,f]=k.useState([]),[x,y]=k.useState({}),[_,b]=k.useState([]),[j,N]=k.useState([]),[C,A]=k.useState([]),[E,D]=k.useState(""),[R,F]=k.useState(!1),[O,B]=k.useState([]),[K,Z]=k.useState(!1),[Q,W]=k.useState(null);k.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Le}=await U.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");N(Le||[])})()},[s,a==null?void 0:a.id]);const te=Le=>{A($e=>$e.includes(Le)?$e.filter(ve=>ve!==Le):[...$e,Le])},ne=async()=>{const Le=E.trim();if(!(!Le||!(a!=null&&a.id))){F(!0);try{const{data:$e,error:ve}=await U.from("contact_custom_tags").insert({owner_user_id:a.id,name:Le}).select("id, name, color").single();if(ve)throw ve;$e&&(N(Qe=>[...Qe,$e].sort((we,nt)=>we.name.localeCompare(nt.name))),A(Qe=>[...Qe,$e.id]),D(""))}catch($e){i({title:"Could not create tag",description:$e.message||"Try a different name.",variant:"destructive"})}finally{F(!1)}}},ae=()=>{c("upload"),u([]),f([]),y({}),b([]),A([]),D(""),B([]),W(null),l.current&&(l.current.value="")},ue=()=>{ae(),t(!1)},me=Le=>{const $e=Le.split(` `).map(Ge=>Ge.trim()).filter(Ge=>Ge);if($e.length===0)return{headers:[],data:[]};const ve=Ge=>{const We=[];let Ce="",qe=!1;for(let et=0;et0&&(Qe[0]=Qe[0].replace(/^\uFEFF/,""));const we=new Map,nt=Qe.map((Ge,We)=>{let Ce=(Ge||"").trim();Ce||(Ce=`Column ${We+1}`);const qe=we.get(Ce)||0;return we.set(Ce,qe+1),qe===0?Ce:`${Ce} (${qe+1})`}),Se=$e.slice(1).map(ve);return{headers:nt,data:Se}},de=Le=>{var Qe;const $e=(Qe=Le.target.files)==null?void 0:Qe[0];if(!$e)return;const ve=new FileReader;ve.onload=we=>{var Ce;const nt=(Ce=we.target)==null?void 0:Ce.result,{headers:Se,data:Ge}=me(nt);if(Se.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(Se),f(Ge);const We={};Se.forEach(qe=>{const et=qe.toLowerCase().replace(/[_\s-]/g,"");et.includes("firstname")||et==="first"?We.first_name=qe:et.includes("lastname")||et==="last"?We.last_name=qe:et.includes("spouse")&&et.includes("email")?We.spouse_email=qe:et.includes("spouse")||et.includes("partner")?We.spouse_name=qe:et.includes("email")?We.email=qe:et.includes("phone")||et.includes("mobile")||et.includes("cell")?We.phone=qe:et.includes("address")||et.includes("street")?We.address=qe:et==="city"?We.city=qe:et==="state"||et==="province"?We.state=qe:et==="zip"||et==="zipcode"||et==="postalcode"?We.zip=qe:et.includes("company")||et.includes("organization")||et.includes("business")?We.company_name=qe:et.includes("jobtitle")||et.includes("title")&&!et.includes("spouse")?We.job_title=qe:et.includes("birthday")||et.includes("dob")||et.includes("birthdate")?We.birthday=qe:et.includes("anniversary")||et.includes("homeanniversary")?We.home_anniversary=qe:(et.includes("notes")||et.includes("comment"))&&(We.notes=qe)}),y(We),c("mapping")},ve.readAsText($e)},fe=(Le,$e)=>{y(ve=>{if($e==="none"){const{[Le]:Qe,...we}=ve;return we}return{...ve,[Le]:$e}})},je=Le=>{b($e=>$e.includes(Le)?$e.filter(ve=>ve!==Le):[...$e,Le])},xe=async()=>{if(!(a!=null&&a.id))return;const{data:Le}=await U.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),$e=new Set((Le||[]).filter(we=>we.email).map(we=>we.email.toLowerCase())),ve=new Set((Le||[]).filter(we=>we.phone).map(we=>we.phone.replace(/[^0-9]/g,""))),Qe=m.map(we=>{const nt=et=>{const Ze=x[et];if(!Ze)return"";const rt=d.indexOf(Ze);return rt>=0?(we[rt]||"").trim():""},Se=nt("first_name"),Ge=nt("email"),We=nt("phone"),Ce=Se.length>0,qe=!!(Ge&&$e.has(Ge.toLowerCase())||We&&ve.has(We.replace(/[^0-9]/g,"")));return{first_name:Se,last_name:nt("last_name"),email:Ge,phone:We,address:nt("address"),city:nt("city"),state:nt("state"),zip:nt("zip"),spouse_name:nt("spouse_name"),spouse_email:nt("spouse_email"),company_name:nt("company_name"),job_title:nt("job_title"),birthday:nt("birthday"),home_anniversary:nt("home_anniversary"),notes:nt("notes"),isValid:Ce,isDuplicate:qe,error:Ce?void 0:"First name is required"}});B(Qe),c("preview")},Ee=Le=>{const $e=Le.trim().split(/\s+/);return{first_name:$e[0],last_name:$e.length>1?$e.slice(1).join(" "):null}},Me=async()=>{if(!(a!=null&&a.id))return;const Le=O.filter(we=>we.isValid);if(Le.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}Z(!0);let $e=0,ve=0,Qe=0;try{for(const we of Le)try{let nt=null;if(we.email){const{data:We}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",we.email).maybeSingle();nt=We}if(!nt&&we.phone){const We=we.phone.replace(/[^0-9]/g,""),{data:Ce}=await U.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ce){const qe=Ce.find(et=>et.phone&&et.phone.replace(/[^0-9]/g,"")===We);qe&&(nt={id:qe.id})}}const Se={owner_user_id:a.id,first_name:we.first_name,last_name:we.last_name||null,email:we.email||null,phone:we.phone||null,address:we.address||null,city:we.city||null,state:we.state||null,zip:we.zip||null,spouse_name:we.spouse_name||null,spouse_email:we.spouse_email||null,company_name:we.company_name||null,job_title:we.job_title||null,birthday:vV(we.birthday),home_anniversary:vV(we.home_anniversary),notes:we.notes||null};let Ge=null;if(nt){const{data:We}=await U.from("innercircle_contacts").select("*").eq("id",nt.id).single();if(We){const Ce={},qe=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const et of qe){const Ze=We[et],rt=Se[et];(!Ze||Ze==="")&&rt&&(Ce[et]=rt)}Object.keys(Ce).length>0&&await U.from("innercircle_contacts").update(Ce).eq("id",nt.id)}Ge=nt.id,ve++}else{const{data:We,error:Ce}=await U.from("innercircle_contacts").insert(Se).select("id").single();Ce?(console.error("Insert error for contact:",we.first_name,Ce),Qe++):We?(Ge=We.id,_.length>0&&await U.from("innercircle_contact_tags").insert(_.map(qe=>({contact_id:We.id,relationship_type_id:qe}))),$e++):Qe++}if(Ge&&C.length>0&&await U.from("contact_custom_tag_assignments").upsert(C.map(We=>({contact_id:Ge,tag_id:We})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Ge&&we.spouse_name){const We=Ee(we.spouse_name);let Ce=null;if(we.spouse_email){const{data:et}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",we.spouse_email).maybeSingle();Ce=et}if(!Ce){const{data:et}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",We.first_name).eq("last_name",We.last_name||we.last_name||"").maybeSingle();Ce=et}let qe=null;if(Ce){qe=Ce.id;const et=vV(we.home_anniversary);et&&await U.from("innercircle_contacts").update({home_anniversary:et}).eq("id",Ce.id).is("home_anniversary",null)}else{const{data:et}=await U.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:We.first_name,last_name:We.last_name||we.last_name||null,email:we.spouse_email||null,address:we.address||null,city:we.city||null,state:we.state||null,zip:we.zip||null,home_anniversary:vV(we.home_anniversary),spouse_name:`${we.first_name}${we.last_name?" "+we.last_name:""}`,spouse_email:we.email||null,notes:`Spouse of ${we.first_name} ${we.last_name||""} (imported via CSV)`.trim()}).select("id").single();et&&(qe=et.id,$e++)}qe&&(await U.from("innercircle_contacts").update({spouse_contact_id:qe}).eq("id",Ge),await U.from("innercircle_contacts").update({spouse_contact_id:Ge}).eq("id",qe))}}catch(nt){console.error("Error importing contact:",nt),Qe++}W({created:$e,updated:ve,failed:Qe}),c("result"),($e>0||ve>0)&&n(),i({title:"Import Complete",description:`${$e} created, ${ve} updated${Qe>0?`, ${Qe} failed`:""}.`})}catch(we){console.error("Import error:",we),i({title:"Import Failed",description:we.message||"Failed to import contacts",variant:"destructive"})}finally{Z(!1)}},Oe=O.filter(Le=>Le.isValid).length,Ie=O.filter(Le=>!Le.isValid).length,ze=O.filter(Le=>Le.isValid&&Le.isDuplicate).length,Ve=Oe-ze;return e.jsx(vs,{open:s,onOpenChange:ue,children:e.jsxs(ys,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(s2,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(an,{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:de,className:"hidden"}),e.jsx(ka,{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(q,{onClick:()=>{var Le;return(Le=l.current)==null?void 0:Le.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(q,{variant:"outline",size:"sm",onClick:()=>{const Le=`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`,$e=new Blob([Le],{type:"text/csv"}),ve=URL.createObjectURL($e),Qe=document.createElement("a");Qe.href=ve,Qe.download="contact_import_template.csv",Qe.click(),URL.revokeObjectURL(ve)},children:[e.jsx(li,{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(ce,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:Q9s.map(Le=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(ce,{className:"w-40 text-sm",children:[Le.label,Le.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ds,{value:x[Le.key]||"none",onValueChange:$e=>fe(Le.key,$e),children:[e.jsx(Ps,{className:"w-48",children:e.jsx(Fs,{placeholder:"Select column..."})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"-- Not mapped --"}),d.map($e=>e.jsx(lt,{value:$e,children:$e},$e))]})]})]},Le.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(Le=>e.jsx(Xe,{variant:_.includes(Le.id)?"default":"outline",className:"cursor-pointer",onClick:()=>je(Le.id),children:Le.name},Le.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{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(Le=>{const $e=C.includes(Le.id);return e.jsxs(Xe,{variant:$e?"default":"outline",className:"cursor-pointer gap-1",style:$e&&Le.color?{backgroundColor:Le.color,borderColor:Le.color}:void 0,onClick:()=>te(Le.id),children:[Le.name,$e&&e.jsx($r,{className:"h-3 w-3"})]},Le.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:E,onChange:Le=>D(Le.target.value),onKeyDown:Le=>{Le.key==="Enter"&&(Le.preventDefault(),ne())},className:"max-w-xs"}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:ne,disabled:!E.trim()||R,children:[R?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add Tag"]})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-sm",children:e.jsxs("p",{className:"text-muted-foreground",children:["Preview: ",m.length," row(s) found in CSV"]})})]}),o==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Ve," new"]})]}),ze>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(go,{className:"h-4 w-4"}),e.jsxs("span",{children:[ze," existing (will merge gaps)"]})]}),Ie>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(go,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ie," invalid"]})]})]}),ze>0&&e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-xs text-muted-foreground",children:"Duplicates matched by email or phone will only fill in missing fields — your existing data won't be overwritten."}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/30",children:[e.jsx(At,{children:"First Name"}),e.jsx(At,{children:"Last Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Phone"}),e.jsx(At,{children:"Status"})]})}),e.jsx(ha,{children:O.slice(0,100).map((Le,$e)=>e.jsxs(Ws,{children:[e.jsx(xt,{children:Le.first_name}),e.jsx(xt,{children:Le.last_name}),e.jsx(xt,{children:Le.email}),e.jsx(xt,{children:Le.phone}),e.jsx(xt,{children:Le.isValid?Le.isDuplicate?e.jsx(Xe,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(Xe,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(Xe,{variant:"destructive",children:Le.error||"Invalid"})})]},$e))})]}),O.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",O.length," contacts"]})]})]}),o==="result"&&Q&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(qn,{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:[Q.created," created, ",Q.updated," merged"]}),Q.failed>0&&e.jsxs("p",{className:"text-destructive",children:[Q.failed," failed to import"]})]}),e.jsxs(fn,{children:[o==="upload"&&e.jsx(q,{variant:"outline",onClick:ue,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"outline",onClick:ae,children:"Back"}),e.jsx(q,{onClick:xe,disabled:!x.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(q,{onClick:Me,disabled:K||Oe===0,children:K?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${Oe} Contact${Oe!==1?"s":""}`})]}),o==="result"&&e.jsx(q,{onClick:ue,children:"Done"})]})]})})};function ezs(){return"contacts"in navigator&&"ContactsManager"in window}function tzs(s){const t=[],r=s.split("BEGIN:VCARD").filter(n=>n.trim());for(const n of r){const a=n.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const m=u.replace(/^\s+/,"");if(m.startsWith("N:")||m.startsWith("N;")){const x=m.substring(m.indexOf(":")+1).split(";");l=(x[0]||"").trim(),i=(x[1]||"").trim()}if((m.startsWith("FN:")||m.startsWith("FN;"))&&!i){const x=m.substring(m.indexOf(":")+1).trim().split(" ");i=x[0]||"",l=x.slice(1).join(" ")}(m.startsWith("EMAIL")||m.match(/^item\d+\.EMAIL/i))&&!o&&(o=m.substring(m.indexOf(":")+1).trim()),(m.startsWith("TEL")||m.match(/^item\d+\.TEL/i))&&!c&&(c=m.substring(m.indexOf(":")+1).trim()),(m.startsWith("ADR")||m.match(/^item\d+\.ADR/i))&&!d&&(d=m.substring(m.indexOf(":")+1).split(";").map(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 szs({open:s,onOpenChange:t,onComplete:r}){Cs();const{data:n}=Lp(),a=Dge(),i=k.useRef(null),[l,o]=k.useState("choose"),[c,d]=k.useState([]),[u,m]=k.useState(new Set),[f,x]=k.useState(0),[y,_]=k.useState(0),b=ezs(),j=k.useCallback(B=>{if(!n)return B;const K=new Set(n.filter(Q=>Q.email).map(Q=>Q.email.toLowerCase())),Z=new Set(n.filter(Q=>Q.phone).map(Q=>Q.phone.replace(/\D/g,"")));return B.map(Q=>{var ne,ae;const W=(ne=Q.email)==null?void 0:ne.toLowerCase(),te=(ae=Q.phone)==null?void 0:ae.replace(/\D/g,"");return W&&K.has(W)?{...Q,isDuplicate:!0,duplicateField:"email"}:te&&te.length>=7&&Z.has(te)?{...Q,isDuplicate:!0,duplicateField:"phone"}:Q})},[n]),N=async()=>{try{const B=["name","email","tel","address"],K=await navigator.contacts.select(B,{multiple:!0});if(!K||K.length===0)return;const Z=K.map(te=>{var ue,me,de,fe;const ae=(((ue=te.name)==null?void 0:ue[0])||"").split(" ");return{first_name:ae[0]||"",last_name:ae.slice(1).join(" "),email:((me=te.email)==null?void 0:me[0])||"",phone:((de=te.tel)==null?void 0:de[0])||"",address:(fe=te.address)!=null&&fe[0]?[te.address[0].streetAddress,te.address[0].city,te.address[0].region,te.address[0].postalCode].filter(Boolean).join(", "):""}}),Q=j(Z);d(Q);const W=new Set;Q.forEach((te,ne)=>{te.isDuplicate||W.add(ne)}),m(W),o("preview")}catch(B){console.error("Contact Picker error:",B),Dn({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},C=B=>{var Q;const K=(Q=B.target.files)==null?void 0:Q[0];if(!K)return;const Z=new FileReader;Z.onload=W=>{var me;const te=(me=W.target)==null?void 0:me.result,ne=tzs(te);if(ne.length===0){Dn({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const ae=j(ne);d(ae);const ue=new Set;ae.forEach((de,fe)=>{de.isDuplicate||ue.add(fe)}),m(ue),o("preview")},Z.readAsText(K),i.current&&(i.current.value="")},A=async()=>{const B=c.filter((Z,Q)=>u.has(Q));if(B.length===0)return;o("importing");let K=0;for(const Z of B)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}),K++,_(Math.round(K/B.length*100))}catch(Q){console.error(`Failed to import ${Z.first_name} ${Z.last_name}:`,Q)}x(K),o("done")},E=B=>{m(K=>{const Z=new Set(K);return Z.has(B)?Z.delete(B):Z.add(B),Z})},D=()=>{u.size===c.length?m(new Set):m(new Set(c.map((B,K)=>K)))},R=B=>{B||(o("choose"),d([]),m(new Set),x(0),_(0),l==="done"&&r()),t(B)},F=c.filter(B=>B.isDuplicate).length,O=u.size;return e.jsx(vs,{open:s,onOpenChange:R,children:e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(yg,{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(an,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[b&&e.jsxs(q,{onClick:N,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(yg,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[b&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),b&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs(q,{variant:b?"outline":"default",onClick:()=>{var B;return(B=i.current)==null?void 0:B.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(ka,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:b?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:i,type:"file",accept:".vcf,.vcard",onChange:C,className:"hidden"}),!b&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),l==="preview"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{children:[c.length," contact",c.length!==1?"s":""," found",F>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",F," already exist)"]})]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:D,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(ui,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((B,K)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${B.isDuplicate?"opacity-60":""}`,onClick:()=>E(K),children:[e.jsx(Ri,{checked:u.has(K),onCheckedChange:()=>E(K),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:[B.first_name," ",B.last_name]}),B.isDuplicate&&e.jsxs(Xe,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",B.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[B.phone&&e.jsx("div",{children:B.phone}),B.email&&e.jsx("div",{className:"truncate",children:B.email})]})]})]},K))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(q,{onClick:A,disabled:O===0,children:["Import ",O," Contact",O!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(ls,{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(la,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[f," contact",f!==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(q,{onClick:()=>R(!1),className:"mt-2",children:"Done"})]})]})})}function rzs(s){return pt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function nzs(){const{user:s}=Cs();return pt({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:r}=await U.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(r)throw r;const n=t;return{totalSent:n.length,totalOpened:n.filter(a=>a.opened_at).length,totalClicked:n.filter(a=>a.clicked_at).length,totalWatched:n.filter(a=>a.watched_at).length,openRate:n.length>0?Math.round(n.filter(a=>a.opened_at).length/n.length*100):0,clickRate:n.length>0?Math.round(n.filter(a=>a.clicked_at).length/n.length*100):0,watchRate:n.length>0?Math.round(n.filter(a=>a.watched_at).length/n.length*100):0}},enabled:!!(s!=null&&s.id)})}function azs(){const{user:s}=Cs();return pt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await U.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function G0t(){const{user:s}=Cs(),t=is();return Mt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await U.from("video_share_recipients").insert([{video_id:r.video_id,owner_user_id:s.id,recipient_email:r.recipient_email,recipient_name:r.recipient_name||null,contact_id:r.contact_id||null,sent_via:r.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return n},onSuccess:r=>{t.invalidateQueries({queryKey:["video-share-recipients",r.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function W0t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function K0t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const izs=100;function ozs({open:s,onOpenChange:t,contacts:r,isGmailConnected:n,isMassEmailReady:a,onSendComplete:i}){const l=qr(),o=xa(),c=G0t(),[d,u]=k.useState([]),[m,f]=k.useState(!1),[x,y]=k.useState(""),[_,b]=k.useState(null),[j,N]=k.useState(""),[C,A]=k.useState(""),[E,D]=k.useState(!1),[R,F]=k.useState({done:0,total:0,failed:0}),O=r.filter(ae=>!!ae.email),B=r.length-O.length,K=O.length>izs;k.useEffect(()=>{s&&(b(null),y(""),F({done:0,total:0,failed:0}))},[s]),k.useEffect(()=>{!s||!o||(f(!0),U.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:ae})=>{u(ae||[]),f(!1)}))},[s,o]),k.useEffect(()=>{if(!_)return;const ae=_.title||"a quick video";N(`I recorded a video for you — ${ae}`),A("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[_]);const Z=d.filter(ae=>!x||(ae.title||"").toLowerCase().includes(x.toLowerCase())),Q=(ae,ue)=>{if(!_)return"";const me=_.share_token?`https://video.relevelup.com/share/video/${_.share_token}`:"",de=_.share_token?`https://video.relevelup.com/thumb/${_.share_token}`:_.thumbnail_url||"",fe=_.title||"Video Message",xe=C.replace(/\{\{first_name\}\}/gi,ae).split(/\n\n+/).map(Oe=>`

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

`).join(""),Ee=ue?K0t(ue):me,Me=ue?``:"";return`
`},W=async()=>{if(!_)return;D(!0),F({done:0,total:O.length,failed:0});let ae=0,ue=0;for(const me of O)try{let de;try{de=(await c.mutateAsync({video_id:_.id,recipient_email:me.email,recipient_name:`${me.first_name} ${me.last_name||""}`.trim(),contact_id:me.id,sent_via:"gmail"})).share_token}catch(Me){console.warn("Tracking record failed for",me.email,Me)}const fe=Q(me.first_name,de),je=j.replace(/\{\{first_name\}\}/gi,me.first_name),{data:xe,error:Ee}=await U.functions.invoke("gmail-send",{body:{to:me.email,subject:je,body:fe,contactId:me.id}});if(Ee||!(xe!=null&&xe.success))throw new Error((xe==null?void 0:xe.error)||(Ee==null?void 0:Ee.message)||"Send failed");ae+=1}catch(de){console.error("Failed to send to",me.email,de),ue+=1}finally{F({done:ae+ue,total:O.length,failed:ue}),await new Promise(de=>setTimeout(de,250))}D(!1),ue===0?he.success(`Video sent to ${ae} ${ae===1?"contact":"contacts"}!`):he.warning(`Sent to ${ae}, ${ue} failed. Check console for details.`),t(!1),i==null||i()},te=()=>{if(!_)return;const ae=Q("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:O.map(ue=>({email:ue.email,name:`${ue.first_name} ${ue.last_name||""}`.trim()})),initialSubject:j,initialBodyHtml:ae}}),t(!1)},ne=!!_&&!!j.trim()&&O.length>0&&(K?a:n);return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(bn,{className:"h-5 w-5 text-primary"}),"Send Video to ",O.length," ",O.length===1?"Contact":"Contacts"]}),e.jsxs(an,{children:[K?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(fh,{className:"h-3.5 w-3.5"}),O.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ks,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),B>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",B," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[K&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(go,{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 ",O.length," recipients."]})]}),!K&&!n&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(go,{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(ce,{children:"Choose a video"}),e.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(Ys,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search your video library...",value:x,onChange:ae=>y(ae.target.value),className:"pl-10"})]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto space-y-2 border rounded-md p-2",children:m?e.jsxs(e.Fragment,{children:[e.jsx(dr,{className:"h-14 w-full"}),e.jsx(dr,{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(ae=>{const ue=(_==null?void 0:_.id)===ae.id;return e.jsxs("button",{type:"button",onClick:()=>b(ae),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${ue?"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:[ae.thumbnail_url?e.jsx("img",{src:ae.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(rf,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20",children:e.jsx(Al,{className:"h-4 w-4 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:ae.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ae.duration_seconds?`${Math.round(ae.duration_seconds)}s`:"",ae.created_at?` · ${new Date(ae.created_at).toLocaleDateString()}`:""]})]})]},ae.id)})})]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(Ne,{id:"bulk-video-subject",value:j,onChange:ae=>N(ae.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ce,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(pr,{id:"bulk-video-message",value:C,onChange:ae=>A(ae.target.value),rows:4,className:"resize-y"})]}),E&&R.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",R.done," / ",R.total,R.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",R.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),disabled:E,children:"Cancel"}),K?e.jsxs(q,{onClick:te,disabled:!ne,className:"gap-2",children:[e.jsx(fh,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(q,{onClick:W,disabled:!ne||E,className:"gap-2",children:[E?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"}),E?"Sending…":`Send to ${O.length}`]})]})]})]})})}function l6e(){const s=xa();return pt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function lzs(s){return pt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function czs(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description??null,category:r.category??"nurture",icon:r.icon??"🌱",cover_color:r.cover_color??"from-emerald-500 to-teal-600",goal:r.goal??null,is_active:!1}).select().single();if(a)throw a;return n},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function Y0t(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("drip_campaigns").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",r.id]})}})}function dzs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("drip_campaigns").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function uzs(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const[{data:n,error:a},{data:i,error:l}]=await Promise.all([U.from("drip_campaigns").select("*").eq("id",r).single(),U.from("drip_campaign_steps").select("*").eq("campaign_id",r).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await U.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description,category:n.category,icon:n.icon,cover_color:n.cover_color,goal:n.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(m=>({campaign_id:o.id,step_order:m.step_order,channel:m.channel,subject:m.subject,body:m.body,video_url:m.video_url,delay_type:m.delay_type,delay_days:m.delay_days,delay_hours:m.delay_hours,anchor_field:m.anchor_field,anchor_offset_days:m.anchor_offset_days,send_window_start:m.send_window_start,send_window_end:m.send_window_end})),{error:u}=await U.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function Z0t(s){return pt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function hzs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(n)throw n;return r},onSuccess:(t,r)=>s.invalidateQueries({queryKey:["drip-campaign-steps",r.campaign_id]})})}function mzs(){const s=is();return Mt({mutationFn:async({id:t,campaign_id:r,...n})=>{const{data:a,error:i}=await U.from("drip_campaign_steps").update(n).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:r}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function fzs(){const s=is();return Mt({mutationFn:async({id:t,campaign_id:r})=>{const{error:n}=await U.from("drip_campaign_steps").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function pzs(s){return pt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function xzs(s){return pt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:r}=await U.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(r)throw r;return t??0},enabled:!!s,staleTime:3e4})}function X0t(){const s=is();return Mt({mutationFn:async({campaignId:t,contactIds:r})=>{const{data:n,error:a}=await U.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:r}});if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function gzs(){const s=is();return Mt({mutationFn:async({id:t,status:r})=>{const n={status:r};r==="paused"&&(n.paused_at=new Date().toISOString()),r==="exited"&&(n.exited_at=new Date().toISOString(),n.exit_reason="manual");const{data:a,error:i}=await U.from("drip_campaign_enrollments").update(n).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const yzs=[{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"}],_ye={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"},vzs={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 cM({userId:s,onSelect:t,onSelectVideo:r,triggerLabel:n="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=k.useState(!1),[d,u]=k.useState([]),[m,f]=k.useState(!1),[x,y]=k.useState("");k.useEffect(()=>{!o||!s||(f(!0),U.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:b})=>{u(b||[]),f(!1)}))},[o,s]);const _=d.filter(b=>!x||(b.title||b.recipient_name||"").toLowerCase().includes(x.toLowerCase()));return e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(rf,{className:"h-3.5 w-3.5"}),n]})}),e.jsxs(ys,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(_s,{children:[e.jsx(bs,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search videos...",value:x,onChange:b=>y(b.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:m?e.jsxs(e.Fragment,{children:[e.jsx(dr,{className:"h-16 w-full"}),e.jsx(dr,{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(b=>e.jsxs("button",{onClick:()=>{t(b.playback_url||""),r==null||r(b),c(!1)},className:"w-full flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:b.thumbnail_url?e.jsx("img",{src:b.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:j=>{const N=j.currentTarget.parentElement;if(N){j.currentTarget.remove();const C=document.createElement("span");C.innerHTML="🎬",C.className="text-lg",N.appendChild(C)}}}):e.jsx(bn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.title||b.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.duration_seconds?`${Math.round(b.duration_seconds)}s`:"",b.created_at?` · ${new Date(b.created_at).toLocaleDateString()}`:""]})]})]},b.id))})]})]})}function bzs(){return pt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await U.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function _zs(s){return pt({queryKey:["video-scripts",s],queryFn:async()=>{let t=U.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:r,error:n}=await t;if(n)throw n;return r}})}function wzs(){const{user:s}=Cs();return pt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await U.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function jzs(){const{user:s}=Cs(),t=is();return Mt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await U.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:r.id,category_id:r.category_id,title:r.title,script_text:r.script_text,tags:r.tags,is_custom:!1}]).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function Nzs(s){const{user:t}=Cs();return pt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let r=U.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});r=r.eq("is_deleted",!1);const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!(t!=null&&t.id)})}function kzs(s){return pt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:r}=await U.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function V2(){const{user:s}=Cs(),t=is();return Mt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await U.from("agent_videos").insert([{owner_user_id:s.id,contact_id:r.contact_id,bunny_video_id:r.bunny_video_id,playback_url:r.playback_url,thumbnail_url:r.thumbnail_url,preview_url:r.preview_url,duration_seconds:r.duration_seconds,file_size_mb:r.file_size_mb||0,title:r.title,notes:r.notes,task_id:r.task_id,status:r.status||"processing",touch_type:r.touch_type||"video",page_template:"default",category:r.category||"general"}]).select("*, share_token").single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function Szs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("agent_videos").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function Czs(){const s=is();return Mt({mutationFn:async({id:t,bunnyVideoId:r,hardDelete:n=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:r,hardDelete:n}),r){console.log("Calling bunny-upload delete for videoId:",r);const{data:a,error:i}=await U.functions.invoke("bunny-upload",{body:{action:"delete",videoId:r,isAgentVideo:!0}});i?console.error("Failed to delete from Bunny:",i):console.log("Bunny delete response:",a)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(n){console.log("Hard deleting from database:",t);const{error:a}=await U.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await U.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function wye(){const{user:s}=Cs();return pt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:r}=await U.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function Q0t(){const{data:s,isLoading:t}=wye(),r=s?s.total_storage_mb0?s.total_storage_mb/s.max_storage_mb*100:0,i=a>=80;return{canRecord:r,remainingMb:n,usagePercent:a,isNearLimit:i,storage:s,isLoading:t}}async function dM(s){const{data:t,error:r}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(r)throw r;return t}async function uM(s){const{data:t,error:r}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(r)throw r;return t}async function W_(s){const{data:t,error:r}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(r)throw r;return t}function Tzs(){const{user:s}=Cs(),t=is();return Mt({mutationFn:async({contactId:r,videoId:n,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await U.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await U.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:r,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${n}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function J0t({open:s,onOpenChange:t,onUploadComplete:r}){const{data:n}=Lp(),{data:a}=wye(),i=V2(),l=k.useRef(null),[o,c]=k.useState(null),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(!1),[j,N]=k.useState(0),[C,A]=k.useState("idle"),E=(a==null?void 0:a.total_storage_mb)||0,R=((a==null?void 0:a.max_storage_mb)||1024)-E,F=Z=>{var te;const Q=(te=Z.target.files)==null?void 0:te[0];if(!Q)return;if(!Q.type.startsWith("video/")){he.error("Please select a video file");return}const W=Q.size/(1024*1024);if(W>500){he.error("Video file must be less than 500MB");return}if(W>R){he.error(`Not enough storage. You have ${R.toFixed(1)} MB remaining.`);return}c(Q),d||u(Q.name.replace(/\.[^/.]+$/,""))},O=async()=>{if(!o){he.error("Please select a video file");return}b(!0),N(0),A("creating");try{const{data:Z,error:Q}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(Q)throw new Error(Q.message);const{videoId:W,libraryId:te}=Z;A("uploading");const{data:ne,error:ae}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:W,isAgentVideo:!0}});if(ae)throw new Error(ae.message);await new Promise((de,fe)=>{const je=new XMLHttpRequest;je.upload.addEventListener("progress",xe=>{if(xe.lengthComputable){const Ee=Math.round(xe.loaded/xe.total*100);N(Ee)}}),je.addEventListener("load",()=>{je.status>=200&&je.status<300?de():fe(new Error(`Upload failed with status ${je.status}`))}),je.addEventListener("error",()=>fe(new Error("Upload failed"))),je.open("PUT",ne.uploadUrl),je.setRequestHeader("AccessKey",ne.apiKey),je.send(o)}),A("processing");const ue=o.size/(1024*1024),me=`https://iframe.mediadelivery.net/embed/${te}/${W}`;await i.mutateAsync({bunny_video_id:W,playback_url:me,file_size_mb:ue,title:d||o.name,notes:m||void 0,contact_id:x||void 0,status:"processing",touch_type:"video_upload"}),he.success("Video uploaded successfully! Processing may take a few minutes."),r==null||r(me),B()}catch(Z){console.error("Upload error:",Z),he.error(Z instanceof Error?Z.message:"Failed to upload video")}finally{b(!1),A("idle")}},B=()=>{_||(c(null),u(""),f(""),y(""),N(0),A("idle"),t(!1))},K=()=>{switch(C){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${j}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(vs,{open:s,onOpenChange:B,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Upload Video"}),e.jsx(an,{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(ce,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(bn,{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(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:Z=>{Z.stopPropagation(),c(null)},children:e.jsx($r,{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(ka,{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:F,disabled:_})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{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(ce,{children:"Associate with Contact (optional)"}),e.jsxs(Ds,{value:x||"__none__",onValueChange:Z=>y(Z==="__none__"?"":Z),disabled:_,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a contact"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"__none__",children:"No contact"}),n==null?void 0:n.map(Z=>e.jsxs(lt,{value:Z.id,children:[Z.first_name," ",Z.last_name||""]},Z.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(pr,{id:"notes",value:m,onChange:Z=>f(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(ls,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:K()})]}),e.jsx(ki,{value:C==="uploading"?j:C==="processing"?100:10})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:B,disabled:_,children:"Cancel"}),e.jsx(q,{onClick:O,disabled:!o||_,children:_?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const Ezs=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],Azs={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},eWe=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=>Azs[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function eyt({open:s,onOpenChange:t,campaignId:r}){const[n,a]=k.useState(r??null),[i,l]=k.useState("details");k.useEffect(()=>{a(r??null),l("details")},[r,s]);const o=n,c=!!o,{data:d}=lzs(o||void 0),{data:u,isLoading:m}=Z0t(o||void 0),f=czs(),x=Y0t(),y=hzs(),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState("nurture"),[E,D]=k.useState("🌱"),[R,F]=k.useState("");k.useEffect(()=>{d?(b(d.name),N(d.description||""),A(d.category),D(d.icon),F(d.goal||"")):c||(b(""),N(""),A("nurture"),D("🌱"),F(""))},[d,c,s]);const O=vzs[C],B=async()=>{if(!_.trim()){he.error("Give your campaign a name");return}try{if(c&&o)await x.mutateAsync({id:o,name:_,description:j,category:C,icon:E,goal:R,cover_color:O}),he.success("Campaign updated");else{const Z=await f.mutateAsync({name:_,description:j,category:C,icon:E,goal:R,cover_color:O});return he.success("Campaign created — now add your first step!"),a(Z.id),l("steps"),Z}}catch(Z){he.error(Z.message||"Failed to save")}},K=async()=>{if(!o){he.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{he.error("Failed to add step")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${O} 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(bs,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(an,{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(ta,{value:i,onValueChange:Z=>l(Z),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(ea,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(rs,{value:"details",children:"Details"}),e.jsxs(rs,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(fs,{value:"details",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(ui,{className:"h-full",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Campaign Name *"}),e.jsx(Ne,{value:_,onChange:Z=>b(Z.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Description"}),e.jsx(pr,{value:j,onChange:Z=>N(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(ce,{className:"text-xs",children:"Goal (optional)"}),e.jsx(Ne,{value:R,onChange:Z=>F(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(ce,{className:"text-xs",children:"Category"}),e.jsxs(Ds,{value:C,onValueChange:Z=>A(Z),children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:Object.entries(_ye).map(([Z,Q])=>e.jsx(lt,{value:Z,children:Q},Z))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:Ezs.map(Z=>e.jsx("button",{type:"button",onClick:()=>D(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(fs,{value:"steps",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(ui,{className:"h-full",children:e.jsx("div",{className:"p-5 space-y-3",children:m?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(Ir,{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(q,{size:"sm",onClick:K,disabled:y.isPending,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((Z,Q)=>e.jsx(Mzs,{step:Z,index:Q,totalSteps:u.length},Z.id)),e.jsxs(q,{variant:"outline",size:"sm",onClick:K,disabled:y.isPending,className:"w-full",children:[y.isPending?e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(fn,{className:"border-t p-4 shrink-0",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(q,{onClick:B,disabled:f.isPending||x.isPending,children:[(f.isPending||x.isPending)&&e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function Mzs({step:s,index:t,totalSteps:r}){const n=mzs(),a=fzs(),i=xa(),[l,o]=k.useState(!1),[c,d]=k.useState(()=>({...s,body:eWe(s.body)})),[u,m]=k.useState(!1),[f,x]=k.useState(!1),[y,_]=k.useState(""),[b,j]=k.useState(!1);k.useEffect(()=>{d({...s,body:eWe(s.body)})},[s]);const N=JSON.stringify(c)!==JSON.stringify(s),C=async()=>{m(!0);try{await n.mutateAsync({id:s.id,campaign_id:s.campaign_id,channel:c.channel,subject:c.subject,body:c.body,video_url:c.video_url,delay_type:c.delay_type,delay_days:c.delay_days,delay_hours:c.delay_hours,anchor_field:c.anchor_field,anchor_offset_days:c.anchor_offset_days}),he.success(`Step ${t+1} saved`)}catch{he.error("Failed to save step")}finally{m(!1)}},A=async()=>{if(confirm(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),he.success("Step deleted")}catch{he.error("Failed to delete")}},E=R=>{d({...c,body:c.body+R})},D=()=>{if(c.delay_type==="calendar_anchor"){const F=c.anchor_field==="birthday"?"birthday":"home anniversary",O=c.anchor_offset_days||0;return O===0?`On their ${F}`:O<0?`${Math.abs(O)}d before ${F}`:`${O}d after ${F}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const R=[];return c.delay_days&&R.push(`${c.delay_days}d`),c.delay_hours&&R.push(`${c.delay_hours}h`),t===0?`After ${R.join(" ")||"0"}`:`+${R.join(" ")||"0"}`};return e.jsxs("div",{className:"border rounded-lg bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 hover:bg-muted/30 cursor-pointer",onClick:()=>o(!l),children:[e.jsx("div",{className:"h-7 w-7 shrink-0 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[c.delay_type==="calendar_anchor"?e.jsx(vn,{className:"h-3 w-3"}):e.jsx(jn,{className:"h-3 w-3"}),e.jsx("span",{children:D()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(Ks,{className:"h-3 w-3"}):e.jsx(Ui,{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(pg,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Co,{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(ce,{className:"text-xs",children:"Channel"}),e.jsxs(Ds,{value:c.channel,onValueChange:R=>d({...c,channel:R}),children:[e.jsx(Ps,{className:"mt-1 h-9",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:e.jsx(lt,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Timing Type"}),e.jsxs(Ds,{value:c.delay_type,onValueChange:R=>d({...c,delay_type:R}),children:[e.jsx(Ps,{className:"mt-1 h-9",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"relative",children:"⏱ Relative delay"}),e.jsx(lt,{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(ce,{className:"text-xs",children:"Days delay"}),e.jsx(Ne,{type:"number",min:0,value:c.delay_days,onChange:R=>d({...c,delay_days:parseInt(R.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Hours delay"}),e.jsx(Ne,{type:"number",min:0,max:23,value:c.delay_hours,onChange:R=>d({...c,delay_hours:parseInt(R.target.value)||0}),className:"mt-1 h-9"})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Anchor"}),e.jsxs(Ds,{value:c.anchor_field||"birthday",onValueChange:R=>d({...c,anchor_field:R}),children:[e.jsx(Ps,{className:"mt-1 h-9",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"birthday",children:"🎂 Birthday"}),e.jsx(lt,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(Ne,{type:"number",value:c.anchor_offset_days||0,onChange:R=>d({...c,anchor_offset_days:parseInt(R.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Subject Line"}),e.jsx(Ne,{value:c.subject,onChange:R=>d({...c,subject:R.target.value}),placeholder:"e.g. Quick question about your home search, {{client_first_name}}",className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ce,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(pr,{value:c.body,onChange:R=>d({...c,body:R.target.value}),placeholder:`Hi {{client_first_name}}, I wanted to reach out and...`,rows:6,className:"mt-1 font-mono text-xs"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground mr-1",children:"Insert:"}),yzs.map(R=>e.jsx("button",{type:"button",onClick:()=>E(R.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:R.label},R.key))]})]}),e.jsxs("div",{children:[e.jsx(ce,{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(bn,{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(q,{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(cM,{userId:i||void 0,onSelect:R=>d({...c,video_url:R}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(q,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>j(!0),children:[e.jsx(ka,{className:"h-3 w-3"})," Upload"]}),e.jsxs(q,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{_(""),x(!0)},children:[e.jsx(tl,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(J0t,{open:b,onOpenChange:j,onUploadComplete:R=>d({...c,video_url:R})}),e.jsx(vs,{open:f,onOpenChange:x,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Add video URL"}),e.jsx(an,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(Ne,{value:y,onChange:R=>_(R.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:R=>{R.key==="Enter"&&y.trim()&&(d({...c,video_url:y.trim()}),x(!1))}}),e.jsxs(fn,{children:[e.jsx(q,{variant:"ghost",onClick:()=>x(!1),children:"Cancel"}),e.jsx(q,{disabled:!y.trim(),onClick:()=>{d({...c,video_url:y.trim()}),x(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs(q,{size:"sm",onClick:C,disabled:!N||u,children:[u&&e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]})]})}function Izs({open:s,onOpenChange:t,contactIds:r,onSuccess:n}){const{data:a,isLoading:i}=l6e(),l=X0t(),[o,c]=k.useState(""),[d,u]=k.useState(null),[m,f]=k.useState(!1),x=(a||[]).filter(b=>!b.is_starter),y=x.filter(b=>b.name.toLowerCase().includes(o.toLowerCase())||(b.description||"").toLowerCase().includes(o.toLowerCase())),_=async()=>{if(d)try{const b=await l.mutateAsync({campaignId:d,contactIds:r}),j=[`${b.enrolled} enrolled`];b.skipped>0&&j.push(`${b.skipped} skipped`),b.errors>0&&j.push(`${b.errors} errors`),he.success(j.join(" · ")),t(!1),u(null),n==null||n()}catch(b){he.error(b.message||"Failed to enroll contacts")}};return e.jsxs(vs,{open:s,onOpenChange:t,children:[e.jsxs(ys,{className:"max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(an,{children:[r.length," contact",r.length!==1?"s":""," will be added to the selected campaign. Already-enrolled contacts will be skipped."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search campaigns...",value:o,onChange:b=>c(b.target.value),className:"pl-9 h-9"})]}),e.jsx(ui,{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:x.length===0?e.jsxs(e.Fragment,{children:[e.jsx(Ir,{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(q,{size:"sm",onClick:()=>f(!0),children:[e.jsx(Ys,{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(b=>e.jsxs("button",{onClick:()=>u(b.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===b.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${b.cover_color} flex items-center justify-center text-lg`,children:b.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),b.is_active&&e.jsx(Xe,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:b.description})]}),d===b.id&&e.jsx(la,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},b.id))})})]}),e.jsxs(fn,{className:"gap-2 sm:gap-2",children:[x.length>0&&e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>f(!0),className:"mr-auto text-xs",children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:_,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",r.length," contact",r.length!==1?"s":""]})]})]}),e.jsx(eyt,{open:m,onOpenChange:f})]})}function Pzs({selectedIds:s,contacts:t,onClearSelection:r,onSendToLeadPond:n,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=qr(),{data:c}=H0(),d=bEe(),u=is(),{isGmailConnected:m}=Cm(),{isReady:f}=tD(),{data:x}=sD(),y=a6e(),_=B0t(),[b,j]=k.useState(!1),[N,C]=k.useState(!1),[A,E]=k.useState(!1),[D,R]=k.useState(!1),[F,O]=k.useState(!1),[B,K]=k.useState(""),Z=s.size;if(Z===0)return null;const Q=async de=>{j(!0);try{const je=Array.from(s).map(Ee=>({contact_id:Ee,relationship_type_id:de})),{error:xe}=await U.from("innercircle_contact_tags").upsert(je,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(xe)throw xe;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Dn({title:`Assigned type to ${Z} contacts`}),r()}catch(fe){Dn({title:"Error assigning type",description:fe.message,variant:"destructive"})}finally{j(!1)}},W=async de=>{j(!0);try{const fe=Array.from(s);for(const je of fe)try{await _.mutateAsync({contactId:je,tagId:de})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),Dn({title:`Tagged ${Z} contacts`}),O(!1),K("")}catch(fe){Dn({title:"Error adding tags",description:fe.message,variant:"destructive"})}finally{j(!1)}},te=async()=>{if(B.trim()){j(!0);try{const de=await y.mutateAsync({name:B.trim()});await W(de.id)}catch(de){Dn({title:"Error creating tag",description:de.message,variant:"destructive"}),j(!1)}}},ne=(x==null?void 0:x.filter(de=>de.name.toLowerCase().includes(B.toLowerCase())))||[],ae=x==null?void 0:x.find(de=>de.name.toLowerCase()===B.trim().toLowerCase()),ue=()=>{const de=t.filter(Ie=>s.has(Ie.id)),fe=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],je=de.map(Ie=>{var ze;return[Ie.first_name,Ie.last_name||"",Ie.email||"",Ie.phone||"",Ie.address||"",Ie.birthday||"",Ie.home_anniversary||"",Ie.notes||"",((ze=Ie.tags)==null?void 0:ze.map(Ve=>{var Le;return(Le=Ve.relationship_type)==null?void 0:Le.name}).join("; "))||""]}),xe=[fe.join(","),...je.map(Ie=>Ie.map(ze=>`"${(ze||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ee=new Blob([xe],{type:"text/csv"}),Me=URL.createObjectURL(Ee),Oe=document.createElement("a");Oe.href=Me,Oe.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Oe.click(),URL.revokeObjectURL(Me),Dn({title:`Exported ${Z} contacts`})},me=async()=>{if(confirm(`Are you sure you want to delete ${Z} contacts? This cannot be undone.`)){j(!0);try{const de=Array.from(s);for(const fe of de)await d.mutateAsync(fe);r()}catch(de){Dn({title:"Error deleting contacts",description:de.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(Xe,{variant:"secondary",className:"font-semibold",children:[Z," selected"]}),e.jsxs(Ds,{onValueChange:Q,disabled:b,children:[e.jsx(Ps,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Fh,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(Ls,{children:c==null?void 0:c.filter(de=>de.active).map(de=>e.jsx(lt,{value:de.id,children:de.name},de.id))})]}),e.jsxs(sl,{open:F,onOpenChange:O,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",disabled:b,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Ko,{className:"w-56 p-2",align:"start",children:[e.jsx(Ne,{placeholder:"Search or create tag...",value:B,onChange:de=>K(de.target.value),onKeyDown:de=>{de.key==="Enter"&&B.trim()&&!ae?(de.preventDefault(),te()):de.key==="Enter"&&ae&&(de.preventDefault(),W(ae.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ne.map(de=>e.jsxs("button",{onClick:()=>W(de.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:de.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:de.name})]},de.id)),B.trim()&&!ae&&e.jsxs("button",{onClick:te,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(Ys,{className:"h-3.5 w-3.5"}),'Create "',B.trim(),'"']}),ne.length===0&&!B.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),m&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>C(!0),disabled:b,children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),f&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>{const de=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${de}`)},disabled:b,children:[e.jsx(fh,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>E(!0),disabled:b,children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>R(!0),disabled:b,children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&n&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>n(Array.from(s)),disabled:b,children:[e.jsx(S1,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:b,children:[e.jsx(Jj,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:ue,disabled:b,children:[e.jsx(li,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:me,disabled:b,className:"text-destructive hover:text-destructive",children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:r,className:"ml-auto",children:[e.jsx($r,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(Izs,{open:D,onOpenChange:R,contactIds:Array.from(s),onSuccess:r}),e.jsx(uw,{open:N,onOpenChange:C,bulkContacts:Array.from(s).map(de=>{const fe=t.find(je=>je.id===de);return fe?{id:fe.id,first_name:fe.first_name,last_name:fe.last_name,email:fe.email||""}:null}).filter(de=>de!==null&&de.email!==""),onSendComplete:()=>{C(!1),r()}}),e.jsx(ozs,{open:A,onOpenChange:E,contacts:Array.from(s).map(de=>t.find(fe=>fe.id===de)).filter(de=>!!de).map(de=>({id:de.id,first_name:de.first_name,last_name:de.last_name,email:de.email})),isGmailConnected:!!m,isMassEmailReady:!!f,onSendComplete:()=>{E(!1),r()}})]})}function tWe({contact:s,onEdit:t,onDelete:r,onSnooze:n,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=qr(),{isReady:d}=tD(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:m=>m.stopPropagation(),children:e.jsx(f0,{className:"h-4 w-4"})})}),e.jsxs(Sd,{align:"end",onClick:m=>m.stopPropagation(),children:[e.jsxs(ti,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Mn,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(ti,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(ti,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(Ma,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(ti,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(ti,{onClick:()=>n(s.id,u),children:[e.jsx(Xf,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(ti,{onClick:()=>a(s.id),children:[e.jsx(S1,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(ti,{onClick:()=>l(s.id),children:[e.jsx(Jj,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(ti,{onClick:()=>t(s),children:[e.jsx(Ua,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ti,{onClick:()=>r(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function sWe({currentFilters:s,currentSortBy:t,onApplySmartList:r}){const{data:n}=$0t(),a=z7s(),i=B7s(),[l,o]=k.useState(!1),[c,d]=k.useState(""),u=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all"||s.behavior&&Object.values(s.behavior).some(f=>f!==void 0&&f!==!1),m=async()=>{c.trim()&&(await a.mutateAsync({name:c.trim(),filters:s,sort_by:t}),d(""),o(!1))};return e.jsxs(e.Fragment,{children:[e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(C1,{className:"h-3.5 w-3.5"}),"Smart Filters",n&&n.length>0&&e.jsx(Xe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:n.length}),e.jsx(Co,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Sd,{align:"start",className:"w-56",children:[n&&n.length>0?e.jsxs(e.Fragment,{children:[n.map(f=>e.jsxs(ti,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>r(f.filters,f.sort_by),children:f.name}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:x=>{x.stopPropagation(),i.mutate(f.id)},children:e.jsx(zr,{className:"h-3 w-3 text-destructive"})})]},f.id)),e.jsx(z_,{})]}):e.jsx(ti,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(ti,{onClick:()=>o(!0),children:[e.jsx(mF,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{className:"max-w-sm",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ne,{placeholder:"e.g. Buyers in 40205",value:c,onChange:f=>d(f.target.value),onKeyDown:f=>f.key==="Enter"&&m(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(q,{onClick:m,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const Lzs=[{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 Dzs({open:s,onOpenChange:t,hasLeadSite:r,behavior:n,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o}){const[c,d]=k.useState(n),[u,m]=k.useState(r?"behavior":"contact");k.useEffect(()=>{s&&d(n)},[s,n]);const f=y=>d(_=>({..._,...y})),x=Object.entries(c).filter(([,y])=>y!==void 0&&y!==!1).length;return e.jsx(sw,{open:s,onOpenChange:t,children:e.jsxs(U1,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(rw,{children:[e.jsxs(nw,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(fge,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(ta,{value:u,onValueChange:y=>m(y),className:"mt-4",children:[e.jsxs(ea,{className:"grid w-full grid-cols-3",children:[e.jsxs(rs,{value:"contact",className:"gap-1.5",children:[e.jsx(Dr,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(rs,{value:"behavior",disabled:!r,className:"gap-1.5",children:[e.jsx(xm,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(rs,{value:"engagement",children:"Engagement"})]}),e.jsx(fs,{value:"contact",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Contact Type"}),e.jsxs(Ds,{value:i,onValueChange:l,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"All types"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),o==null?void 0:o.map(y=>e.jsx(lt,{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(fs,{value:"behavior",className:"space-y-6 mt-4",children:r?e.jsxs(e.Fragment,{children:[e.jsxs(bV,{title:"Last Active On Site",children:[e.jsx(u_,{value:c.lastActive||"",onValueChange:y=>f({lastActive:y||void 0}),className:"grid grid-cols-2 gap-2",children:Lzs.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(Du,{value:y.value}),e.jsx("span",{className:"text-sm",children:y.label})]},y.value))}),c.lastActive&&e.jsx(q,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>f({lastActive:void 0}),children:"Clear"})]}),e.jsxs(bV,{title:"Registration",children:[e.jsx(_j,{label:"Registered on lead site",checked:c.registered==="yes",onChange:y=>f({registered:y?"yes":void 0})}),e.jsx(_j,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:y=>f({registered:y?"no":void 0})})]}),e.jsxs(bV,{title:"Property Activity",children:[e.jsx(_j,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:y=>f({viewedListing:y?"any":void 0})}),e.jsx(_j,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:y=>f({viewedListing:y?"multiple7d":void 0})}),e.jsx(_j,{label:"Saved a property",checked:!!c.savedProperty,onChange:y=>f({savedProperty:y||void 0})}),e.jsx(_j,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:y=>f({hasSavedSearch:y||void 0})})]}),e.jsxs(bV,{title:"Requests",children:[e.jsx(_j,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:y=>f({requestedShowing:y||void 0})}),e.jsx(_j,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:y=>f({requestedValuation:y||void 0})})]})]}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground",children:"Connect a Lead Site with MLS to unlock website behavior filters."})}),e.jsxs(fs,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(_j,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:y=>f({websiteActiveOnly:y||void 0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More engagement filters (last emailed, awaiting response, past-due tasks) are in the pipeline."})]})]}),e.jsxs(ait,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(q,{variant:"ghost",onClick:()=>d({}),disabled:x===0,children:"Clear behavior filters"}),e.jsx(q,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function bV({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function _j({label:s,checked:t,onChange:r}){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(Rr,{checked:t,onCheckedChange:r})]})}function Rzs({behavior:s,onRemove:t,onClearAll:r}){const n=Ozs(s);return n.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.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:r,className:"text-xs text-primary underline underline-offset-2 hover:no-underline",children:"Clear"})]})}function Ozs(s){const t=[];if(s.lastActive){const r={today:"Active today","7d":"Active last 7 days","30d":"Active last 30 days","90d":"Active last 90 days",never:"Never active"};t.push({key:"lastActive",label:r[s.lastActive]})}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 B6(s){const r=[];for(let n=0;n<50;n++){const{data:a,error:i}=await s(n*1e3,n*1e3+1e3-1);if(i)throw i;const l=a||[];if(r.push(...l),l.length<1e3)break}return r}function mO(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function Fzs(){const{user:s}=Cs(),{leadSite:t,hasLeadSite:r}=hf(),{data:n,isLoading:a}=pt({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,N)=>{const C=i.get(j)||mO();i.set(j,{...C,...N})},o=await B6((j,N)=>U.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(j,N)),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 N=i.get(j.contact_id);(!N||!N.lastActiveAt||j.last_seen_at>N.lastActiveAt)&&l(j.contact_id,{lastActiveAt:j.last_seen_at})});const u=await B6((j,N)=>U.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(j,N)),m=new Map;u.forEach(j=>{j.contact_id&&(m.set(j.user_id,j.contact_id),l(j.contact_id,{registered:!0}))});const f=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await B6((j,N)=>U.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(j,N))).forEach(j=>{const N=j.visitor_id?c.get(j.visitor_id):null;if(!N)return;const C=i.get(N)||mO();C.propertyViewCount+=1,j.viewed_at>=f&&(C.propertyViewCount7d+=1),i.set(N,C)}),(await B6((j,N)=>U.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(j,N))).forEach(j=>{const N=m.get(j.user_id);if(!N)return;const C=i.get(N)||mO();C.savedListingCount+=1,i.set(N,C)}),(await B6((j,N)=>U.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(j,N))).forEach(j=>{const N=m.get(j.user_id);if(!N)return;const C=i.get(N)||mO();C.activeSavedSearchCount+=1,i.set(N,C)}),(await B6((j,N)=>U.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(j,N))).forEach(j=>{if(!j.email)return;const N=d.get(j.email.toLowerCase());if(!N)return;const C=i.get(N)||mO(),A=(j.lead_type||"").toLowerCase();(A.includes("showing")||A.includes("question")||A==="contact")&&(C.showingRequests+=1),(A.includes("valuation")||A.includes("cma")||A.includes("home_value"))&&(C.valuationRequests+=1),i.set(N,C)}),i},enabled:!!s&&r,staleTime:5*60*1e3});return{behaviorMap:n??new Map,hasLeadSite:r,isLoading:a}}function rWe(s){if(!s)return null;const t=El(s);if(!t)return null;const r=new Date;r.setHours(0,0,0,0);const n=new Date(r.getFullYear(),t.getMonth(),t.getDate());return ns.relationshipScore.status==="at-risk"},{key:"never-contacted",title:"Never Contacted",subtitle:"No outreach yet",icon:xl,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:jn,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:_1,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:_m,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:Pn,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:bm,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:Ql,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:Ir,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:du,gradient:"from-slate-500/15 via-zinc-500/10 to-transparent",iconBg:"bg-slate-500/15",iconColor:"text-slate-600 dark:text-slate-400",match:s=>{var t,r;return!((t=s.email)!=null&&t.trim())&&!((r=s.phone)!=null&&r.trim())}}];function zzs({contacts:s,contactDealsMap:t,websiteActiveIds:r,activeKey:n,onSelect:a}){const i=k.useRef(null),l=k.useMemo(()=>{const c={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":r.size,"missing-info":0,vips:0};if(!s)return c;for(const d of s){const u={hasDeal:!!(t&&t[d.id]),daysToBirthday:rWe(d.birthday),daysToAnniv:rWe(d.home_anniversary)};for(const m of nWe)m.key!=="website-active"&&m.match(d,u)&&c[m.key]++}return c},[s,t,r]),o=c=>{var d;(d=i.current)==null||d.scrollBy({left:c,behavior:"smooth"})};return e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Smart Segments"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Auto-organized for you"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[n&&e.jsxs("button",{onClick:()=>a(null),className:"flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:[e.jsx($r,{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(jl,{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(Ia,{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:nWe.map(c=>{const d=c.icon,u=l[c.key],m=n===c.key,f=u===0;return e.jsxs("button",{onClick:()=>a(m?null:c.key),disabled:f&&!m,className:`group relative shrink-0 snap-start w-[180px] text-left rounded-xl border transition-all duration-200 overflow-hidden ${m?"border-[#406E71] ring-2 ring-[#406E71]/30 shadow-lg scale-[1.02] bg-card":f?"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 tyt="innercircle_geocode_cache_v1";function Bzs(){try{return JSON.parse(localStorage.getItem(tyt)||"{}")}catch{return{}}}function $zs(s){try{localStorage.setItem(tyt,JSON.stringify(s))}catch{}}function Uzs(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 qzs({open:s,onOpenChange:t,contacts:r,onCitySelect:n}){const a=k.useRef(null),i=k.useRef(null),[l,o]=k.useState(""),[c,d]=k.useState(!0),[u,m]=k.useState([]),[f,x]=k.useState({done:0,total:0}),[y,_]=k.useState(!1),[b,j]=k.useState("heat");k.useEffect(()=>{if(!s)return;let C=!1;return(async()=>{d(!0);const{data:A}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();C||(o((A==null?void 0:A.value)||""),d(!1))})(),()=>{C=!0}},[s]),k.useEffect(()=>{if(!s||!l)return;let C=!1;return(async()=>{const E=Bzs(),D=r.map(W=>({c:W,addr:Uzs(W)})).filter(W=>W.addr),R=[],F=[];for(const{c:W,addr:te}of D){const ne=E[te];ne!==null&&(ne?R.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:ne.lat,lng:ne.lng}):F.push({c:W,addr:te}))}if(C||m(R),x({done:R.length,total:D.length}),F.length===0)return;_(!0);const O=6;let B=0;const K={...E},Z=[...R],Q=async()=>{var W;for(;B{C=!0}},[s,l,r]);const N=k.useMemo(()=>{const C=new Map;for(const A of r){const E=(A.city||"").trim();if(!E)continue;const D=(A.state||"").trim()||null,R=`${E.toLowerCase()}|${D||""}`,F=C.get(R);F?F.count++:C.set(R,{city:E,state:D,count:1})}return Array.from(C.values()).sort((A,E)=>E.count-A.count)},[r]);return k.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return ol.accessToken=l,i.current=new ol.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new ol.NavigationControl,"top-right"),()=>{var C;(C=i.current)==null||C.remove(),i.current=null}},[s,l]),k.useEffect(()=>{const C=i.current;if(!C||u.length===0)return;const A=()=>{const D={type:"FeatureCollection",features:u.map(F=>({type:"Feature",properties:{id:F.id,name:F.name},geometry:{type:"Point",coordinates:[F.lng,F.lat]}}))},R=C.getSource("contacts-src");if(R?R.setData(D):(C.addSource("contacts-src",{type:"geojson",data:D}),C.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]}}),C.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}}),C.on("click","contacts-points",F=>{var K;const O=(K=F.features)==null?void 0:K[0];if(!O)return;const B=O.geometry.coordinates.slice();new ol.Popup({offset:12}).setLngLat(B).setHTML(`
${O.properties.name||"Contact"}
`).addTo(C)}),C.on("mouseenter","contacts-points",()=>{C.getCanvas().style.cursor="pointer"}),C.on("mouseleave","contacts-points",()=>{C.getCanvas().style.cursor=""})),C.getLayer("contacts-heat")&&C.setLayoutProperty("contacts-heat","visibility",b==="heat"?"visible":"none"),C.getLayer("contacts-points")&&(C.setPaintProperty("contacts-points","circle-opacity",b==="points"?.9:0),C.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!C._fitDone){const F=new ol.LngLatBounds;u.forEach(O=>F.extend([O.lng,O.lat]));try{C.fitBounds(F,{padding:60,maxZoom:11,duration:600}),C._fitDone=!0}catch{}}};C.isStyleLoaded()?A():C.once("load",A)},[u,b]),e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(_s,{className:"p-4 pb-2 border-b",children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(ld,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(Xe,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",N.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(ls,{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(q,{size:"sm",variant:b==="heat"?"default":"ghost",onClick:()=>j("heat"),className:"h-8",children:[e.jsx(ld,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(q,{size:"sm",variant:b==="points"?"default":"ghost",onClick:()=>j("points"),className:"h-8",children:[e.jsx(AF,{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(ls,{className:"h-3 w-3 animate-spin"}),"Mapping ",f.done," / ",f.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(go,{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(Ma,{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(ui,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[N.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."}),N.slice(0,50).map((C,A)=>{var R;const E=((R=N[0])==null?void 0:R.count)||1,D=C.count/E*100;return e.jsx(ke,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{n==null||n(C.city,C.state),t(!1)},children:e.jsxs(Pe,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${D}%`}}),e.jsxs("div",{className:"relative flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[C.city,C.state?`, ${C.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:A===0?"🔥 Hottest market":`Rank #${A+1}`})]}),e.jsx(Xe,{variant:"secondary",className:"shrink-0",children:C.count})]})]})},`${C.city}-${C.state}-${A}`)})]})})]})]})]})})}function zT(s){if(!s)return null;try{const t=s.split(/[-/T]/);if(t.length<3)return null;const r=parseInt(t[1],10)-1,n=parseInt(t[2],10);if(isNaN(r)||isNaN(n))return null;const a=new Date;a.setHours(0,0,0,0);let i=new Date(a.getFullYear(),r,n);return i.setHours(0,0,0,0),ir)return null;const a=t==="birthday"?"🎂":"🏡",i=n===0?t==="birthday"?"Birthday today!":"Anniversary today!":n===1?t==="birthday"?"Birthday tomorrow":"Anniversary tomorrow":`${a} in ${n}d`;return{emoji:a,label:i,daysUntil:n}}function aWe({birthday:s,homeAnniversary:t,weddingAnniversary:r,className:n,contactId:a,contactName:i,contactAddress:l}){const o=qr(),c=sje(s,"birthday",7),d=sje(t,"anniversary",7),u=sje(r||null,"anniversary",7);if(!c&&!d&&!u)return null;const m=(f,x,y)=>{y.stopPropagation();const _=new URLSearchParams;a&&_.set("contactId",a),i&&_.set("name",i),l&&_.set("address",l),(f==="home_anniversary"||f==="wedding_anniversary")&&x&&_.set("date",x),_.set("cardType",f),o(`/mission-control/card-studio?${_.toString()}`)};return e.jsxs("div",{className:zt("flex flex-wrap gap-1",n),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Xe,{variant:"secondary",className:zt("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:f=>m("birthday",s,f),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(Ks,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Xe,{variant:"secondary",className:zt("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:f=>m("home_anniversary",t,f),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(Ks,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(Xe,{variant:"secondary",className:zt("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:f=>m("wedding_anniversary",r||null,f),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(Ks,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function iWe({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(Xe,{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 oWe({count:s,className:t}){return!s||s<=0?null:e.jsxs(Xe,{variant:"outline",className:zt("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(GE,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function Vzs(){const s=xa();return pt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:r}=await U.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(r)throw r;const n={};return(t||[]).forEach(a=>{a.contact_id&&(n[a.contact_id]=(n[a.contact_id]||0)+1)}),n},enabled:!!s,staleTime:6e4})}function Hzs(){const s=xa();return pt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:r}=await U.from("deal_pipeline").select(` id, deal_name, contact_id, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(r)throw r;const n={};return(t||[]).forEach(a=>{a.contact_id&&!n[a.contact_id]&&(n[a.contact_id]=a)}),n},enabled:!!s})}function Gzs({contactId:s,compact:t=!1}){const{data:r}=sD(),{data:n}=D7s(s),a=a6e(),i=B0t(),l=F7s(),[o,c]=k.useState(!1),[d,u]=k.useState(""),m=k.useRef(null),f=new Set((n==null?void 0:n.map(j=>j.tag_id))||[]),x=(r==null?void 0:r.filter(j=>j.name.toLowerCase().includes(d.toLowerCase())))||[],y=r==null?void 0:r.find(j=>j.name.toLowerCase()===d.trim().toLowerCase()),_=async j=>{f.has(j.id)?await l.mutateAsync({contactId:s,tagId:j.id}):await i.mutateAsync({contactId:s,tagId:j.id})},b=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:[n==null?void 0:n.map(j=>{var N,C,A;return e.jsxs(Xe,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((N=j.tag)==null?void 0:N.color)||"#6366F1",color:((C=j.tag)==null?void 0:C.color)||"#6366F1"},children:[e.jsx(Fh,{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($r,{className:"h-2.5 w-2.5"})})]},j.id)}),e.jsxs(sl,{open:o,onOpenChange:c,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{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(Ys,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Ko,{className:"w-56 p-2",align:"start",onClick:j=>j.stopPropagation(),children:[e.jsx(Ne,{ref:m,placeholder:"Search or create tag...",value:d,onChange:j=>u(j.target.value),onKeyDown:j=>{j.key==="Enter"&&d.trim()&&!y?(j.preventDefault(),b()):j.key==="Enter"&&y&&!f.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:[x.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}),f.has(j.id)&&e.jsx(la,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},j.id)),d.trim()&&!y&&e.jsxs("button",{onClick:b,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(Ys,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),x.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 lWe({contactId:s,tags:t}){return!t||t.length===0?null:e.jsx(e.Fragment,{children:t.map(r=>{var n,a,i;return e.jsx(Xe,{variant:"outline",className:"text-[10px] gap-0.5",style:{borderColor:((n=r.tag)==null?void 0:n.color)||"#6366F1",color:((a=r.tag)==null?void 0:a.color)||"#6366F1"},children:(i=r.tag)==null?void 0:i.name},r.tag_id)})})}const _V=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function Wzs({open:s,onOpenChange:t}){const{data:r,isLoading:n}=sD(),a=a6e(),i=O7s(),l=R7s(),[o,c]=k.useState(""),[d,u]=k.useState(_V[0]),[m,f]=k.useState(null),[x,y]=k.useState(""),[_,b]=k.useState(""),j=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(_V[0]),Dn({title:"Tag created"})}catch(E){Dn({title:"Error",description:E.message,variant:"destructive"})}},N=async E=>{if(x.trim())try{await i.mutateAsync({id:E,name:x.trim(),color:_}),f(null),Dn({title:"Tag updated"})}catch(D){Dn({title:"Error",description:D.message,variant:"destructive"})}},C=async(E,D)=>{if(confirm(`Delete tag "${D}"? It will be removed from all contacts.`))try{await l.mutateAsync(E),Dn({title:"Tag deleted"})}catch(R){Dn({title:"Error",description:R.message,variant:"destructive"})}},A=E=>{f(E.id),y(E.name),b(E.color)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"New tag name...",value:o,onChange:E=>c(E.target.value),onKeyDown:E=>E.key==="Enter"&&j(),className:"flex-1 h-9"}),e.jsxs(q,{size:"sm",onClick:j,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:_V.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:[n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(r==null?void 0:r.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tags yet. Create one above!"}),r==null?void 0:r.map(E=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:m===E.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:_V.map(D=>e.jsx("button",{onClick:()=>b(D),className:`h-5 w-5 rounded-full border-2 ${_===D?"border-foreground":"border-transparent"}`,style:{backgroundColor:D}},D))}),e.jsx(Ne,{value:x,onChange:D=>y(D.target.value),onKeyDown:D=>D.key==="Enter"&&N(E.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>N(E.id),children:e.jsx(la,{className:"h-4 w-4 text-primary"})}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>f(null),children:e.jsx($r,{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(q,{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(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{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:()=>C(E.id,E.name),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})},E.id))]})]})})}function Kzs({open:s,onOpenChange:t}){const{data:r,isLoading:n}=I8(),a=jEe(),i=eJt(),l=tJt(),[o,c]=k.useState(""),[d,u]=k.useState(null),[m,f]=k.useState(""),x=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(j){he.error(j.message||"Failed to add lead source")}},y=async j=>{if(m.trim())try{await i.mutateAsync({id:j,name:m.trim()}),u(null)}catch(N){he.error(N.message||"Failed to update")}},_=async(j,N)=>{if(confirm(`Remove lead source "${N}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(j)}catch(C){he.error(C.message||"Failed to remove")}},b=j=>{u(j.id),f(j.name)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"New lead source name...",value:o,onChange:j=>c(j.target.value),onKeyDown:j=>j.key==="Enter"&&x(),className:"flex-1 h-9"}),e.jsxs(q,{size:"sm",onClick:x,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(r==null?void 0:r.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),r==null?void 0:r.map(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(Ne,{value:m,onChange:N=>f(N.target.value),onKeyDown:N=>N.key==="Enter"&&y(j.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>y(j.id),children:e.jsx(la,{className:"h-4 w-4 text-primary"})}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx($r,{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(q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>b(j),children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{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(zr,{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 syt({value:s,onChange:t,label:r="Lead Source"}){const{data:n}=I8(),a=jEe(),[i,l]=k.useState(!1),[o,c]=k.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(ce,{children:r}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ds,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(Ps,{className:"flex-1",children:e.jsx(Fs,{placeholder:"Select lead source"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"_none",children:"No source"}),n==null?void 0:n.map(u=>e.jsx(lt,{value:u.id,children:u.name},u.id))]})]}),e.jsx(q,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx($r,{className:"h-4 w-4"}):e.jsx(Ys,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"New lead source name...",value:o,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())},className:"flex-1"}),e.jsx(q,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function mCe({contactId:s,currentSpouseContactId:t,currentSpouseName:r,currentSpouseEmail:n,onLink:a,onUnlink:i,isEditing:l}){const o=qr(),c=xa(),[d,u]=k.useState(!1),[m,f]=k.useState(""),{data:x}=pt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:_,error:b}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(b)throw b;return _},enabled:!!t}),{data:y}=pt({queryKey:["spouse-search",c,s,m],queryFn:async()=>{let _=U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(m.trim()){const N=m.replace(/[,()%]/g," ").trim();N&&(_=_.or(`first_name.ilike.%${N}%,last_name.ilike.%${N}%,email.ilike.%${N}%,phone.ilike.%${N}%`))}const{data:b,error:j}=await _;if(j)throw j;return b},enabled:d&&!!c});if(t&&x){const _=`${x.first_name} ${x.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{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(qi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${x.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:_}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[x.phone,x.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(q,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(WE,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${x.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(ci,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(r||n)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{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(qi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm",children:r}),n&&e.jsx("span",{className:"text-xs text-muted-foreground block truncate",children:n})]}),l&&e.jsxs(sl,{open:d,onOpenChange:u,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(Ul,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Ko,{className:"w-72 p-2",align:"end",children:e.jsx(cWe,{search:m,setSearch:f,results:y,onSelect:_=>{a(_),u(!1),f("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(sl,{open:d,onOpenChange:u,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(Ul,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Ko,{className:"w-72 p-2",align:"start",children:e.jsx(cWe,{search:m,setSearch:f,results:y,onSelect:_=>{a(_),u(!1),f("")}})})]})]}):null}function cWe({search:s,setSearch:t,results:r,onSelect:n}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(ui,{className:"max-h-48",children:r&&r.length>0?e.jsx("div",{className:"space-y-0.5",children:r.map(a=>e.jsxs("button",{onClick:()=>n(a.id),className:"w-full text-left px-2 py-1.5 rounded hover:bg-accent transition-colors",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[a.first_name," ",a.last_name]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[a.phone,a.email].filter(Boolean).join(" · ")||"No contact info"})]},a.id))}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:s?"No contacts found":"Type to search contacts"})})]})}function Yzs(){var cs;const s=qr(),[t,r]=ic(),{user:n}=Cs(),a=rD(),i=is(),l=t.get("type"),o=t.get("filter")??t.get("status"),c=t.get("new")==="true",{contactsWithScores:d,isLoading:u}=zge(),{activeContactIds:m,hasLeadSite:f}=Y9s(),{data:x}=Vzs(),{data:y}=H0(),{data:_}=Hzs(),{data:b}=sD(),{data:j}=gye(),[N,C]=k.useState(new Set),[A,E]=k.useState("any"),D=Dge(),R=vEe(),F=bEe(),O=Act(),[B,K]=k.useState(""),[Z,Q]=k.useState(!1),[W,te]=k.useState(l||"all"),[ne,ae]=k.useState(o||"all"),[ue,me]=k.useState("date-added"),[de,fe]=k.useState("all"),[je,xe]=k.useState({}),[Ee,Me]=k.useState(!1),{behaviorMap:Oe,hasLeadSite:Ie}=Fzs(),[ze,Ve]=k.useState(c),[Le,$e]=k.useState(null),[ve,Qe]=k.useState(!1),[we,nt]=k.useState(!1),[Se,Ge]=k.useState(null),[We,Ce]=k.useState(""),[qe,et]=k.useState(new Set),[Ze,rt]=k.useState(!1),ct=Math.max(1,parseInt(t.get("page")||"1",10)||1),[vt,kt]=k.useState(ct),St=k.useCallback(it=>{kt(Xt=>{const Bs=typeof it=="function"?it(Xt):it;return r(us=>{const cr=new URLSearchParams(us);return Bs<=1?cr.delete("page"):cr.set("page",String(Bs)),cr},{replace:!0}),Bs})},[]),[Yt,es]=k.useState(50),[zs,sr]=k.useState("my"),[ms,gt]=k.useState(!1),[Ut,ht]=k.useState(!1),{data:Jt}=uv(),{addToLeadPond:Ms}=xft(Jt==null?void 0:Jt.teamId),ts=!!((cs=Jt==null?void 0:Jt.team)!=null&&cs.lead_pond_enabled&&(Jt!=null&&Jt.teamId)),Xs=!!(Jt!=null&&Jt.teamId),[js,$s]=k.useState([]),[Js,or]=k.useState(!1),Er=it=>{$s([it]),or(!0)},Sr=it=>{$s(it),or(!0)},Gr=it=>{Jt!=null&&Jt.teamId&&Ms.mutate({contact_id:it,team_id:Jt.teamId})},Yr=it=>{Jt!=null&&Jt.teamId&&it.forEach(Xt=>{Ms.mutate({contact_id:Xt,team_id:Jt.teamId})})},Fn=k.useCallback(it=>{rt(!1),et(Xt=>{const Bs=new Set(Xt);return Bs.has(it)?Bs.delete(it):Bs.add(it),Bs})},[]);k.useEffect(()=>{if(!(n!=null&&n.id))return;const it=U.channel(`innercircle_contacts_inserts_${n.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${n.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{U.removeChannel(it)}},[i,n==null?void 0:n.id]),k.useEffect(()=>{o&&ae(o)},[o]);const[sa,gs]=k.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});k.useEffect(()=>{c&&Ve(!0)},[c]),k.useEffect(()=>{var it;Le&&gs({first_name:Le.first_name||"",last_name:Le.last_name||"",email:Le.email||"",phone:Le.phone||"",address:Le.address||"",city:Le.city||"",state:Le.state||"",zip_code:Le.zip_code||"",birthday:Le.birthday||"",home_anniversary:Le.home_anniversary||"",spouse_name:Le.spouse_name||"",spouse_email:Le.spouse_email||"",lead_source_id:Le.lead_source_id||"",notes:Le.notes||"",tagIds:((it=Le.tags)==null?void 0:it.map(Xt=>Xt.relationship_type_id))||[]})},[Le]);const mi=k.useMemo(()=>{const it=new Set;return b==null||b.forEach(Xt=>{(Xt.name==="Recruits"||Xt.name==="Brokerage Agents")&&it.add(Xt.id)}),it},[b]),In=k.useMemo(()=>Array.from(N).some(it=>mi.has(it)),[N,mi]),Br=k.useMemo(()=>{if(!d)return[];let it=d.filter(us=>{var pn,wn,ca,Vi,so,Ka,kn,Fi,zi,Qa,Hi;if(!In&&us.synced_source)return!1;const cr=B===""||`${us.first_name} ${us.last_name}`.toLowerCase().includes(B.toLowerCase())||((pn=us.email)==null?void 0:pn.toLowerCase().includes(B.toLowerCase()))||((wn=us.phone)==null?void 0:wn.includes(B))||((ca=us.city)==null?void 0:ca.toLowerCase().includes(B.toLowerCase()))||((Vi=us.state)==null?void 0:Vi.toLowerCase().includes(B.toLowerCase()))||((so=us.address)==null?void 0:so.toLowerCase().includes(B.toLowerCase()))||((Ka=us.zip_code)==null?void 0:Ka.toLowerCase().includes(B.toLowerCase())),Ar=W==="all"||((kn=us.tags)==null?void 0:kn.some(Gi=>Gi.relationship_type_id===W)),xr=N.size===0||(()=>{const Gi=(j==null?void 0:j.filter(Qn=>Qn.contact_id===us.id).map(Qn=>Qn.tag_id))||[];return A==="any"?Gi.some(Qn=>N.has(Qn)):Array.from(N).every(Qn=>Gi.includes(Qn))})(),Kr=!!((Fi=us.address)!=null&&Fi.trim()||(zi=us.city)!=null&&zi.trim()||(Qa=us.state)!=null&&Qa.trim()||(Hi=us.zip_code)!=null&&Hi.trim());return cr&&Ar&&xr&&(de==="all"||de==="has-address"&&Kr||de==="no-address"&&!Kr)});ne==="not-touched-90"?it=it.filter(us=>{const cr=us.relationshipScore.daysSinceTouch;return cr===null||cr>90}):ne==="at-risk"?it=it.filter(us=>us.relationshipScore.status==="at-risk"):ne==="cooling"?it=it.filter(us=>us.relationshipScore.status==="cooling"):ne==="warm"?it=it.filter(us=>us.relationshipScore.status==="warm"):ne==="has-deal"?it=it.filter(us=>_&&_[us.id]):ne==="no-deal"?it=it.filter(us=>!_||!_[us.id]):ne==="open-house"?it=it.filter(us=>{var Ar;return(((Ar=us.lead_source_ref)==null?void 0:Ar.name)||us.lead_source)==="Open House"}):ne==="website-active"?it=it.filter(us=>m.has(us.id)):ne==="never-contacted"?it=it.filter(us=>us.relationshipScore.daysSinceTouch===null):ne==="vips"?it=it.filter(us=>us.relationshipScore.score>=80):ne==="missing-info"?it=it.filter(us=>{var cr,Ar;return!((cr=us.email)!=null&&cr.trim())&&!((Ar=us.phone)!=null&&Ar.trim())}):ne==="birthdays-soon"?it=it.filter(us=>{const cr=zT(us.birthday);return cr!==null&&cr<=30}):ne==="anniversary-soon"?it=it.filter(us=>{const cr=zT(us.home_anniversary);return cr!==null&&cr<=30}):ne==="in-drip"?it=it.filter(us=>((x==null?void 0:x[us.id])??0)>0):ne==="not-in-drip"&&(it=it.filter(us=>((x==null?void 0:x[us.id])??0)===0));const Xt=je;if(Xt.lastActive||Xt.registered||Xt.viewedListing||Xt.savedProperty||Xt.hasSavedSearch||Xt.requestedShowing||Xt.requestedValuation||Xt.websiteActiveOnly){const us=Date.now(),cr={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};it=it.filter(Ar=>{const xr=Oe.get(Ar.id);if(Xt.lastActive==="never"){if(xr!=null&&xr.lastActiveAt)return!1}else if(Xt.lastActive){const Kr=us-cr[Xt.lastActive];if(!(xr!=null&&xr.lastActiveAt)||new Date(xr.lastActiveAt).getTime()0)||Xt.viewedListing==="multiple7d"&&!(xr&&xr.propertyViewCount7d>=3)||Xt.savedProperty&&!(xr&&xr.savedListingCount>0)||Xt.hasSavedSearch&&!(xr&&xr.activeSavedSearchCount>0)||Xt.requestedShowing&&!(xr&&xr.showingRequests>0)||Xt.requestedValuation&&!(xr&&xr.valuationRequests>0)||Xt.websiteActiveOnly&&!m.has(Ar.id))})}return it=[...it].sort((us,cr)=>{switch(ue){case"important-dates":{const Ar=zT(us.birthday),xr=zT(cr.birthday),Kr=zT(us.home_anniversary),mn=zT(cr.home_anniversary),pn=[Ar,Kr].filter(ca=>ca!==null).sort((ca,Vi)=>(ca??1/0)-(Vi??1/0))[0]??1/0,wn=[xr,mn].filter(ca=>ca!==null).sort((ca,Vi)=>(ca??1/0)-(Vi??1/0))[0]??1/0;return pn-wn}case"last-touched":{const Ar=us.relationshipScore.lastTouchDate,xr=cr.relationshipScore.lastTouchDate;return!Ar&&!xr?0:Ar?xr?new Date(Ar).getTime()-new Date(xr).getTime():1:-1}case"next-touch":{const Ar=us.relationshipScore.daysSinceTouch,xr=cr.relationshipScore.daysSinceTouch;return Ar===null&&xr===null?0:Ar===null?-1:xr===null?1:xr-Ar}case"score":return us.relationshipScore.score-cr.relationshipScore.score;case"date-added":{const Ar=us.created_at,xr=cr.created_at;return!Ar&&!xr?0:Ar?xr?new Date(xr).getTime()-new Date(Ar).getTime():-1:1}case"last-name":{const Ar=(us.last_name||"").toLowerCase(),xr=(cr.last_name||"").toLowerCase();if(Ar!==xr)return Ar.localeCompare(xr);const Kr=(us.first_name||"").toLowerCase(),mn=(cr.first_name||"").toLowerCase();return Kr.localeCompare(mn)}case"name":default:{const Ar=`${us.first_name||""} ${us.last_name||""}`.toLowerCase(),xr=`${cr.first_name||""} ${cr.last_name||""}`.toLowerCase();return Ar.localeCompare(xr)}}}),it},[d,B,W,N,A,ne,ue,_,j,m,x,de,je,Oe,In]),ps=Br.length,Or=Math.max(1,Math.ceil(ps/Yt)),Qr=Math.min(vt,Or),Tn=k.useMemo(()=>{const it=(Qr-1)*Yt;return Br.slice(it,it+Yt)},[Br,Qr,Yt]),Qt=k.useRef(!1);k.useEffect(()=>{if(!Qt.current){Qt.current=!0;return}St(1)},[B,W,N,A,ne,ue,de,je]);const Re=k.useCallback(()=>{rt(!1),et(it=>it.size>0?new Set:new Set(Tn.map(Xt=>Xt.id)))},[Tn]),Ke=k.useCallback(()=>{rt(!0),et(new Set(Br.map(it=>it.id)))},[Br]),at=k.useCallback((it,Xt)=>{K(it.search||""),te(it.type||"all"),ae(it.status||"all"),xe(it.behavior||{}),me(Xt||"name")},[]),Nt=()=>{gs({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Ft=async it=>{it.preventDefault();const Xt={...sa,lead_source_id:sa.lead_source_id||null};Le?(await R.mutateAsync({id:Le.id,...Xt}),$e(null)):(await D.mutateAsync(Xt),Ve(!1)),Nt()},qt=async it=>{confirm("Are you sure you want to delete this contact?")&&await F.mutateAsync(it)};return e.jsx(ws,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Contacts"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),Jt&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>sr("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${zs==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(Jt.team.contact_visibility==="full_team"||Jt.team.contact_visibility==="leader_only"&&Jt.role==="team_leader")&&e.jsxs("button",{onClick:()=>sr("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${zs==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Dr,{className:"h-3.5 w-3.5"}),"Team"]}),Jt.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>sr("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${zs==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(S1,{className:"h-3.5 w-3.5"}),"Lead Pond"]})]})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(jl,{className:"h-4 w-4 mr-1"}),"Back"]})}),zs==="team"?e.jsx(VAe,{}):zs==="lead-pond"&&Jt?e.jsx(HAe,{teamId:Jt.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(zzs,{contacts:d,contactDealsMap:_,websiteActiveIds:m,activeKey:{"at-risk":"needs-attention",cooling:"cooling","not-touched-90":"stale-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info"}[ne]??null,onSelect:it=>{const Bs=it?{"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"}[it]:"all";ae(Bs),St(1)}}),e.jsxs(ke,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search contacts...",value:B,onChange:it=>K(it.target.value),className:"pl-9 h-10 rounded-xl bg-muted/40"})]}),e.jsxs(sw,{children:[e.jsx(mge,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl relative shrink-0","aria-label":"Filters",children:[e.jsx(dS,{className:"h-4 w-4"}),(()=>{const it=(W!=="all"?1:0)+(ne!=="all"?1:0)+(de!=="all"?1:0)+N.size+Object.values(je).filter(Xt=>Xt!==void 0&&Xt!==!1).length;return it>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:it}):null})()]})}),e.jsxs(U1,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(rw,{className:"text-left",children:e.jsx(nw,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(Ds,{value:W,onValueChange:te,children:[e.jsx(Ps,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(Fs,{placeholder:"All Types"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),y==null?void 0:y.filter(it=>it.active).map(it=>e.jsx(lt,{value:it.id,children:it.name},it.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(Ds,{value:ne,onValueChange:ae,children:[e.jsx(Ps,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(Fs,{placeholder:"All Status"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Status"}),e.jsx(lt,{value:"warm",children:"🟢 Warm"}),e.jsx(lt,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(lt,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(lt,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(lt,{value:"no-deal",children:"📭 No Deal"}),e.jsx(lt,{value:"open-house",children:"🏠 Open House"}),f&&e.jsx(lt,{value:"website-active",children:"🌐 Website Active"}),e.jsx(lt,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(lt,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(Ds,{value:de,onValueChange:it=>fe(it),children:[e.jsx(Ps,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(Fs,{placeholder:"All Addresses"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Addresses"}),e.jsx(lt,{value:"has-address",children:"Has Address"}),e.jsx(lt,{value:"no-address",children:"No Address"})]})]})]}),b&&b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{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:b.map(it=>{const Xt=N.has(it.id);return e.jsxs("button",{onClick:()=>{C(Bs=>{const us=new Set(Bs);return us.has(it.id)?us.delete(it.id):us.add(it.id),us})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${Xt?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:it.color}}),it.name]},it.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(Ds,{value:ue,onValueChange:me,children:[e.jsx(Ps,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"name",children:"Name (A-Z)"}),e.jsx(lt,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(lt,{value:"important-dates",children:"Important Dates"}),e.jsx(lt,{value:"last-touched",children:"Last Touched"}),e.jsx(lt,{value:"next-touch",children:"Next Touch Due"}),e.jsx(lt,{value:"score",children:"Relationship Score"}),e.jsx(lt,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs(q,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Me(!0),children:[e.jsx(Ir,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(q,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>gt(!0),children:[e.jsx(Fh,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(sWe,{currentFilters:{search:B,type:W,status:ne,behavior:je},currentSortBy:ue,onApplySmartList:at})}),e.jsx(q,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{te("all"),ae("all"),fe("all"),C(new Set),xe({})},children:"Clear all filters"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(q,{onClick:()=>Ve(!0),className:"h-11 rounded-xl",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1.5"})," Add Contact"]}),e.jsxs(q,{onClick:()=>Q(!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(ld,{className:"h-4 w-4 mr-1.5"})," Heat Map"]})]}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:"w-full h-10 rounded-xl gap-2",children:[e.jsx(ka,{className:"h-4 w-4"})," Import & Sync"]})}),e.jsxs(Sd,{align:"center",className:"w-[calc(100vw-2rem)] max-w-sm",children:[e.jsxs(ti,{onClick:()=>Qe(!0),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(ti,{onClick:()=>nt(!0),children:[e.jsx(yg,{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(JGe,{})})]})]})]}),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(_n,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or phone...",value:B,onChange:it=>K(it.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(Dr,{className:"h-3.5 w-3.5"}),"Grid"]}),e.jsxs("button",{type:"button",onClick:()=>Q(!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(ld,{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(q,{onClick:()=>Ve(!0),className:"rounded-none rounded-l-xl h-10 px-4 gap-2 shadow-none",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{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(Ia,{className:"h-4 w-4 rotate-90"})})}),e.jsxs(Sd,{align:"end",children:[e.jsxs(ti,{onClick:()=>Qe(!0),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Import CSV"]}),e.jsxs(ti,{onClick:()=>nt(!0),children:[e.jsx(yg,{className:"h-4 w-4 mr-2"}),"Import from Phone"]})]})]})]}),e.jsx(JGe,{}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsx(q,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(Uu,{className:"h-4 w-4"})})}),e.jsxs(Ko,{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(it=>e.jsx("button",{onClick:()=>me(it.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${ue===it.v?"bg-accent font-medium text-primary":""}`,children:it.l},it.v))]})]})]})]}),e.jsxs("div",{className:"hidden sm:flex px-3 sm:px-4 py-3 bg-muted/40 border-t flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Ds,{value:W,onValueChange:te,children:[e.jsx(Ps,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(Fs,{placeholder:"All Types"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),y==null?void 0:y.filter(it=>it.active).map(it=>e.jsx(lt,{value:it.id,children:it.name},it.id))]})]}),e.jsxs(Ds,{value:ne,onValueChange:ae,children:[e.jsx(Ps,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(Fs,{placeholder:"All Status"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Status"}),e.jsx(lt,{value:"warm",children:"🟢 Warm"}),e.jsx(lt,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(lt,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(lt,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(lt,{value:"no-deal",children:"📭 No Deal"}),e.jsx(lt,{value:"open-house",children:"🏠 Open House"}),f&&e.jsx(lt,{value:"website-active",children:"🌐 Website Active"}),e.jsx(lt,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(lt,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(Ds,{value:de,onValueChange:it=>fe(it),children:[e.jsx(Ps,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(Fs,{placeholder:"All Addresses"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Addresses"}),e.jsx(lt,{value:"has-address",children:"Has Address"}),e.jsx(lt,{value:"no-address",children:"No Address"})]})]}),b&&b.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(sl,{children:[e.jsx(rl,{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(Fh,{className:"h-3.5 w-3.5"}),N.size===0?"Filter by Tags":`${N.size} tag${N.size>1?"s":""}`]})}),e.jsx(Ko,{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:b.map(it=>{const Xt=N.has(it.id);return e.jsxs("button",{onClick:()=>{C(Bs=>{const us=new Set(Bs);return us.has(it.id)?us.delete(it.id):us.add(it.id),us})},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(Ri,{checked:Xt,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:it.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:it.name})]},it.id)})}),N.size>0&&e.jsx(q,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>C(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(Gd,{children:[e.jsx(Wd,{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(Bo,{className:"h-3.5 w-3.5"})})}),e.jsxs(Sd,{align:"end",children:[e.jsxs(ti,{onClick:()=>gt(!0),children:[e.jsx(Fh,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(ti,{onClick:()=>ht(!0),children:[e.jsx(S1,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sWe,{currentFilters:{search:B,type:W,status:ne,behavior:je},currentSortBy:ue,onApplySmartList:at}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsxs(q,{variant:"outline",size:"sm",className:"gap-1.5 h-8 rounded-lg border-[#2a4c64]/20 text-[#2a4c64] hover:bg-[#2a4c64]/5 hover:text-[#2a4c64]",onClick:()=>Me(!0),children:[e.jsx(Ir,{className:"h-3.5 w-3.5"}),"Advanced Filters",Object.values(je).filter(it=>it!==void 0&&it!==!1).length>0&&e.jsx(Xe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Object.values(je).filter(it=>it!==void 0&&it!==!1).length})]})]})]}),Object.values(je).some(it=>it!==void 0&&it!==!1)&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(Rzs,{behavior:je,onRemove:it=>xe(Xt=>{const Bs={...Xt};return delete Bs[it],Bs}),onClearAll:()=>xe({})})})]}),e.jsx(Dzs,{open:Ee,onOpenChange:Me,hasLeadSite:Ie||f,behavior:je,onApply:xe,selectedType:W,onSelectedTypeChange:te,relationshipTypes:y}),e.jsx(Pzs,{selectedIds:qe,contacts:Br,onClearSelection:()=>{et(new Set),rt(!1)},showLeadPondAction:ts,onSendToLeadPond:Yr,showTransferAction:Xs,onTransfer:Sr}),qe.size>0&&qe.size===Tn.length&&!Ze&&ps>Yt&&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 ",Tn.length," contacts on this page are selected."]}),e.jsxs(q,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:Ke,children:["Select all ",ps.toLocaleString()," matching contacts"]})]}),Ze&&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 ",ps.toLocaleString()," matching contacts are selected.",e.jsx(q,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{et(new Set),rt(!1)},children:"Clear selection"})]}),ps>Yt&&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 ",(Qr-1)*Yt+1,"–",Math.min(Qr*Yt,ps)," of ",ps.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"outline",size:"sm",disabled:Qr<=1,onClick:()=>St(1),children:"First"}),e.jsx(q,{variant:"outline",size:"sm",disabled:Qr<=1,onClick:()=>St(it=>it-1),children:e.jsx(jl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Qr," of ",Or]}),e.jsx(q,{variant:"outline",size:"sm",disabled:Qr>=Or,onClick:()=>St(it=>it+1),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(q,{variant:"outline",size:"sm",disabled:Qr>=Or,onClick:()=>St(Or),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:u?e.jsx(ke,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):Br.length===0?e.jsx(ke,{className:"p-6 text-center text-muted-foreground",children:B||W!=="all"||ne!=="all"||de!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):Tn.map(it=>{var Bs,us,cr;const{relationshipScore:Xt}=it;return e.jsx(ke,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const Ar=new URLSearchParams;B&&Ar.set("search",B),W!=="all"&&Ar.set("type",W),ne!=="all"&&Ar.set("filter",ne),N.size>0&&(Ar.set("tags",Array.from(N).join(",")),Ar.set("tagMode",A));const xr=Ar.toString();s(`/mission-control/contacts/${it.id}${xr?`?${xr}`:""}`)},children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsxs("h3",{className:"font-semibold text-base truncate",children:[it.first_name," ",it.last_name]}),e.jsx(oWe,{count:(x==null?void 0:x[it.id])??0}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[it.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ks,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:it.email})]}),it.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Mn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:it.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(G7,{score:Xt,size:"sm"}),e.jsx(hCe,{contact:it}),(((Bs=it.lead_source_ref)==null?void 0:Bs.name)||it.lead_source)&&e.jsx(Xe,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((us=it.lead_source_ref)==null?void 0:us.name)||it.lead_source}),(cr=it.tags)==null?void 0:cr.map(Ar=>{var xr;return e.jsx(Xe,{variant:"secondary",className:"text-xs",children:(xr=Ar.relationship_type)==null?void 0:xr.name},Ar.id)}),e.jsx(lWe,{contactId:it.id,tags:j==null?void 0:j.filter(Ar=>Ar.contact_id===it.id)}),e.jsx(iWe,{deal:_==null?void 0:_[it.id]})]}),e.jsx(aWe,{birthday:it.birthday,homeAnniversary:it.home_anniversary,weddingAnniversary:it.wedding_anniversary,className:"mb-2",contactId:it.id,contactName:`${it.first_name}${it.last_name?" "+it.last_name:""}`,contactAddress:[it.address,it.city,it.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Xt.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),As(new Date(Xt.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),it.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(vn,{className:"h-3 w-3"}),As(El(it.birthday),"MMM d")]}),it.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),As(El(it.home_anniversary),"MMM d")]}),it.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ys,{className:"h-3 w-3"}),"Added ",As(new Date(it.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:Ar=>Ar.stopPropagation(),children:e.jsx(tWe,{contact:it,onEdit:$e,onDelete:qt,onSnooze:(Ar,xr)=>{Ge(Ar),Ce(xr)},showLeadPondAction:ts,onSendToLeadPond:Gr,showTransferAction:Xs,onTransfer:Er})})]})})},it.id)})}):e.jsx(ke,{children:e.jsx(Pe,{className:"p-0 overflow-x-auto",children:e.jsxs(da,{className:"min-w-[800px]",children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-[40px]",children:e.jsx(Ri,{checked:Tn.length>0&&Tn.every(it=>qe.has(it.id)),onCheckedChange:()=>Re()})}),e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Score"}),e.jsx(At,{children:"Contact Info"}),e.jsx(At,{children:"Types / Pipeline"}),e.jsx(At,{children:"Last Contact"}),e.jsx(At,{className:"cursor-pointer select-none",onClick:()=>me(ue==="date-added"?"name":"date-added"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Date Added",ue==="date-added"&&e.jsx(Uu,{className:"h-3 w-3"})]})}),e.jsx(At,{children:"Important Dates"}),e.jsx(At,{className:"w-[50px]",children:"Actions"})]})}),e.jsx(ha,{children:u?e.jsx(Ws,{children:e.jsx(xt,{colSpan:10,className:"text-center py-8",children:"Loading contacts..."})}):Br.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:B||W!=="all"||ne!=="all"||de!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):Tn.map(it=>{var us,cr,Ar;const{relationshipScore:Xt}=it,Bs=_==null?void 0:_[it.id];return e.jsxs(Ws,{className:`cursor-pointer hover:bg-accent/50 ${qe.has(it.id)?"bg-accent/30":""}`,onClick:()=>{const xr=new URLSearchParams;B&&xr.set("search",B),W!=="all"&&xr.set("type",W),ne!=="all"&&xr.set("status",ne),N.size>0&&(xr.set("tags",Array.from(N).join(",")),xr.set("tagMode",A));const Kr=xr.toString();s(`/mission-control/contacts/${it.id}${Kr?`?${Kr}`:""}`)},children:[e.jsx(xt,{onClick:xr=>xr.stopPropagation(),children:e.jsx(Ri,{checked:qe.has(it.id),onCheckedChange:()=>Fn(it.id)})}),e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{children:[it.first_name," ",it.last_name]}),e.jsx(oWe,{count:(x==null?void 0:x[it.id])??0})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(G7,{score:Xt,size:"sm"}),e.jsx(hCe,{contact:it})]})}),e.jsx(xt,{children:e.jsx(G7,{score:Xt,size:"sm",showScore:!0})}),e.jsx(xt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[it.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ks,{className:"h-3 w-3"}),it.email]}),it.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Mn,{className:"h-3 w-3"}),it.phone]})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(((us=it.lead_source_ref)==null?void 0:us.name)||it.lead_source)&&e.jsx(Xe,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((cr=it.lead_source_ref)==null?void 0:cr.name)||it.lead_source}),(Ar=it.tags)==null?void 0:Ar.map(xr=>{var Kr;return e.jsx(Xe,{variant:"secondary",className:"text-xs",children:(Kr=xr.relationship_type)==null?void 0:Kr.name},xr.id)}),e.jsx(lWe,{contactId:it.id,tags:j==null?void 0:j.filter(xr=>xr.contact_id===it.id)}),e.jsx(iWe,{deal:Bs})]})}),e.jsx(xt,{children:e.jsx("div",{className:"text-sm",children:Xt.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(jn,{className:"h-3 w-3"}),As(new Date(Xt.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-muted-foreground text-xs italic",children:"Never contacted"})})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:it.created_at?As(new Date(it.created_at),"MMM d, yyyy"):"—"})}),e.jsx(xt,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(aWe,{birthday:it.birthday,homeAnniversary:it.home_anniversary,weddingAnniversary:it.wedding_anniversary,contactId:it.id,contactName:`${it.first_name}${it.last_name?" "+it.last_name:""}`,contactAddress:[it.address,it.city,it.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[it.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(vn,{className:"h-3 w-3"}),As(El(it.birthday),"MMM d")]}),it.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),As(El(it.home_anniversary),"MMM d")]})]})]})}),e.jsx(xt,{children:e.jsx(tWe,{contact:it,onEdit:$e,onDelete:qt,onSnooze:(xr,Kr)=>{Ge(xr),Ce(Kr)},showLeadPondAction:ts,onSendToLeadPond:Gr,showTransferAction:Xs,onTransfer:Er})})]},it.id)})})]})})}),ps>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 ",(Qr-1)*Yt+1,"–",Math.min(Qr*Yt,ps)," of ",ps.toLocaleString()," contacts"]}),e.jsxs(Ds,{value:String(Yt),onValueChange:it=>{es(Number(it)),St(1)},children:[e.jsx(Ps,{className:"w-[80px] h-8",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"50",children:"50"}),e.jsx(lt,{value:"100",children:"100"}),e.jsx(lt,{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(q,{variant:"outline",size:"sm",disabled:Qr<=1,onClick:()=>St(1),children:"First"}),e.jsx(q,{variant:"outline",size:"sm",disabled:Qr<=1,onClick:()=>St(it=>it-1),children:e.jsx(jl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Qr," of ",Or]}),e.jsx(q,{variant:"outline",size:"sm",disabled:Qr>=Or,onClick:()=>St(it=>it+1),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(q,{variant:"outline",size:"sm",disabled:Qr>=Or,onClick:()=>St(Or),children:"Last"})]})]}),e.jsx(vs,{open:ze||!!Le,onOpenChange:it=>{it||(Ve(!1),$e(null),Nt())},children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:Le?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Ft,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"first_name",children:"First Name *"}),e.jsx(Ne,{id:"first_name",value:sa.first_name,onChange:it=>gs({...sa,first_name:it.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"last_name",children:"Last Name"}),e.jsx(Ne,{id:"last_name",value:sa.last_name,onChange:it=>gs({...sa,last_name:it.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",value:sa.email,onChange:it=>gs({...sa,email:it.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"phone",children:"Phone"}),e.jsx(Ne,{id:"phone",value:sa.phone,onChange:it=>gs({...sa,phone:it.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"address",children:"Address"}),e.jsx(Ne,{id:"address",value:sa.address,onChange:it=>gs({...sa,address:it.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:sa.city,onChange:it=>gs({...sa,city:it.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:sa.state,onChange:it=>gs({...sa,state:it.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"zip_code",children:"Zip"}),e.jsx(Ne,{id:"zip_code",value:sa.zip_code,onChange:it=>gs({...sa,zip_code:it.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"birthday",children:"Birthday"}),e.jsx(Ne,{id:"birthday",type:"date",value:sa.birthday,onChange:it=>gs({...sa,birthday:it.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(Ne,{id:"home_anniversary",type:"date",value:sa.home_anniversary,onChange:it=>gs({...sa,home_anniversary:it.target.value})})]})]}),Le&&e.jsx(mCe,{contactId:Le.id,currentSpouseContactId:(Le==null?void 0:Le.spouse_contact_id)||null,currentSpouseName:(Le==null?void 0:Le.spouse_name)||null,currentSpouseEmail:(Le==null?void 0:Le.spouse_email)||null,onLink:it=>O.mutate({contactId:Le.id,spouseContactId:it}),onUnlink:()=>O.mutate({contactId:Le.id,spouseContactId:null}),isEditing:!0}),e.jsx(syt,{value:sa.lead_source_id,onChange:it=>gs({...sa,lead_source_id:it})}),e.jsxs("div",{children:[e.jsx(ce,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:y==null?void 0:y.filter(it=>it.active).map(it=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Ri,{checked:sa.tagIds.includes(it.id),onCheckedChange:Xt=>{gs(Xt?{...sa,tagIds:[...sa.tagIds,it.id]}:{...sa,tagIds:sa.tagIds.filter(Bs=>Bs!==it.id)})}}),e.jsx("span",{className:"text-sm",children:it.name})]},it.id))})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"notes",children:"Notes"}),e.jsx(pr,{id:"notes",value:sa.notes,onChange:it=>gs({...sa,notes:it.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>{Ve(!1),$e(null),Nt()},children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:D.isPending||R.isPending,children:[Le?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(J9s,{open:ve,onOpenChange:Qe,relationshipTypes:(y==null?void 0:y.filter(it=>it.active))||[],onSuccess:()=>{Qe(!1)}}),e.jsx(szs,{open:we,onOpenChange:nt,onComplete:()=>nt(!1)}),e.jsx(yye,{open:!!Se,onOpenChange:it=>{it||Ge(null)},contactId:Se||"",contactName:We}),e.jsx(Wzs,{open:ms,onOpenChange:gt}),e.jsx(Kzs,{open:Ut,onOpenChange:ht}),e.jsx(qzs,{open:Z,onOpenChange:Q,contacts:d||[],onCitySelect:it=>{K(it),St(1)}}),e.jsx(gft,{open:Js,onOpenChange:or,contactIds:js,contactNames:js.map(it=>{const Xt=Br.find(Bs=>Bs.id===it);return Xt?`${Xt.first_name} ${Xt.last_name||""}`.trim():""}),onComplete:()=>{$s([]),et(new Set),rt(!1)}})]})]})})}const Zzs="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function Xzs({open:s,onOpenChange:t,contact:r}){var Z;const{user:n}=Cs(),a=qr(),i=is(),{intakePage:l,isLoading:o}=vye(),{isGmailConnected:c,gmailEmail:d}=Cm(),u=Rge(),{data:m}=pt({queryKey:["profile-for-invite",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&s,queryFn:async()=>{const{data:Q}=await U.from("profiles").select("name, email, avatar_url").eq("id",n.id).maybeSingle();return Q}}),f=(m==null?void 0:m.name)||((Z=n==null?void 0:n.email)==null?void 0:Z.split("@")[0])||"Your Agent",x=f.split(" ")[0],y=l?`https://contacts.relevelup.com/${l.slug}`:"",_=k.useMemo(()=>`Hi ${r.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[r.first_name]),[b,j]=k.useState("gmail"),[N,C]=k.useState(""),[A,E]=k.useState(""),[D,R]=k.useState(!1);k.useEffect(()=>{s&&(C(`Quick favor, ${r.first_name} — can you update your info?`),E(_),j(c?"gmail":"system"))},[s,_,r.first_name,c]);const F=k.useMemo(()=>A.split(/\n\n+/).map(Q=>`

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

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

A note from ${f}

${F}

Update Your Info

Takes about a minute — promise

Share My Info →

${y}

Sent with care by ${f}

Powered by ReLevelUp

`,B=async()=>{if(!l){he.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!N.trim()||!A.trim()){he.error("Subject and message are required");return}R(!0);const Q=O();try{if(b==="gmail"&&c){const{data:W,error:te}=await U.functions.invoke("gmail-send",{body:{to:r.email,subject:N,body:Q,contactId:r.id}});if(te)throw te;if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Failed to send")}else{const{data:W,error:te}=await U.functions.invoke("send-connect-invite",{body:{contactEmail:r.email,subject:N,htmlBody:Q,replyToEmail:(m==null?void 0:m.email)||(n==null?void 0:n.email),agentName:f}});if(te)throw te;if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Failed to send")}try{await u.mutateAsync({contactId:r.id,actionTypeId:Zzs,notes:`Sent Connect Page invite — Subject: "${N}"`})}catch(W){console.warn("Failed to log activity:",W)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),he.success("Connect Page invite sent!"),t(!1)}catch(W){console.error("Send error:",W),he.error(W instanceof Error?W.message:"Failed to send invite")}finally{R(!1)}},K=O();return e.jsx(vs,{open:s,onOpenChange:Q=>!D&&t(Q),children:e.jsxs(ys,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[r.first_name," ",r.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(ta,{value:b,onValueChange:Q=>j(Q),className:"mt-1.5",children:e.jsxs(ea,{className:"grid w-full grid-cols-2",children:[e.jsxs(rs,{value:"gmail",disabled:!c,children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(rs,{value:"system",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:b==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(m==null?void 0:m.email)||(n==null?void 0:n.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(Ne,{id:"invite-subject",value:N,onChange:Q=>C(Q.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(pr,{id:"invite-message",value:A,onChange:Q=>E(Q.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(ce,{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(un,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden bg-muted/30",children:e.jsx("iframe",{srcDoc:K,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(q,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsx(q,{onClick:B,disabled:D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(go,{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(q,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(Ul,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function Qzs(){const{user:s}=Cs();return pt({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Jzs(s){return pt({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:r}=await U.from("cmas").select("*").eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function eBs(s){return pt({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:r}=await U.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s})}function ryt(){const s=is(),{user:t}=Cs(),{leadSite:r}=hf();return Mt({mutationFn:async n=>{const{data:a,error:i}=await U.from("cmas").insert({agent_id:t.id,lead_site_id:(r==null?void 0:r.id)??null,contact_id:n.contactId??null,deal_id:n.dealId??null,buyer_mode:!!n.buyerMode,title:n.title??n.subject.address,subject:n.subject,settings:{sqftPct:.2,monthsBack:6,statuses:["Active","Pending","Closed"]}}).select("*").single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function tBs(){const s=is();return Mt({mutationFn:async({id:t,patch:r})=>{const{data:n,error:a}=await U.from("cmas").update(r).eq("id",t).select("*").single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["cma",r.id]}),s.invalidateQueries({queryKey:["cmas"]})}})}function sBs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("cmas").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function rBs(){const{leadSite:s}=hf();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(n)throw n;return r}})}function nBs(){const{leadSite:s}=hf();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(n)throw n;return r}})}function aBs(){const s=is();return Mt({mutationFn:async({cmaId:t,comps:r})=>{if(await U.from("cma_comps").delete().eq("cma_id",t),!r.length)return;const n=r.map((i,l)=>({cma_id:t,mls_number:i.mlsNumber??null,source_provider:i.source_provider??null,selected:i.selected!==!1,manual:!!i.manual,score:i.score??null,position:l,snapshot:i})),{error:a}=await U.from("cma_comps").insert(n);if(a)throw a},onSuccess:(t,r)=>s.invalidateQueries({queryKey:["cma-comps",r.cmaId]})})}function dWe(s,t){const r=t.filter(m=>{var f,x;return m.selected!==!1&&(((f=m.snapshot)==null?void 0:f.sqft)||m.sqft)&&(((x=m.snapshot)==null?void 0:x.price)||m.price)});if(!r.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const n=r.map(m=>{const f=m.snapshot||m;return(f.soldPrice||f.price)/f.sqft}).filter(m=>Number.isFinite(m)&&m>0).sort((m,f)=>m-f);if(!n.length)return{low:null,likely:null,high:null,ppsf:null};const a=n[Math.floor(n.length/2)],i=n.reduce((m,f)=>m+f,0)/n.length,l=n.reduce((m,f)=>m+(f-i)**2,0)/n.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 iBs(s){return pt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function oBs(s){return pt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function c6e(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("client_portals").insert({deal_id:r.deal_id,owner_user_id:s,slug:"",is_enabled:r.is_enabled??!0,visibility:r.visibility||"private",require_onboarding:r.require_onboarding??!0,allow_spouse:r.allow_spouse??!1,client_name:r.client_name||null,client_email:r.client_email||null,client_phone:r.client_phone||null,invite_method:r.invite_method||"email"}).select().single();if(a)throw a;return n},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["client-portal",n.deal_id]})}})}function nD(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("client_portals").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function nyt(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function ayt(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function iyt(){const s=is();return Mt({mutationFn:async({id:t,dealId:r})=>{await U.from("portal_updates").delete().eq("portal_id",t);const{error:n}=await U.from("client_portals").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function lBs(s){return pt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function oyt(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["portal-updates",r.portal_id]})}})}function cBs(){const s=xa();return pt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function dBs(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("portal_custom_questions").insert({owner_user_id:s,question_text:r.question_text,field_type:r.field_type,options:r.options||[],is_required:r.is_required||!1,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function uBs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("portal_custom_questions").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function hBs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function R_(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function mBs({contactId:s}){const t=qr(),r=is(),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(null),_=nD(),b=oyt(),{data:j,isLoading:N}=pt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:F,error:O}=await U.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(O)throw O;if(!F||F.length===0)return[];const B=F.map(Q=>Q.id),{data:K,error:Z}=await U.from("client_portals").select("*").in("deal_id",B).is("archived_at",null);if(Z)throw Z;return(K||[]).map(Q=>({...Q,deal:F.find(W=>W.id===Q.deal_id)}))},enabled:!!s}),C=(j==null?void 0:j.map(F=>F.id))||[],{data:A}=pt({queryKey:["contact-portal-updates",C],queryFn:async()=>{if(C.length===0)return{};const{data:F,error:O}=await U.from("portal_updates").select("*").in("portal_id",C).order("created_at",{ascending:!1});if(O)throw O;const B={};return(F||[]).forEach(K=>{B[K.portal_id]||(B[K.portal_id]=K)}),B},enabled:C.length>0}),E=F=>{navigator.clipboard.writeText(R_(F)),a(F),he.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},D=async F=>{d.trim()&&(await b.mutateAsync({portal_id:F,title:d,content:m||void 0}),c(!1),u(""),f(""),r.invalidateQueries({queryKey:["contact-portal-updates"]}),he.success("Portal update posted!"))},R=async()=>{x&&(await _.mutateAsync({id:x.id,welcome_message:x.welcome_message,next_step_text:x.next_step_text,is_enabled:x.is_enabled,show_post_close_tips:x.show_post_close_tips,review_url:x.review_url}),l(!1),y(null),r.invalidateQueries({queryKey:["contact-portals",s]}),he.success("Portal settings updated!"))};return N||!j||j.length===0?null:e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ql,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Pe,{className:"space-y-3",children:j.map(F=>{var Z,Q,W;const O=((Z=F.stage_mapping)==null?void 0:Z.length)>0?F.stage_mapping:Nge(((Q=F.deal)==null?void 0:Q.deal_type)||"buyer"),B=O==null?void 0:O[F.current_stage_index??0],K=A==null?void 0:A[F.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=F.deal)==null?void 0:W.deal_name)||"Portal"}),B&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",B.label||B.name]})]}),e.jsx(Xe,{variant:F.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:F.is_enabled?"Active":"Disabled"})]}),K&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:K.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:As(new Date(K.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(q,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>E(F.slug),children:[n===F.slug?e.jsx(la,{className:"h-3 w-3 mr-1"}):e.jsx(si,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(q,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(R_(F.slug),"_blank"),children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(Ui,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Title"}),e.jsx(Ne,{value:d,onChange:te=>u(te.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Details (optional)"}),e.jsx(pr,{value:m,onChange:te=>f(te.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(q,{onClick:()=>D(F.id),disabled:!d.trim()||b.isPending,className:"w-full",children:[e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(vs,{open:i,onOpenChange:l,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{y({...F}),l(!0)},children:[e.jsx(Bo,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Portal Settings"})}),x&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Portal Enabled"}),e.jsx(Rr,{checked:x.is_enabled,onCheckedChange:te=>y({...x,is_enabled:te})})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Welcome Message"}),e.jsx(pr,{value:x.welcome_message||"",onChange:te=>y({...x,welcome_message:te.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Next Step"}),e.jsx(Ne,{value:x.next_step_text||"",onChange:te=>y({...x,next_step_text:te.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Review URL"}),e.jsx(Ne,{value:x.review_url||"",onChange:te=>y({...x,review_url:te.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Show Post-Close Tips"}),e.jsx(Rr,{checked:x.show_post_close_tips,onCheckedChange:te=>y({...x,show_post_close_tips:te})})]}),e.jsx(cl,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{onClick:R,disabled:_.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(q,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${F.deal_id}`),children:[e.jsx(ci,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),j.length>1&&e.jsx(cl,{})]},F.id)})})]})}function fBs({contactId:s}){const{data:t}=pt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await U.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),r=t&&t.size>0,{data:n,isLoading:a}=pt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await U.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!r});if(!r||a||!n||n.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:"h-7 w-7 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Nn,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(Xe,{variant:"secondary",className:"text-xs ml-auto",children:[n.length," ",n.length===1?"property":"properties"]})]})}),e.jsx(Pe,{className:"pt-0",children:e.jsx("div",{className:"space-y-1",children:n.map(l=>{const o=i(l),c=l.property_address||`MLS# ${l.mls_number}`;return e.jsxs("a",{href:o||"#",target:"_blank",rel:"noopener noreferrer",onClick:d=>{o||d.preventDefault()},className:"group flex items-center gap-3 p-2.5 rounded-lg hover:bg-muted/60 transition-colors",children:[l.photo_url?e.jsx("div",{className:"h-10 w-10 rounded-lg overflow-hidden flex-shrink-0 bg-muted",children:e.jsx("img",{src:l.photo_url,alt:c,className:"w-full h-full object-cover"})}):e.jsx("div",{className:"h-9 w-9 rounded-lg bg-gradient-to-br from-primary/15 to-primary/5 flex items-center justify-center flex-shrink-0",children:e.jsx(Pn,{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(jn,{className:"h-3 w-3"}),e.jsx("span",{title:As(new Date(l.viewed_at),"PPp"),children:Nl(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(un,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const pBs=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function uWe({value:s,onChange:t,onAdd:r,suggestions:n,placeholder:a,icon:i}){const[l,o]=k.useState(!1),c=k.useRef(null),d=k.useRef(null);k.useEffect(()=>{const m=f=>{d.current&&!d.current.contains(f.target)&&c.current&&!c.current.contains(f.target)&&o(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]);const u=n.filter(m=>m.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ne,{ref:c,value:s,onChange:m=>{t(m.target.value),o(!0)},onFocus:()=>o(!0),placeholder:a,onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),u.length>0?r(u[0]):r(s))}}),n.length>0&&e.jsx(Co,{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(q,{type:"button",variant:"outline",size:"sm",onClick:()=>r(s),children:e.jsx(Ys,{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(m=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>{r(m),o(!1)},children:[i||e.jsx(Ma,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),m]},m))})]})}function xBs({contactId:s,contactName:t}){var fe,je,xe;const{user:r}=Cs(),n=xa(),{hasLeadSite:a}=hf(),i=is(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,m]=k.useState(""),[f,x]=k.useState(!1),[y,_]=k.useState(""),[b,j]=k.useState(null),[N,C]=k.useState(!1),[A,E]=k.useState(!1),{data:D}=pt({queryKey:["agent-lead-site-config",n],queryFn:async()=>{const{data:Ee,error:Me}=await U.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",n).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(Me||!Ee)return{cities:[],zipCodes:[]};const Oe=Ee.theme_config||{},Ie=Array.isArray(Oe.searchCities)?Oe.searchCities:[];Ee.mls_market_area&&!Ie.includes(Ee.mls_market_area)&&Ie.unshift(Ee.mls_market_area);const ze=Array.isArray(Oe.searchZipCodes)?Oe.searchZipCodes:[];return{cities:Ie,zipCodes:ze}},enabled:!!n}),{data:R,isLoading:F}=pt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:Ee,error:Me}=await U.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(Me)throw Me;return Ee},enabled:!!s&&!!r}),[O,B]=k.useState({}),K=()=>{B({is_active:(R==null?void 0:R.is_active)??!0,min_price:(R==null?void 0:R.min_price)??null,max_price:(R==null?void 0:R.max_price)??null,min_beds:(R==null?void 0:R.min_beds)??null,min_baths:(R==null?void 0:R.min_baths)??null,min_sqft:(R==null?void 0:R.min_sqft)??null,max_sqft:(R==null?void 0:R.max_sqft)??null,cities:(R==null?void 0:R.cities)??[],zip_codes:(R==null?void 0:R.zip_codes)??[],property_types:(R==null?void 0:R.property_types)??[],frequency:(R==null?void 0:R.frequency)??"daily"}),o(!0)},Z=Mt({mutationFn:async()=>{const Ee={contact_id:s,owner_user_id:n,is_active:O.is_active??!0,min_price:O.min_price||null,max_price:O.max_price||null,min_beds:O.min_beds||null,min_baths:O.min_baths||null,min_sqft:O.min_sqft||null,max_sqft:O.max_sqft||null,cities:O.cities||[],zip_codes:O.zip_codes||[],property_types:O.property_types||[],frequency:O.frequency||"daily"};if(R!=null&&R.id){const{error:Me}=await U.from("contact_property_alerts").update(Ee).eq("id",R.id);if(Me)throw Me}else{const{error:Me}=await U.from("contact_property_alerts").insert(Ee);if(Me)throw Me}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),he.success("Property alert saved!")},onError:Ee=>{he.error(Ee.message||"Failed to save alert")}}),Q=Mt({mutationFn:async()=>{if(!(R!=null&&R.id))return;const{error:Ee}=await U.from("contact_property_alerts").delete().eq("id",R.id);if(Ee)throw Ee},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),he.success("Property alert removed")}}),W=Ee=>{var Oe;const Me=Ee.trim();Me&&!((Oe=O.cities)!=null&&Oe.includes(Me))&&B(Ie=>({...Ie,cities:[...Ie.cities||[],Me]})),d("")},te=Ee=>{var Oe;const Me=Ee.trim();Me&&!((Oe=O.zip_codes)!=null&&Oe.includes(Me))&&B(Ie=>({...Ie,zip_codes:[...Ie.zip_codes||[],Me]})),m("")},ne=Ee=>{B(Me=>{const Oe=Me.property_types||[];return{...Me,property_types:Oe.includes(Ee)?Oe.filter(Ie=>Ie!==Ee):[...Oe,Ee]}})},ae=async()=>{if(R!=null&&R.id){C(!0),x(!0),_(""),j(null);try{const{data:Ee,error:Me}=await U.functions.invoke("process-property-alerts",{body:{alert_id:R.id,mode:"preview"}});if(Me)throw Me;Ee!=null&&Ee.html?(_(Ee.html),j({count:Ee.listings_count||0,recipient:Ee.recipient,subject:Ee.subject})):j({count:0,message:(Ee==null?void 0:Ee.message)||"No matching listings found right now."})}catch(Ee){he.error(Ee.message||"Failed to generate preview"),x(!1)}finally{C(!1)}}},ue=async()=>{if(R!=null&&R.id&&confirm(`Send property alert email to ${t} now?`)){E(!0);try{const{data:Ee,error:Me}=await U.functions.invoke("process-property-alerts",{body:{alert_id:R.id,mode:"send"}});if(Me)throw Me;Ee!=null&&Ee.sent_count?(he.success(`Sent ${Ee.sent_count} ${Ee.sent_count===1?"listing":"listings"} to ${Ee.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):he.info((Ee==null?void 0:Ee.message)||"No new matching listings to send right now.")}catch(Ee){he.error(Ee.message||"Failed to send alert")}finally{E(!1)}}};if(!a||F)return null;if(R&&!l)return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${R.is_active?"bg-green-500/10":"bg-muted"}`,children:R.is_active?e.jsx(ym,{className:"h-4 w-4 text-green-600"}):e.jsx(b_,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(Xe,{variant:R.is_active?"default":"secondary",className:"text-xs ml-auto",children:[R.is_active?"Active":"Paused"," · ",R.frequency]})]})}),e.jsxs(Pe,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[R.min_price||R.max_price?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Xl,{className:"h-3 w-3"}),R.min_price?`$${(R.min_price/1e3).toFixed(0)}k`:"$0"," - ",R.max_price?`$${(R.max_price/1e3).toFixed(0)}k`:"Any"]}):null,R.min_beds?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(e2,{className:"h-3 w-3"}),R.min_beds,"+ beds"]}):null,R.min_baths?e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(of,{className:"h-3 w-3"}),R.min_baths,"+ baths"]}):null,(fe=R.cities)==null?void 0:fe.map(Ee=>e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Ma,{className:"h-3 w-3"}),Ee]},Ee)),(je=R.zip_codes)==null?void 0:je.map(Ee=>e.jsx(Xe,{variant:"outline",children:Ee},Ee)),(xe=R.property_types)==null?void 0:xe.map(Ee=>e.jsx(Xe,{variant:"outline",children:Ee},Ee))]}),R.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(R.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:ae,disabled:N,children:[N?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(q,{size:"sm",onClick:ue,disabled:A||!R.is_active,title:R.is_active?"Send this alert email now":"Activate alert to send",children:[A?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Send Now"]}),e.jsx(q,{variant:"outline",size:"sm",onClick:K,children:"Manage Alert"}),e.jsxs(q,{variant:"destructive",size:"sm",onClick:()=>Q.mutate(),disabled:Q.isPending,children:[Q.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(vs,{open:f,onOpenChange:x,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Property Alert Email Preview"}),(b==null?void 0:b.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:"})," ",b.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",b.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",b.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:N?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(ls,{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:(b==null?void 0:b.message)||"No matching listings found right now."})}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>x(!1),children:"Close"}),y&&e.jsxs(q,{onClick:()=>{x(!1),ue()},disabled:A||!R.is_active,children:[e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]});const me=((D==null?void 0:D.cities)||[]).filter(Ee=>{var Me;return!((Me=O.cities)!=null&&Me.includes(Ee))}),de=((D==null?void 0:D.zipCodes)||[]).filter(Ee=>{var Me;return!((Me=O.zip_codes)!=null&&Me.includes(Ee))});return l?e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(ym,{className:"h-4 w-4 text-primary"}),R?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Alert Active"}),e.jsx(Rr,{checked:O.is_active??!0,onCheckedChange:Ee=>B(Me=>({...Me,is_active:Ee}))})]}),e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Xl,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ne,{type:"number",placeholder:"Min price",value:O.min_price??"",onChange:Ee=>B(Me=>({...Me,min_price:Ee.target.value?Number(Ee.target.value):null}))}),e.jsx(Ne,{type:"number",placeholder:"Max price",value:O.max_price??"",onChange:Ee=>B(Me=>({...Me,max_price:Ee.target.value?Number(Ee.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(e2,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(Ds,{value:O.min_beds?String(O.min_beds):"any",onValueChange:Ee=>B(Me=>({...Me,min_beds:Ee==="any"?null:Number(Ee)})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Any"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"any",children:"Any"}),[1,2,3,4,5].map(Ee=>e.jsxs(lt,{value:String(Ee),children:[Ee,"+"]},Ee))]})]})]}),e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(of,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(Ds,{value:O.min_baths?String(O.min_baths):"any",onValueChange:Ee=>B(Me=>({...Me,min_baths:Ee==="any"?null:Number(Ee)})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Any"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(Ee=>e.jsxs(lt,{value:String(Ee),children:[Ee,"+"]},Ee))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(m2,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ne,{type:"number",placeholder:"Min sqft",value:O.min_sqft??"",onChange:Ee=>B(Me=>({...Me,min_sqft:Ee.target.value?Number(Ee.target.value):null}))}),e.jsx(Ne,{type:"number",placeholder:"Max sqft",value:O.max_sqft??"",onChange:Ee=>B(Me=>({...Me,max_sqft:Ee.target.value?Number(Ee.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ma,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(uWe,{value:c,onChange:d,onAdd:W,suggestions:me,placeholder:"Type to search cities..."}),O.cities&&O.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:O.cities.map(Ee=>e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[Ee,e.jsx("button",{onClick:()=>B(Me=>{var Oe;return{...Me,cities:(Oe=Me.cities)==null?void 0:Oe.filter(Ie=>Ie!==Ee)}}),children:e.jsx($r,{className:"h-3 w-3"})})]},Ee))})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(uWe,{value:u,onChange:m,onAdd:te,suggestions:de,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),O.zip_codes&&O.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:O.zip_codes.map(Ee=>e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[Ee,e.jsx("button",{onClick:()=>B(Me=>{var Oe;return{...Me,zip_codes:(Oe=Me.zip_codes)==null?void 0:Oe.filter(Ie=>Ie!==Ee)}}),children:e.jsx($r,{className:"h-3 w-3"})})]},Ee))})]}),e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Pn,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:pBs.map(Ee=>{var Me;return e.jsx(Xe,{variant:(Me=O.property_types)!=null&&Me.includes(Ee)?"default":"outline",className:"cursor-pointer",onClick:()=>ne(Ee),children:Ee},Ee)})})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"mb-1.5",children:"Frequency"}),e.jsxs(Ds,{value:O.frequency||"daily",onValueChange:Ee=>B(Me=>({...Me,frequency:Ee})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"daily",children:"Daily"}),e.jsx(lt,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(q,{onClick:()=>Z.mutate(),disabled:Z.isPending,className:"flex-1",children:[Z.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(q,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),R&&e.jsx(q,{variant:"destructive",size:"icon",onClick:()=>Q.mutate(),disabled:Q.isPending,children:e.jsx($r,{className:"h-4 w-4"})})]})]})]}):e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("button",{onClick:K,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(ym,{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 gBs({contactId:s,contactName:t}){var ne;const{user:r}=Cs(),n=xa(),{hasLeadSite:a}=hf(),i=is(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,m]=k.useState([]),[f,x]=k.useState(!1),[y,_]=k.useState(!1),[b,j]=k.useState(!1),[N,C]=k.useState(""),A=k.useRef(null),E=k.useRef(null),{data:D}=pt({queryKey:["agent-lead-site-cities",n],queryFn:async()=>{const{data:ae,error:ue}=await U.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",n).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(ue||!ae)return[];const me=ae.theme_config||{},de=Array.isArray(me.searchCities)?me.searchCities:[];return ae.mls_market_area&&!de.includes(ae.mls_market_area)&&de.unshift(ae.mls_market_area),de},enabled:!!n}),{data:R,isLoading:F}=pt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:ae,error:ue}=await U.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(ue)throw ue;return ae},enabled:!!s&&!!r});k.useEffect(()=>{const ae=ue=>{E.current&&!E.current.contains(ue.target)&&A.current&&!A.current.contains(ue.target)&&_(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[]);const O=()=>{x((R==null?void 0:R.market_report_enabled)??!1),m((R==null?void 0:R.market_report_cities)??[]),o(!0)},B=ae=>{const ue=(ae||c).trim();ue&&!u.includes(ue)&&m([...u,ue]),d(""),_(!1)},K=(D||[]).filter(ae=>!u.includes(ae)&&ae.toLowerCase().includes(c.toLowerCase())),Z=Mt({mutationFn:async()=>{const{data:ae,error:ue}=await U.functions.invoke("send-market-report",{body:{action:"preview",agentId:n,cities:(R==null?void 0:R.market_report_cities)??[]}});if(ue)throw new Error(ue.message||"Failed to generate preview");if(ae&&!ae.ok&&ae.error)throw new Error(ae.error);return ae},onSuccess:ae=>{C(ae.html),j(!0)},onError:ae=>{he.error(ae.message||"Failed to generate preview")}}),Q=Mt({mutationFn:async()=>{const{data:ae,error:ue}=await U.functions.invoke("send-market-report",{body:{action:"send",agentId:n,cities:(R==null?void 0:R.market_report_cities)??[],contactIds:[s]}});if(ue)throw new Error(ue.message||"Failed to send report");if(ae&&!ae.ok&&ae.error)throw new Error(ae.error);return ae},onSuccess:()=>{he.success(`Market report sent to ${t}!`)},onError:ae=>{he.error(ae.message||"Failed to send report")}}),W=Mt({mutationFn:async()=>{const{error:ae}=await U.from("innercircle_contacts").update({market_report_enabled:f,market_report_cities:u}).eq("id",s);if(ae)throw ae},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),he.success(f?"Monthly market report enabled!":"Market report disabled")},onError:ae=>{he.error(ae.message||"Failed to save")}}),te=Mt({mutationFn:async()=>{const{error:ae}=await U.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(ae)throw ae},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),x(!1),m([]),he.success("Market report removed")},onError:ae=>{he.error(ae.message||"Failed to remove market report")}});return!a||F?null:R!=null&&R.market_report_enabled&&!l?e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:"h-7 w-7 rounded-lg flex items-center justify-center bg-primary/10",children:e.jsx(Mo,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(Xe,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Pe,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((ne=R.market_report_cities)==null?void 0:ne.length)>0?R.market_report_cities.map(ae=>e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Ma,{className:"h-3 w-3"}),ae]},ae)):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(q,{variant:"outline",size:"sm",onClick:()=>Z.mutate(),disabled:Z.isPending,className:"flex-1",children:[Z.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(q,{variant:"default",size:"sm",onClick:()=>Q.mutate(),disabled:Q.isPending,className:"flex-1",children:[Q.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",size:"sm",onClick:O,className:"flex-1",children:"Manage"}),e.jsxs(q,{variant:"destructive",size:"sm",onClick:()=>te.mutate(),disabled:te.isPending,className:"flex-1",children:[te.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(vs,{open:b,onOpenChange:j,children:e.jsxs(ys,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Mo,{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:N}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(q,{onClick:()=>{j(!1),Q.mutate()},disabled:Q.isPending,className:"flex-1",children:[Q.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(hn,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(q,{variant:"outline",onClick:()=>j(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Mo,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Send Monthly Report"}),e.jsx(Rr,{checked:f,onCheckedChange:x})]}),f&&e.jsxs("div",{children:[e.jsxs(ce,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ma,{className:"h-3.5 w-3.5"})," Report Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select cities from your website's configured areas."}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ne,{ref:A,value:c,onChange:ae=>{d(ae.target.value),_(!0)},onFocus:()=>_(!0),placeholder:"Type to search cities...",onKeyDown:ae=>{ae.key==="Enter"&&(ae.preventDefault(),K.length>0?B(K[0]):B())}}),e.jsx(Co,{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(q,{type:"button",variant:"outline",size:"sm",onClick:()=>B(),children:e.jsx(Ys,{className:"h-4 w-4"})})]}),y&&K.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:K.map(ae=>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:()=>B(ae),children:[e.jsx(Ma,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),ae]},ae))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(ae=>e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[ae,e.jsx("button",{onClick:()=>m(u.filter(ue=>ue!==ae)),children:e.jsx($r,{className:"h-3 w-3"})})]},ae))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(q,{onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(q,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("button",{onClick:O,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(Mo,{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 yBs(s){return pt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:r}=await U.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(r)throw console.error("[ContactDripActivity] enrollments error",r),r;const n=(t||[]).map(c=>c.id),a=Array.from(new Set((t||[]).map(c=>c.campaign_id)));let i=new Map;if(a.length>0){const{data:c}=await U.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(n.length>0){const{data:c,error:d}=await U.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",n).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(u=>{var m;return{...u,campaign:{name:((m=i.get(u.campaign_id))==null?void 0:m.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function vBs(s){switch(s){case"active":return e.jsx(Xe,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(Xe,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(Xe,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(Xe,{variant:"outline",children:"Exited"});default:return e.jsx(Xe,{variant:"outline",children:s})}}function hWe(s){return s==="sent"?e.jsx(qn,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(du,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(Xf,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(jn,{className:"h-4 w-4 text-muted-foreground"})}function bBs({contactId:s}){const t=qr(),{data:r,isLoading:n}=yBs(s),[a,i]=k.useState(null);if(n)return null;const l=(r==null?void 0:r.enrollments)||[],o=(r==null?void 0:r.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(GE,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Pe,{className:"space-y-4",children:[l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Enrollments"}),l.map(c=>{var d;return e.jsxs("button",{onClick:()=>t("/mission-control/smart-drips"),className:"w-full text-left flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-600 flex-shrink-0",children:e.jsx(GE,{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"}),vBs(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: ",Nl(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Nl(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Nl(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(Ia,{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(vs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:m=>!m&&i(null),children:[e.jsx(Yi,{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:hWe(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(Ui,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(Ks,{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"," · ",As(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(ys,{className:"max-w-lg",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[hWe(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:As(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(q,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function lyt({contactId:s}={}){const{user:t}=Cs();return pt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const r=t.id;let n=U.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",r).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(n=n.eq("contact_id",s));let a=U.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",r).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await U.from("email_campaigns").select("id, subject").eq("user_id",r),l=(i.data||[]).map(_=>_.id),o=new Map((i.data||[]).map(_=>[_.id,_.subject]));let c=[];if(l.length>0){let _=U.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(_=_.eq("contact_id",s)),c=(await _).data||[]}const[d,u]=await Promise.all([n,a]),m=(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})),f=(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})),x=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=[...m,...f,...x];return y.sort((_,b)=>_.sent_at0&&e.jsx(Xe,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Pe,{children:r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):t.length===0?e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(Ks,{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(Xe,{variant:"outline",className:`text-xs ${_Bs[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:As(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(q,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!n),children:n?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(Vn,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function jBs({videoId:s}){var l;const{data:t,isLoading:r,error:n}=kzs(s);if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(dr,{className:"w-full aspect-video rounded-lg"}),e.jsx(dr,{className:"h-4 w-1/3"})]});if(n||!t||t.is_deleted)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(du,{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 NBs({contactId:s}){const t=qr(),[r,n]=k.useState(!1),{data:a,isLoading:i}=pt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:m,error:f}=await U.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(f)throw f;return m},enabled:!!s}),l=async(m,f)=>{const x=f==="done"?"todo":"done";await U.from("deal_tasks").update({status:x,completed_at:x==="done"?new Date().toISOString():null}).eq("id",m),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=pt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:m,error:f}=await U.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(f)throw f;return m},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(m=>m.status!=="done"))||[],u=(a==null?void 0:a.filter(m=>m.status==="done"))||[];return e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(la,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>n(!0),children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Pe,{className:"space-y-1",children:i?e.jsx(dr,{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(m=>e.jsxs("button",{onClick:async()=>{await l(m.id,m.status),o()},className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 transition-colors group",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0 group-hover:border-primary"}),e.jsxs("span",{className:"text-sm flex-1 truncate",children:[c[m.priority]," ",m.title]}),m.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:As(new Date(m.due_date),"MMM d")})]},m.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"]})})]})}),r&&e.jsx(kBs,{contactId:s,open:r,onOpenChange:m=>{n(m),m||o()}})]})}function kBs({contactId:s,open:t,onOpenChange:r}){const[n,a]=k.useState(""),[i,l]=k.useState("medium"),[o,c]=k.useState(),{data:d}=pt({queryKey:["session"],queryFn:async()=>{const{data:m}=await U.auth.getSession();return m.session}}),u=async()=>{var f;if(!n.trim()||!((f=d==null?void 0:d.user)!=null&&f.id))return;const{error:m}=await U.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:n.trim(),priority:i,status:"todo",due_date:o?As(o,"yyyy-MM-dd"):null}]);if(m){console.error("Task create error:",m);return}r(!1)};return e.jsx(vs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"sm:max-w-[400px]",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Title"}),e.jsx(Ne,{value:n,onChange:m=>a(m.target.value),placeholder:"Task title...",onKeyDown:m=>m.key==="Enter"&&u()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Priority"}),e.jsxs("select",{value:i,onChange:m=>l(m.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"low",children:"🟢 Low"}),e.jsx("option",{value:"medium",children:"🟡 Medium"}),e.jsx("option",{value:"high",children:"🟠 High"}),e.jsx("option",{value:"urgent",children:"🔴 Urgent"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Due Date"}),e.jsx(Ne,{type:"date",value:o?As(o,"yyyy-MM-dd"):"",onChange:m=>c(m.target.value?new Date(m.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(q,{onClick:u,disabled:!n.trim(),children:"Create Task"})]})]})]})})}function SBs({contactId:s}){const t=qr(),{data:r,isLoading:n}=pt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await U.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return n||!r||r.length===0?null:e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(bm,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Pe,{className:"space-y-2",children:r.map(a=>{const i=a.stage;return e.jsx("button",{onClick:()=>t(`/mission-control/pipeline?deal=${a.id}`),className:"w-full text-left p-3 rounded-lg border hover:bg-accent transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.deal_name}),a.property_address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.property_address}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(Xe,{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(ci,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function CBs(){var gt,Ut,ht,Jt,Ms;const{contactId:s}=xo(),t=qr(),[r]=ic(),n=r.get("search")||"",a=r.get("type")||"all",i=r.get("status")||r.get("filter")||"all",l=r.get("tags")||"",o=r.get("tagMode")==="all"?"all":"any",c=k.useMemo(()=>new Set(l.split(",").map(ts=>ts.trim()).filter(Boolean)),[l]),{data:d,isLoading:u}=aQt(s||""),{data:m}=H0(),{data:f}=TB(),{data:x}=EB(3650),{data:y}=bye(365),{data:_}=iBs(s),{contactsWithScores:b}=zge(),{data:j}=gye(),N=vEe(),C=bEe(),A=Rge(),E=Act(),[D,R]=k.useState(!1),[F,O]=k.useState({}),[B,K]=k.useState(!1),[Z,Q]=k.useState(null),[W,te]=k.useState(""),[ne,ae]=k.useState(void 0),[ue,me]=k.useState(""),[de,fe]=k.useState(null),[je,xe]=k.useState(!1),[Ee,Me]=k.useState(null),[Oe,Ie]=k.useState(!1),{isGmailConnected:ze,gmailEmail:Ve}=Cm(),{isReady:Le}=tD(),$e=Le||ze,ve=ryt(),[Qe,we]=k.useState(!1),{data:nt}=pt({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:ts}}=await U.auth.getUser();if(!ts)return!1;const{data:Xs}=await U.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",ts.id);return(Xs||[]).some(js=>js.is_active&&js.mls_provider_id&&!js.no_mls_mode)}}),Se=async()=>{var Js,or,Er,Sr;if(!d)return;const ts=(Js=d.address)==null?void 0:Js.trim(),Xs=(or=d.city)==null?void 0:or.trim(),js=(Er=d.state)==null?void 0:Er.trim().toUpperCase(),$s=((Sr=d.zip_code)==null?void 0:Sr.trim())||"";if(!ts||!Xs||!js){he.error("Add a full address (street, city, state) before creating a CMA.");return}try{we(!0);const Gr=await ve.mutateAsync({subject:{address:ts,city:Xs,state:js,zip:$s},contactId:d.id,title:`${d.first_name||""} ${d.last_name||""}`.trim()+" — "+ts});t(`/mission-control/cma/${Gr.id}`)}catch(Gr){he.error("Could not create CMA: "+((Gr==null?void 0:Gr.message)||"unknown error"))}finally{we(!1)}},{data:Ge}=pt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:ts,error:Xs}=await U.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Xs)throw Xs;return ts},enabled:!!s}),We=ts=>{if(!ts)return null;const Xs=ts.match(/Video ID:\s*([a-f0-9-]+)/i);return Xs?Xs[1]:null},Ce=k.useMemo(()=>{if(!b)return[];const ts=new Map;if(c.size>0&&j)for(const js of j)ts.has(js.contact_id)||ts.set(js.contact_id,new Set),ts.get(js.contact_id).add(js.tag_id);let Xs=b.filter(js=>{var Er,Sr,Gr;const $s=n===""||`${js.first_name} ${js.last_name}`.toLowerCase().includes(n.toLowerCase())||((Er=js.email)==null?void 0:Er.toLowerCase().includes(n.toLowerCase()))||((Sr=js.phone)==null?void 0:Sr.includes(n)),Js=a==="all"||((Gr=js.tags)==null?void 0:Gr.some(Yr=>Yr.relationship_type_id===a));let or=!0;if(c.size>0){const Yr=ts.get(js.id)||new Set;o==="all"?or=Array.from(c).every(Fn=>Yr.has(Fn)):or=Array.from(c).some(Fn=>Yr.has(Fn))}return $s&&Js&&or});return i==="not-touched-90"?Xs=Xs.filter(js=>{const $s=js.relationshipScore.daysSinceTouch;return $s===null||$s>90}):i==="at-risk"?Xs=Xs.filter(js=>js.relationshipScore.status==="at-risk"):i==="cooling"?Xs=Xs.filter(js=>js.relationshipScore.status==="cooling"):i==="warm"&&(Xs=Xs.filter(js=>js.relationshipScore.status==="warm")),Xs.map(js=>js.id)},[b,n,a,i,c,o,j]),qe=Ce.indexOf(s||""),et=qe>0?Ce[qe-1]:null,Ze=qe1&&qe!==-1,ct=ts=>{const Xs=new URLSearchParams;n&&Xs.set("search",n),a!=="all"&&Xs.set("type",a),i!=="all"&&Xs.set("status",i),c.size>0&&(Xs.set("tags",Array.from(c).join(",")),Xs.set("tagMode",o));const js=Xs.toString();return`/mission-control/contacts/${ts}${js?`?${js}`:""}`},vt=k.useMemo(()=>{const ts=((x==null?void 0:x.filter(js=>js.contact_id===s))||[]).map(js=>{var Er,Sr,Gr;const $s=We(js.notes);let Js=((Er=js.action_type)==null?void 0:Er.name)||"Touch",or=js.notes;if(Js==="Other"&&((Sr=js.notes)!=null&&Sr.startsWith("["))){const Yr=js.notes.indexOf("]");Yr>0&&(Js=js.notes.substring(1,Yr),or=js.notes.substring(Yr+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:js.id,type:"touch",completed_at:js.completed_at,name:Js,color:((Gr=js.action_type)==null?void 0:Gr.color)||"#3B82F6",notes:or,videoId:$s}}),Xs=((y==null?void 0:y.filter(js=>js.contact_id===s))||[]).map(js=>({id:js.id,type:"popby",completed_at:js.completed_at,name:"Pop-by",color:"#F97316",notes:js.notes,videoId:null}));return[...ts,...Xs].sort((js,$s)=>new Date($s.completed_at).getTime()-new Date(js.completed_at).getTime())},[x,y,s]),kt=()=>{var ts;d&&(O({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:((ts=d.tags)==null?void 0:ts.map(Xs=>Xs.relationship_type_id))||[]}),R(!0))},St=async()=>{await N.mutateAsync({id:s,...F,lead_source_id:F.lead_source_id||null}),R(!1)},Yt=async()=>{confirm("Are you sure you want to delete this contact?")&&(await C.mutateAsync(s),t("/mission-control/contacts"))},zs=((gt=f==null?void 0:f.find(ts=>ts.id===Z))==null?void 0:gt.name)==="Other",sr=async()=>{if(!Z||zs&&!ue.trim())return;const ts=ne?new Date(ne.getFullYear(),ne.getMonth(),ne.getDate(),12,0,0).toISOString():void 0,Xs=zs?`[${ue.trim()}]${W?" — "+W:""}`:W;await A.mutateAsync({contactId:s,actionTypeId:Z,notes:Xs,completedAt:ts}),K(!1),Q(null),te(""),ae(void 0),me("")},ms=(ts,Xs)=>{$e&&d?(Me({email:ts,name:Xs||`${d.first_name} ${d.last_name||""}`.trim()}),xe(!0)):window.location.href=`mailto:${ts}`};return u?e.jsx(ws,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):d?e.jsxs(e.Fragment,{children:[e.jsx(ws,{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(q,{variant:"ghost",size:"sm",onClick:()=>{window.history.length>1?t(-1):t("/mission-control/contacts")},children:[e.jsx(jl,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),rt&&e.jsxs("div",{className:"flex items-center gap-1 ml-2 border-l pl-2",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>et&&t(ct(et)),disabled:!et,className:"px-2",children:[e.jsx(jl,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only sm:not-sr-only sm:ml-1",children:"Prev"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[qe+1," of ",Ce.length]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>Ze&&t(ct(Ze)),disabled:!Ze,className:"px-2",children:[e.jsx("span",{className:"sr-only sm:not-sr-only sm:mr-1",children:"Next"}),e.jsx(Ia,{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(q,{variant:"outline",onClick:()=>ms(d.email,`${d.first_name} ${d.last_name||""}`.trim()),children:[e.jsx(Ks,{className:"h-4 w-4 mr-1"}),"Email"]}),d.email&&e.jsxs(q,{variant:"outline",onClick:()=>Ie(!0),className:"border-primary/40 text-primary hover:bg-primary/10",children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"}),"Send Connect Page"]}),e.jsxs(q,{variant:"default",onClick:()=>t(`/mission-control/video/record?contact_id=${s}`),className:"bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(bn,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(vs,{open:B,onOpenChange:K,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(ys,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Action Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:f==null?void 0:f.filter(ts=>ts.active).map(ts=>e.jsxs("button",{onClick:()=>Q(ts.id),className:` p-3 rounded-lg border text-left transition-all ${Z===ts.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:ts.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ts.description})]},ts.id))}),zs&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ce,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(Ne,{id:"custom-action-name",value:ue,onChange:ts=>me(ts.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Date (optional — backdate if needed)"}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("w-full justify-start text-left font-normal mt-2",!ne&&"text-muted-foreground"),children:[e.jsx(vn,{className:"h-4 w-4 mr-2"}),ne?As(ne,"PPP"):"Today (default)"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:ne,onSelect:ae,disabled:ts=>ts>new Date,initialFocus:!0,className:zt("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(pr,{id:"action-notes",value:W,onChange:ts=>te(ts.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(q,{onClick:sr,disabled:!Z||zs&&!ue.trim()||A.isPending,className:"w-full",children:[e.jsx(la,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(q,{variant:"outline",onClick:kt,children:[e.jsx(iu,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(q,{variant:"destructive",size:"icon",onClick:Yt,children:e.jsx(zr,{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||""]}),(((Ut=d.lead_source_ref)==null?void 0:Ut.name)||d.lead_source)&&e.jsx(Xe,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((ht=d.lead_source_ref)==null?void 0:ht.name)||d.lead_source})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-muted-foreground",children:[d.email&&e.jsxs("button",{onClick:()=>ms(d.email),className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Ks,{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(Mn,{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(hCe,{contact:d}),(Jt=d.tags)==null?void 0:Jt.map(ts=>{const Xs=m==null?void 0:m.find(js=>js.id===ts.relationship_type_id);return Xs?e.jsx(Xe,{variant:"secondary",className:"text-xs",children:Xs.name},ts.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx(Gzs,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(ke,{className:"md:col-span-2",children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Contact Information"})}),e.jsx(Pe,{children:D?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(ce,{htmlFor:"first_name",children:"First Name"}),e.jsx(Ne,{id:"first_name",value:F.first_name,onChange:ts=>O({...F,first_name:ts.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"last_name",children:"Last Name"}),e.jsx(Ne,{id:"last_name",value:F.last_name,onChange:ts=>O({...F,last_name:ts.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",value:F.email,onChange:ts=>O({...F,email:ts.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"phone",children:"Phone"}),e.jsx(Ne,{id:"phone",value:F.phone,onChange:ts=>O({...F,phone:ts.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"address",children:"Street Address"}),e.jsx(Ne,{id:"address",value:F.address,onChange:ts=>O({...F,address:ts.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(ce,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:F.city,onChange:ts=>O({...F,city:ts.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:F.state,onChange:ts=>O({...F,state:ts.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(Ne,{id:"zip_code",value:F.zip_code,onChange:ts=>O({...F,zip_code:ts.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(ce,{htmlFor:"birthday",children:"Birthday"}),e.jsx(Ne,{id:"birthday",type:"date",value:F.birthday,onChange:ts=>O({...F,birthday:ts.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(Ne,{id:"home_anniversary",type:"date",value:F.home_anniversary,onChange:ts=>O({...F,home_anniversary:ts.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(Ne,{id:"wedding_anniversary",type:"date",value:F.wedding_anniversary||"",onChange:ts=>O({...F,wedding_anniversary:ts.target.value})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(Ne,{id:"spouse_birthday",type:"date",value:F.spouse_birthday,onChange:ts=>O({...F,spouse_birthday:ts.target.value})})]})]}),e.jsx(cl,{}),e.jsx(mCe,{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:ts=>E.mutate({contactId:s,spouseContactId:ts}),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(ce,{htmlFor:"company_name",children:"Company"}),e.jsx(Ne,{id:"company_name",value:F.company_name,onChange:ts=>O({...F,company_name:ts.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"job_title",children:"Job Title"}),e.jsx(Ne,{id:"job_title",value:F.job_title,onChange:ts=>O({...F,job_title:ts.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(syt,{value:F.lead_source_id||"",onChange:ts=>O({...F,lead_source_id:ts})}),e.jsxs("div",{children:[e.jsx(ce,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:m==null?void 0:m.filter(ts=>ts.active).map(ts=>{var Xs;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Ri,{checked:(Xs=F.tagIds)==null?void 0:Xs.includes(ts.id),onCheckedChange:js=>{var $s;O(js?{...F,tagIds:[...F.tagIds||[],ts.id]}:{...F,tagIds:($s=F.tagIds)==null?void 0:$s.filter(Js=>Js!==ts.id)})}}),e.jsx("span",{className:"text-sm",children:ts.name})]},ts.id)})})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"notes",children:"Notes"}),e.jsx(pr,{id:"notes",value:F.notes,onChange:ts=>O({...F,notes:ts.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{onClick:St,disabled:N.isPending,children:"Save Changes"}),e.jsx(q,{variant:"outline",onClick:()=>R(!1),children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-4",children:[vt.length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",As(new Date(vt[0].completed_at),"MMM d, yyyy")," ","(",vt[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(Ks,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("button",{onClick:()=>ms(d.email),className:"text-primary hover:underline truncate text-left",children:d.email})]}),d.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{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(Ma,{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}`]})]})]}),nt&&d.address&&d.city&&d.state&&e.jsxs(q,{size:"sm",variant:"outline",onClick:Se,disabled:Qe,children:[Qe?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(__,{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(vn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",As(El(d.birthday),El(d.birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",As(El(d.home_anniversary),El(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(yi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Spouse Birthday: ",As(El(d.spouse_birthday),El(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(yi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Wedding Anniversary: ",As(El(d.wedding_anniversary),El(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(Ys,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",As(new Date(d.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(cl,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(mCe,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:d.spouse_name||null,currentSpouseEmail:d.spouse_email||null,onLink:ts=>E.mutate({contactId:s,spouseContactId:ts}),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(Ga,{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(cl,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(Ms=d.tags)!=null&&Ms.length?d.tags.map(ts=>{var Xs;return e.jsx(Xe,{variant:"secondary",children:(Xs=ts.relationship_type)==null?void 0:Xs.name},ts.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),d.notes&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{}),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(K9s,{contact:d,onLogTouch:()=>K(!0)}),e.jsx(SBs,{contactId:s}),e.jsx(mBs,{contactId:s}),e.jsx(fBs,{contactId:s}),e.jsx(xBs,{contactId:s,contactName:d.first_name}),e.jsx(gBs,{contactId:s,contactName:d.first_name}),e.jsx(NBs,{contactId:s}),e.jsx(bBs,{contactId:s}),e.jsx(wBs,{contactId:s}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Activity Log"})}),e.jsx(Pe,{children:vt.length>0?e.jsx("div",{className:"space-y-4",children:vt.map(ts=>{var Xs;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:ts.color},children:ts.type==="popby"?e.jsx(Di,{className:"h-4 w-4"}):(Xs=ts.name)==null?void 0:Xs.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:ts.name}),ts.videoId&&e.jsxs(q,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>fe(ts.videoId),children:[e.jsx(Al,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:As(new Date(ts.completed_at),"MMM d, yyyy h:mm a")}),ts.notes&&!ts.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:ts.notes})]})]},ts.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),_&&_.length>0&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ui,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-4",children:_.map(ts=>{var Xs,js;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(Xs=ts.video)!=null&&Xs.thumbnail_url?e.jsx("img",{src:ts.video.thumbnail_url,alt:ts.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>fe(ts.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:()=>fe(ts.video_id),children:e.jsx(bn,{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: ",((js=ts.video)==null?void 0:js.title)||"Untitled Video"]}),e.jsxs(q,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>fe(ts.video_id),children:[e.jsx(Al,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:As(new Date(ts.created_at),"MMM d, yyyy h:mm a")}),ts.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',ts.message,'"']})]})]},ts.id)})})})]}),Ge&&Ge.length>0&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(hn,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-3",children:Ge.map(ts=>e.jsxs(vs,{children:[e.jsx(Yi,{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(Ks,{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:ts.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",ts.to_email," · ",As(new Date(ts.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-sky-500"}),ts.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",ts.to_email," · ",As(new Date(ts.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:ts.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${ts.subject}`})})]})]},ts.id))})})]})]}),e.jsx(vs,{open:!!de,onOpenChange:ts=>!ts&&fe(null),children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Video Preview"})}),de&&e.jsx(jBs,{videoId:de})]})})]})]})}),$e&&d&&Ee&&e.jsx(uw,{open:je,onOpenChange:xe,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:Ee.email},gmailEmail:Ve}),d&&d.email&&e.jsx(Xzs,{open:Oe,onOpenChange:Ie,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:d.email}})]}):e.jsx(ws,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx(q,{onClick:()=>t("/mission-control/contacts"),children:"Back to Contacts"})]})})}function TBs({rangeDays:s}){const{user:t}=Cs(),r=is(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),{data:d=[],isLoading:u}=pt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let x=U.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const b=new Date(Date.now()-s*864e5).toISOString();x=x.gte("created_at",b)}const{data:y,error:_}=await x;if(_)throw _;return y||[]}}),{data:m}=pt({queryKey:["newsletter-campaign-recipients",n],enabled:!!n,queryFn:async()=>{const{data:x,error:y}=await U.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",n).order("sent_at",{ascending:!1}).limit(2e3);if(y)throw y;return x||[]}}),f=async()=>{if(!(!i||!t)){c(!0);try{const{data:x,error:y}=await U.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(y)throw y;if(!x||x.length===0){he.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:_}=await U.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:b,error:j}=await U.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:x.length,status:"draft"}).select("id").single();if(j)throw j;const N=x.map(A=>({campaign_id:b.id,contact_id:A.contact_id,email:A.email,name:A.name,status:"pending"}));for(let A=0;A{const y=x.sent_count||0,_=y>0?x.open_count/y*100:0,b=y>0?x.click_count/y*100:0,j=x.sent_at?lv(new Date,new Date(x.sent_at)):0,N=x.status==="sent"&&j>=3&&y>0&&x.open_counta(x.id),children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),N&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>l(x),children:[e.jsx(qE,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),x.status==="sent"&&y>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(wV,{icon:e.jsx(hn,{className:"h-3.5 w-3.5"}),label:"Sent",value:y,sub:`of ${x.total_recipients}`}),e.jsx(wV,{icon:e.jsx(Nn,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:x.open_count,sub:`${_.toFixed(1)}%`,children:e.jsx(ki,{value:_,className:"h-1 mt-1"})}),e.jsx(wV,{icon:e.jsx(Bc,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:x.click_count,sub:`${b.toFixed(1)}%`,children:e.jsx(ki,{value:b,className:"h-1 mt-1"})}),e.jsx(wV,{icon:e.jsx(eP,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:x.bounce_count,sub:x.bounce_count>0?"review":"none"})]})]},x.id)})})]})}),e.jsx(sw,{open:!!n,onOpenChange:x=>!x&&a(null),children:e.jsxs(U1,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(rw,{children:e.jsx(nw,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:m?m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:m.map(x=>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:x.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:x.email})]}),e.jsx("td",{className:"py-2 text-xs",children:x.opened_at?e.jsx(Xe,{variant:"default",className:"text-xs",children:As(new Date(x.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:x.clicked_at?e.jsx(Xe,{variant:"default",className:"text-xs bg-purple-600",children:As(new Date(x.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[x.status==="sent"&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"sent"}),x.status==="pending"&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"queued"}),x.status==="failed"&&e.jsx(Xe,{variant:"destructive",className:"text-xs",title:x.error_message||"",children:"failed"}),x.status==="suppressed"&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},x.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(el,{open:!!i,onOpenChange:x=>!x&&l(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Resend to non-openers?"}),e.jsxs(Ho,{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(qo,{children:[e.jsx(Go,{disabled:o,children:"Cancel"}),e.jsx(Oo,{onClick:f,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(qE,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function wV({icon:s,label:t,value:r,sub:n,children:a}){return e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsxs("div",{className:"flex items-baseline gap-1.5 mt-0.5",children:[e.jsx("span",{className:"text-lg font-bold",children:r.toLocaleString()}),n&&e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),a]})}function EBs(){const{user:s}=Cs(),t=qr(),r=is(),{data:n=[],isLoading:a}=pt({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const{data:{session:m}}=await U.auth.getSession(),x=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m.access_token}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!x.success)throw new Error(x.error||`Failed to ${d}`);return x},l=Mt({mutationFn:d=>i("cancel",d),onSuccess:()=>{he.success("Schedule cancelled — saved as draft"),r.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>he.error(d.message)}),o=Mt({mutationFn:d=>i("delete",d),onSuccess:()=>{he.success("Scheduled email deleted"),r.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>he.error(d.message)}),c=Mt({mutationFn:async({id:d,iso:u})=>{const{error:m}=await U.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(m)throw m;await i("schedule",d)},onSuccess:()=>{he.success("Send time updated"),r.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>he.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):n.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(jn,{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:n.map(d=>e.jsx(ABs,{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 ABs({campaign:s,onEdit:t,onCancel:r,onDelete:n,onReschedule:a,isBusy:i}){const l=s.scheduled_at?new Date(s.scheduled_at):null,[o,c]=k.useState(!1),[d,u]=k.useState(l||void 0),[m,f]=k.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),x=()=>{if(!d)return he.error("Pick a date");const y=new Date(`${As(d,"yyyy-MM-dd")}T${m}:00`).toISOString();if(new Date(y).getTime()yf(y.target.value)})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(q,{onClick:x,disabled:i,children:[i&&e.jsx(ls,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsxs(q,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(ad,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Cancel this scheduled send?"}),e.jsxs(Ho,{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(qo,{children:[e.jsx(Go,{children:"Keep scheduled"}),e.jsx(Oo,{onClick:r,children:"Cancel send"})]})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsxs(q,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete this scheduled email?"}),e.jsx(Ho,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Keep"}),e.jsx(Oo,{onClick:n,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}const mWe=["Gmail","Mass Email","Campaign","Client Portal Invite"],MBs={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 IBs(){const{user:s}=Cs(),[t,r]=ic(),{data:n=[],isLoading:a}=lyt(),[i,l]=k.useState(""),[o,c]=k.useState("all"),[d,u]=k.useState("30"),[m,f]=k.useState(!1),[x,y]=k.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:_}=Cm(),{data:b=0}=pt({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:E}=await U.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return E||0},refetchInterval:3e4});k.useEffect(()=>{const E=new URLSearchParams(t);x==="scheduled"?E.set("tab","scheduled"):E.delete("tab"),r(E,{replace:!0})},[x]);const j=k.useMemo(()=>Array.from(new Set(n.map(E=>E.contact_id).filter(Boolean))),[n]),{data:N}=pt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,j.length],enabled:j.length>0,queryFn:async()=>{const{data:E}=await U.from("innercircle_contacts").select("id, first_name, last_name").in("id",j),D=new Map;return(E||[]).forEach(R=>{D.set(R.id,[R.first_name,R.last_name].filter(Boolean).join(" ")||"Contact")}),D}}),C=k.useMemo(()=>{const E=d==="all"?null:Date.now()-parseInt(d)*864e5,D=i.trim().toLowerCase();return n.filter(R=>{if(o!=="all"&&R.channel!==o||E&&new Date(R.sent_at).getTime(){const E={};let D=0,R=0,F=0;return C.forEach(O=>{E[O.channel]=(E[O.channel]||0)+1,(O.channel==="Campaign"||O.channel==="Mass Email")&&(F++,O.opened_at&&D++,O.clicked_at&&R++)}),{byChannel:E,opened:D,clicked:R,trackable:F}},[C]);return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-start md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(hn,{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(q,{onClick:()=>f(!0),children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"})," Send Email"]})]}),e.jsxs(ta,{value:x,onValueChange:E=>y(E),className:"space-y-6",children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"sent",className:"gap-2",children:[e.jsx(hn,{className:"h-4 w-4"})," Sent"]}),e.jsxs(rs,{value:"scheduled",className:"gap-2",children:[e.jsx(jn,{className:"h-4 w-4"})," Scheduled",b>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1 h-5 min-w-5 px-1.5 text-xs",children:b})]})]}),e.jsxs(fs,{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(ke,{children:e.jsxs(Pe,{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:C.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:mWe.map(E=>A.byChannel[E]?`${A.byChannel[E]} ${E}`:null).filter(Boolean).join(" · ")||"—"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(qn,{className:"h-3 w-3"})," Delivered"]}),e.jsx("p",{className:"text-2xl font-bold",children:C.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"All sends completed"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(Nn,{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(ke,{children:e.jsxs(Pe,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(Bc,{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(a2,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search subject, recipient, contact...",value:i,onChange:E=>l(E.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:o,onValueChange:c,children:[e.jsx(Ps,{className:"w-[200px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Channels"}),mWe.map(E=>e.jsx(lt,{value:E,children:E},E))]})]}),e.jsxs(Ds,{value:d,onValueChange:u,children:[e.jsx(Ps,{className:"w-[160px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"7",children:"Last 7 days"}),e.jsx(lt,{value:"30",children:"Last 30 days"}),e.jsx(lt,{value:"90",children:"Last 90 days"}),e.jsx(lt,{value:"365",children:"Last year"}),e.jsx(lt,{value:"all",children:"All time"})]})]})]}),e.jsx(TBs,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):C.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ks,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sent emails match your filters."})]})}):e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-xs uppercase text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Channel"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Subject"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Recipient"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Contact"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:e.jsx(J_,{children:e.jsxs(Oc,{children:[e.jsxs(Fc,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(a2,{className:"h-3 w-3"})]}),e.jsx(Sc,{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:C.slice(0,500).map(E=>{const D=E.contact_id?N==null?void 0:N.get(E.contact_id):null,R=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:As(new Date(E.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Xe,{variant:"outline",className:MBs[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&&D?e.jsx(Vn,{to:`/mission-control/contacts/${E.contact_id}`,className:"text-primary hover:underline",children:D}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:R?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(Xe,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(qn,{className:"h-3 w-3"})," Delivered"]}),E.opened_at&&e.jsxs(Xe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"})," Opened"]}),E.clicked_at&&e.jsxs(Xe,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Bc,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},E.id)})})]}),C.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",C.length," — narrow your filters to see more."]})]})})})]}),e.jsx(fs,{value:"scheduled",className:"mt-0",children:e.jsx(EBs,{})})]}),e.jsx(uw,{open:m,onOpenChange:f,gmailEmail:_})]})})}const fWe={Crown:Gf,FileText:En,Users:Dr,Globe:Ql,Star:fa,Phone:Mn,MessageSquare:Ui,PenTool:oS,Video:bn,Gift:Di},jV=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function PBs(){var St,Yt;const s=qr(),{user:t}=Cs(),{data:r}=H0(),{data:n}=oQt(),{data:a}=fQt(),{data:i}=Ect(),{data:l}=TB(),{data:o}=iQt(),c=pQt(),d=lQt(),u=dQt(),m=uQt(),f=hQt(),x=mQt(),y=cQt(),[_,b]=k.useState(null),[j,N]=k.useState(!1),[C,A]=k.useState(null),[E,D]=k.useState(""),[R,F]=k.useState(""),[O,B]=k.useState([]),[K,Z]=k.useState(null),[Q,W]=k.useState(null),[te,ne]=k.useState(null),[ae,ue]=k.useState(!1),[me,de]=k.useState(""),[fe,je]=k.useState(""),[xe,Ee]=k.useState(""),[Me,Oe]=k.useState(""),Ie=(es,zs)=>a==null?void 0:a.some(sr=>sr.plan_id===es&&sr.relationship_type_id===zs&&sr.active),ze=es=>a==null?void 0:a.find(zs=>zs.relationship_type_id===es&&zs.active),Ve=async(es,zs)=>{const sr=Ie(es,zs);await c.mutateAsync({planId:es,relationshipTypeId:zs,active:!sr})},Le=(n==null?void 0:n.filter(es=>es.active&&!es.owner_user_id))||[],$e=(n==null?void 0:n.filter(es=>es.owner_user_id===(t==null?void 0:t.id)))||[],ve=r==null?void 0:r.find(es=>es.id===_),Qe=_?ze(_):null,we=n==null?void 0:n.find(es=>es.id===(Qe==null?void 0:Qe.plan_id)),nt=async()=>{if(!E.trim())return;const es=await d.mutateAsync({name:E,description:R});es&&O.length>0&&await f.mutateAsync({planId:es.id,items:O}),Ce()},Se=async()=>{!E.trim()||!C||(await u.mutateAsync({id:C,name:E,description:R}),await f.mutateAsync({planId:C,items:O}),Ce())},Ge=es=>{var zs;A(es.id),D(es.name),F(es.description||""),B(((zs=es.items)==null?void 0:zs.map(sr=>({month_number:sr.month_number,action_type_id:sr.action_type_id,default_script_id:sr.default_script_id||void 0,notes:sr.notes||void 0})))||[]),N(!0)},We=async(es,zs)=>{if(es.owner_user_id===(t==null?void 0:t.id)){Ge(es);return}try{const sr=await y.mutateAsync({sourcePlanId:es.id,newName:`${es.name} (My Copy)`});if(!sr)return;await c.mutateAsync({planId:es.id,relationshipTypeId:zs,active:!1}),await c.mutateAsync({planId:sr.id,relationshipTypeId:zs,active:!0}),A(sr.id),D(sr.name),F(sr.description||""),B((es.items||[]).map(ms=>({month_number:ms.month_number,action_type_id:ms.action_type_id,default_script_id:ms.default_script_id||void 0,notes:ms.notes||void 0}))),N(!0)}catch{}},Ce=()=>{N(!1),A(null),D(""),F(""),B([])},qe=(es,zs)=>{W(zs)},et=(es,zs,sr)=>{B(ms=>[...ms.filter(Ut=>Ut.month_number!==es),{month_number:es,action_type_id:zs,default_script_id:sr}]),Z(null),W(null)},Ze=es=>{B(zs=>zs.filter(sr=>sr.month_number!==es))},rt=async()=>{if(!me.trim()||!fe.trim()||!Q)return;const es=await x.mutateAsync({actionTypeId:Q,title:me,scriptBody:fe,emailSubject:xe||void 0,tone:Me||void 0});es&&K!==null&&et(K,Q,es.id),ue(!1),de(""),je(""),Ee(""),Oe("")},ct=Q?o==null?void 0:o.filter(es=>es.action_type_id===Q&&es.active):[],vt=es=>fWe[es||"Phone"]||Mn,kt=es=>fWe[es||"Users"]||Dr;return e.jsxs(ws,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(jl,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(q,{onClick:()=>N(!0),className:"w-full sm:w-auto",children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Custom Plan"]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Your Contact Groups"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a group to assign a touchpoint plan"}),r==null?void 0:r.filter(es=>es.active).map(es=>{const zs=kt(es.icon),sr=(i==null?void 0:i[es.id])||0,ms=ze(es.id),gt=n==null?void 0:n.find(ht=>ht.id===(ms==null?void 0:ms.plan_id)),Ut=_===es.id;return e.jsxs("button",{onClick:()=>b(es.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${Ut?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(zs,{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:es.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[sr," contacts"]})]}),gt?e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1"}),gt.name.split(" ")[0]]}):e.jsx(Xe,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},es.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:_&&ve?e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[(()=>{const es=kt(ve.icon);return e.jsx(es,{className:"h-5 w-5"})})(),ve.name," Touchpoint Plan"]}),e.jsxs(Ur,{children:["Choose a plan for your ",ve.name," contacts"]})]}),e.jsxs(Pe,{className:"space-y-6",children:[we&&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(Ti,{className:"h-4 w-4 text-green-500"}),"Currently using: ",we.name]}),we.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:we.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{variant:"outline",size:"sm",disabled:y.isPending||c.isPending,onClick:()=>We(we,_),children:[e.jsx(zy,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>Ve(we.id,_),children:"Disable"})]})]}),we.items&&we.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(vn,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:jV.map((es,zs)=>{var Ut,ht;const sr=((Ut=we.items)==null?void 0:Ut.filter(Jt=>Jt.month_number===zs+1))||[],ms=(ht=sr[0])==null?void 0:ht.action_type,gt=ms?vt(ms.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${sr.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:es}),gt&&e.jsx(gt,{className:"h-4 w-4 mx-auto mt-1",style:{color:(ms==null?void 0:ms.color)||"#3B82F6"}})]},zs)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:we?"Switch to a Different Plan":"Choose a Plan"}),Le.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"}),Le.map(es=>{var sr;const zs=(we==null?void 0:we.id)===es.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${zs?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:es.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((sr=es.items)==null?void 0:sr.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>ne(es.id),children:e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:y.isPending,onClick:()=>{const ms=`${es.name} (Copy)`;y.mutate({sourcePlanId:es.id,newName:ms})},children:e.jsx(si,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:zs?"outline":"default",disabled:zs||c.isPending,onClick:()=>Ve(es.id,_),children:zs?"Active":"Use This"})]})]},es.id)})]}),$e.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),$e.map(es=>{var sr;const zs=(we==null?void 0:we.id)===es.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${zs?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:es.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((sr=es.items)==null?void 0:sr.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>ne(es.id),children:e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>Ge(es),children:e.jsx(zy,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>m.mutate(es.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})}),e.jsx(q,{size:"sm",variant:zs?"outline":"default",disabled:zs||c.isPending,onClick:()=>Ve(es.id,_),children:zs?"Active":"Use This"})]})]},es.id)})]}),Le.length===0&&$e.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No plans available. Create a custom plan to get started."})]})]})]}):e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(vn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select a contact group to view and assign plans"})]})})})]}),e.jsx(ke,{className:"bg-muted/50",children:e.jsx(Pe,{className:"py-4",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"How it works:"})," When you assign a plan to a contact group, those contacts will appear in your daily suggested actions based on the plan's schedule."]})})})]}),e.jsx(vs,{open:j,onOpenChange:es=>{es?N(!0):Ce()},children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:C?"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(ce,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(Ne,{id:"plan-name",value:E,onChange:es=>D(es.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(pr,{id:"plan-description",value:R,onChange:es=>F(es.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(ce,{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:jV.map((es,zs)=>{const sr=zs+1,ms=O.find(ht=>ht.month_number===sr),gt=ms?l==null?void 0:l.find(ht=>ht.id===ms.action_type_id):null,Ut=gt?vt(gt.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>Z(K===sr?null:sr),className:` w-full p-3 rounded-lg border text-center transition-all ${ms?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${K===sr?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:es}),Ut?e.jsx(Ut,{className:"h-5 w-5 mx-auto mt-1",style:{color:(gt==null?void 0:gt.color)||"#3B82F6"}}):e.jsx(Ys,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),ms&&e.jsx("button",{type:"button",onClick:ht=>{ht.stopPropagation(),Ze(sr)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx($r,{className:"h-3 w-3"})})]},zs)})}),K!==null&&!Q&&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 ",jV[K-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(es=>es.active).map(es=>{const zs=vt(es.icon);return e.jsxs("button",{type:"button",onClick:()=>qe(K,es.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(zs,{className:"h-4 w-4",style:{color:es.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:es.name})]},es.id)})})]}),K!==null&&Q&&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(q,{variant:"ghost",size:"sm",onClick:()=>W(null),children:[e.jsx(jl,{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:()=>et(K,Q),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"})]})}),ct==null?void 0:ct.map(es=>e.jsx("button",{type:"button",onClick:()=>et(K,Q,es.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:es.title}),es.tone&&e.jsx(Xe,{variant:"secondary",className:"text-xs mt-1",children:es.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[es.script_body.substring(0,100),"..."]})]})},es.id)),e.jsxs("button",{type:"button",onClick:()=>ue(!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(Ys,{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"})]})]})]})]})]}),O.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[O.length," touchpoint",O.length!==1?"s":""," per year"]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:Ce,children:"Cancel"}),e.jsxs(q,{onClick:C?Se:nt,disabled:!E.trim()||d.isPending||u.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),C?"Save Changes":"Create Plan"]})]})]})}),e.jsx(vs,{open:ae,onOpenChange:ue,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"script-title",children:"Script Title"}),e.jsx(Ne,{id:"script-title",value:me,onChange:es=>de(es.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(Ds,{value:Me,onValueChange:Oe,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select tone..."})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"friendly",children:"Friendly"}),e.jsx(lt,{value:"professional",children:"Professional"}),e.jsx(lt,{value:"casual",children:"Casual"}),e.jsx(lt,{value:"formal",children:"Formal"})]})]})]}),((Yt=(St=l==null?void 0:l.find(es=>es.id===Q))==null?void 0:St.name)==null?void 0:Yt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(Ne,{id:"script-email-subject",value:xe,onChange:es=>Ee(es.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"script-body",children:"Script Content"}),e.jsx(pr,{id:"script-body",value:fe,onChange:es=>je(es.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(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>ue(!1),children:"Cancel"}),e.jsxs(q,{onClick:rt,disabled:!me.trim()||!fe.trim()||x.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(vs,{open:!!te,onOpenChange:es=>{es||ne(null)},children:e.jsx(ys,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const es=n==null?void 0:n.find(ms=>ms.id===te);if(!es)return null;const zs=es.owner_user_id===(t==null?void 0:t.id),sr=[...es.items||[]].sort((ms,gt)=>ms.month_number-gt.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[es.name,!zs&&e.jsx(Xe,{variant:"secondary",children:"Template"})]}),es.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:es.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[sr.length," touchpoint",sr.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(ms,gt)=>gt+1).map(ms=>{const gt=sr.find(Ms=>Ms.month_number===ms),Ut=gt?l==null?void 0:l.find(Ms=>Ms.id===gt.action_type_id):null,ht=gt!=null&>.default_script_id?o==null?void 0:o.find(Ms=>Ms.id===gt.default_script_id):null,Jt=Ut?vt(Ut.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${gt?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:jV[ms-1]}),gt&&Ut?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Jt&&e.jsx(Jt,{className:"h-4 w-4",style:{color:Ut.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:Ut.name}),ht&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:ht.title})]}),ht&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:ht.script_body}),gt.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:gt.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},ms)})})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>ne(null),children:"Close"}),zs?e.jsxs(q,{onClick:()=>{const ms=n==null?void 0:n.find(gt=>gt.id===te);ms&&(ne(null),Ge(ms))},children:[e.jsx(zy,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(q,{disabled:y.isPending,onClick:()=>{y.mutate({sourcePlanId:es.id,newName:`${es.name} (Copy)`}),ne(null)},children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const rje="https://cma.relevelup.com";function cyt({open:s,onOpenChange:t,cma:r}){var ne;const{user:n}=Cs(),{toast:a}=Ba(),[i,l]=k.useState([]),[o,c]=k.useState(null),[d,u]=k.useState(!1),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState(!1),[C,A]=k.useState(null),[E,D]=k.useState(!1),[R,F]=k.useState(!1),[O,B]=k.useState(null);k.useEffect(()=>{!s||!n||(async()=>{var Ee;const[ae,ue,me,de,fe]=await Promise.all([U.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n.id).not("email","is",null).order("first_name"),U.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",n.id).maybeSingle(),U.from("gmail_integrations").select("id, is_active").eq("user_id",n.id).maybeSingle(),U.from("ses_verified_emails").select("email, status").eq("user_id",n.id).eq("status","Success").limit(1),U.from("mass_email_settings").select("*").eq("user_id",n.id).maybeSingle()]),je=(ae.data||[]).filter(Me=>Me.email&&Me.email.includes("@"));l(je),A(ue.data||null),D(!!((Ee=me.data)!=null&&Ee.is_active)),F(!!(de.data&&de.data.length>0)),B(fe.data||null);const xe=r.contact_id?je.find(Me=>Me.id===r.contact_id):null;xe&&(c(xe),f(xe.email))})()},[s,n,r.contact_id]),k.useEffect(()=>{var de;if(!s)return;const ae=((de=r.subject)==null?void 0:de.address)||"your home",ue=((C==null?void 0:C.name)||"").split(" ")[0]||"your agent",me=(o==null?void 0:o.first_name)||"there";y(`Your home value report for ${ae}`),b(`Hi ${me}, I put together a fresh market analysis for ${ae}. 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, ${(C==null?void 0:C.name)||ue}`)},[s,o==null?void 0:o.id,C==null?void 0:C.name,(ne=r.subject)==null?void 0:ne.address]);const K=k.useMemo(()=>E?"Gmail (your inbox)":R?"Amazon SES":null,[E,R]),Z=!!(m.trim()&&x.trim()&&_.trim()&&K&&!j),Q=ae=>{c(ae),f(ae.email||""),u(!1)},W=ae=>{const ue=`${rje}/${r.share_token}?e=${ae}`,fe=_.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(Ee=>`

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

`).join(""),je=C!=null&&C.use_email_signature&&(C!=null&&C.email_signature)?`
${C.email_signature}
`:`
${C!=null&&C.name?`
${C.name}
`:""} ${C!=null&&C.brokerage_name?`
${C.brokerage_name}
`:""} ${C!=null&&C.phone?`
${C.phone}
`:""} ${C!=null&&C.email?``:""}
`,xe=``;return`
${fe} ${je}
Prepared with LevelUp · ReLevelUp Real Estate
${xe}
`},te=async()=>{if(!(!n||!Z)){N(!0);try{const{data:ae,error:ue}=await U.from("cma_email_sends").insert({cma_id:r.id,agent_id:n.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:m.trim(),subject:x.trim(),sent_via:E?"gmail":"ses"}).select("id").single();if(ue)throw ue;const me=W(ae.id);if(E){const{data:de,error:fe}=await U.functions.invoke("gmail-send",{body:{to:m.trim(),subject:x.trim(),body:me}});if(fe)throw fe;if(!(de!=null&&de.success))throw new Error((de==null?void 0:de.error)||"Gmail send failed")}else if(R){const de=(O==null?void 0:O.display_name)||(C==null?void 0:C.name)||"ReLevelUp",fe=`${de.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:je,error:xe}=await U.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:m.trim(),from_email:`${de} <${fe}>`,subject:x.trim(),body_html:me,reply_to:(O==null?void 0:O.reply_to_email)||(C==null?void 0:C.email)||void 0}});if(xe)throw xe;if(!(je!=null&&je.success))throw new Error((je==null?void 0:je.error)||"SES send failed")}o&&!r.contact_id&&await U.from("cmas").update({contact_id:o.id}).eq("id",r.id),a({title:"CMA sent",description:`Delivered to ${m.trim()}`}),t(!1)}catch(ae){console.error("Send CMA error:",ae),a({title:"Send failed",description:ae.message||"Could not send email",variant:"destructive"})}finally{N(!1)}}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"w-5 h-5"}),"Send CMA to contact"]})}),K?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:K})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Contact"}),e.jsxs(sl,{open:d,onOpenChange:u,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{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(xg,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Ko,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search contacts…"}),e.jsxs(kg,{children:[e.jsx(Sg,{children:"No contacts with email found."}),e.jsx(Cg,{children:i.map(ae=>e.jsxs(Sp,{value:`${ae.first_name} ${ae.last_name||""} ${ae.email}`,onSelect:()=>Q(ae),children:[e.jsx(la,{className:zt("w-4 h-4 mr-2",(o==null?void 0:o.id)===ae.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[ae.first_name," ",ae.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ae.email})]})]},ae.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"To email"}),e.jsx(Ne,{type:"email",value:m,onChange:ae=>f(ae.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Subject"}),e.jsx(Ne,{value:x,onChange:ae=>y(ae.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Message"}),e.jsx(pr,{rows:10,value:_,onChange:ae=>b(ae.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/",r.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(un,{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:`${rje}/${r.share_token}`,target:"_blank",rel:"noreferrer",children:`${rje}/${r.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(fn,{children:[e.jsx(q,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:te,disabled:!Z,children:[j?e.jsx(ls,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(hn,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function LBs({onCreated:s}){const[t,r]=k.useState(!1),[n,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),m=rBs(),f=ryt(),{toast:x}=Ba(),[y,_]=k.useState([]),b=async()=>{var C;_([]);try{const A=await m.mutateAsync({address:n,city:i,state:o,zip:d});_(A.matches||[]),(C=A.matches)!=null&&C.length||x({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(A){x({title:"Search failed",description:A.message,variant:"destructive"})}},j=async C=>{const A=await f.mutateAsync({subject:C});r(!1),s(A.id)},N=async()=>{if(!n||!i||!o){x({title:"Address, city, state required"});return}const C=await f.mutateAsync({subject:{address:n,city:i,state:o,zip:d}});r(!1),s(C.id)};return e.jsxs(vs,{open:t,onOpenChange:r,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsx(bs,{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(Ne,{className:"md:col-span-2",placeholder:"Street address",value:n,onChange:C=>a(C.target.value)}),e.jsx(Ne,{placeholder:"City",value:i,onChange:C=>l(C.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"ST",maxLength:2,value:o,onChange:C=>c(C.target.value.toUpperCase())}),e.jsx(Ne,{placeholder:"ZIP",value:d,onChange:C=>u(C.target.value)})]})]}),e.jsxs(q,{onClick:b,disabled:!n||m.isPending,className:"w-full",children:[m.isPending?e.jsx(ls,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(_n,{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((C,A)=>{var E;return e.jsxs("button",{onClick:()=>j(C),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:C.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[C.city,", ",C.state," ",C.zip," · ",C.bedrooms??"?"," bd / ",C.bathrooms??"?"," ba · ",((E=C.sqft)==null?void 0:E.toLocaleString())??"?"," sqft",C.mlsNumber?` · MLS# ${C.mlsNumber}`:""," · ",C.source_provider]})]},A)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs(q,{variant:"outline",onClick:N,disabled:f.isPending,className:"w-full",children:[e.jsx(Pn,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function DBs(){const{data:s,isLoading:t}=Qzs(),r=sBs(),n=qr(),{toast:a}=Ba(),[i,l]=k.useState(null);return e.jsx(ws,{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(En,{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(LBs,{onCreated:o=>n(`/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(ke,{className:"hover:shadow-md transition",children:e.jsxs(Pe,{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(Xe,{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(q,{variant:"outline",size:"sm",onClick:()=>n(`/mission-control/cma/${o.id}`),children:"Open"}),o.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>{const m=`https://cma.relevelup.com/${o.share_token}`;navigator.clipboard.writeText(m),a({title:"Share link copied"})},children:e.jsx(un,{className:"w-4 h-4"})}),e.jsxs(q,{variant:"secondary",size:"sm",onClick:()=>l(o),children:[e.jsx(Ks,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>{confirm("Delete this CMA?")&&r.mutate(o.id)},children:e.jsx(zr,{className:"w-4 h-4"})})]})]})},o.id)})}):e.jsx(ke,{children:e.jsx(Pe,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(cyt,{open:!!i,onOpenChange:o=>!o&&l(null),cma:i})]})})}function RBs(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 pWe(s,t,r){const a=r*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 OBs({subject:s,comps:t,radiusMiles:r,onMarkerClick:n}){const a=k.useRef(null),i=k.useRef(null),l=k.useRef([]),[o,c]=k.useState(null);k.useEffect(()=>{let u=!1;return(async()=>{const{data:m}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(m!=null&&m.value)&&c(m.value)})(),()=>{u=!0}},[]);const d=k.useMemo(()=>{const u=Number(s==null?void 0:s.latitude),m=Number(s==null?void 0:s.longitude);return!Number.isFinite(u)||!Number.isFinite(m)?null:{lat:u,lng:m}},[s==null?void 0:s.latitude,s==null?void 0:s.longitude]);return k.useEffect(()=>{if(!o||!a.current||i.current||!d)return;ol.accessToken=o;const u=new ol.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new ol.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:pWe(d.lat,d.lng,r)}),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]),k.useEffect(()=>{const u=i.current;if(!u||!d)return;const m=()=>{const f=u.getSource("radius");f&&f.setData(pWe(d.lat,d.lng,r))};u.isStyleLoaded()?m():u.once("load",m)},[r,d]),k.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(b=>b.remove()),l.current=[];const m=document.createElement("div");m.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; `,m.textContent="★";const f=new ol.Marker({element:m}).setLngLat([d.lng,d.lat]).setPopup(new ol.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(f);const x=new ol.LngLatBounds;x.extend([d.lng,d.lat]),t.forEach((b,j)=>{const N=Number(b.latitude),C=Number(b.longitude);if(!Number.isFinite(N)||!Number.isFinite(C))return;const A=RBs(b.status),E=document.createElement("div");E.style.cssText="width:22px;height:22px;";const D=document.createElement("div");D.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: ${b.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,D.onmouseenter=()=>{D.style.transform="scale(1.25)"},D.onmouseleave=()=>{D.style.transform="scale(1)"},n&&(D.onclick=()=>n(j)),E.appendChild(D);const R=b.soldPrice||b.price,F=new ol.Popup({offset:14}).setHTML(`
${b.address??""}
${b.status??""}`+(R?` · $${R.toLocaleString()}`:"")+"
"),O=new ol.Marker({element:E}).setLngLat([C,N]).setPopup(F).addTo(u);l.current.push(O),x.extend([C,N])});const _=r*1.60934/110.574;x.extend([d.lng,d.lat+_]),x.extend([d.lng,d.lat-_]);try{u.fitBounds(x,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,r,s.address,n]),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 Zx=null;function FBs(){if(Zx)return Zx;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return Zx={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},Zx;const r=t.getExtension("WEBGL_debug_renderer_info"),n=r?t.getParameter(r.UNMASKED_RENDERER_WEBGL):"Unknown",a=["swiftshader","llvmpipe","software","microsoft basic render"],i=(n||"").toLowerCase();if(a.some(c=>i.includes(c)))return Zx={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:n},Zx;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(Zx={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:n},Zx):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(Zx={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:n},Zx):(Zx={canRunVirtualBg:!0,renderer:n},Zx)}catch{return Zx={canRunVirtualBg:!0},Zx}}const zBs=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function BBs({value:s,onChange:t,isLoading:r=!1,disabled:n=!1,className:a}){const i=k.useRef(null),[l,o]=k.useState(!1),[c]=k.useState(()=>FBs()),d=!c.canRunVirtualBg,{data:u=[],refetch:m}=pt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:b}}=await U.auth.getUser();if(!b)return[];const{data:j,error:N}=await U.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return N?(console.error("Failed to load backgrounds:",N),[]):j||[]}}),f=u.map(b=>({type:"image",label:b.name,imageUrl:b.image_url,thumbnail:b.thumbnail_url||b.image_url})),x=[...zBs,...f],y=b=>b.type!==s.type?!1:b.type==="image"?b.imageUrl===s.imageUrl:!0,_=async b=>{var N;const j=(N=b.target.files)==null?void 0:N[0];if(j){if(!j.type.startsWith("image/")){he.error("Please select an image file");return}if(j.size>5*1024*1024){he.error("Image must be under 5MB");return}o(!0);try{const{data:{user:C}}=await U.auth.getUser();if(!C)throw new Error("Not authenticated");const A=j.name.split(".").pop()||"jpg",E=`${C.id}/${crypto.randomUUID()}.${A}`,{error:D}=await U.storage.from("video-backgrounds").upload(E,j,{contentType:j.type});if(D)throw D;const{data:R}=U.storage.from("video-backgrounds").getPublicUrl(E),F=R.publicUrl,{error:O}=await U.from("video_backgrounds").insert({name:j.name.replace(/\.[^.]+$/,""),image_url:F,thumbnail_url:F,category:"custom",is_stock:!1,user_id:C.id});if(O)throw O;await m(),t({type:"image",imageUrl:F,blurRadius:15}),he.success("Background uploaded!")}catch(C){console.error("Upload error:",C),he.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:zt("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(du,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:c.reason||"Virtual backgrounds may cause lag on this device"})]}),e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto py-2 px-1 scrollbar-none",children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap mr-1 font-medium",children:"Background:"}),r&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ls,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),x.map((b,j)=>{const N=y(b);return e.jsxs("button",{type:"button",disabled:n,onClick:()=>t({type:b.type,imageUrl:b.imageUrl,blurRadius:15}),className:zt("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",N?"border-primary bg-primary/10":"border-transparent bg-muted/50",n&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("div",{className:"w-12 h-8 rounded flex items-center justify-center overflow-hidden bg-muted",children:[b.type==="none"&&e.jsx(uF,{className:"h-4 w-4 text-muted-foreground"}),b.type==="blur"&&e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-primary/20 to-primary/40 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Blur"})}),b.type==="image"&&b.thumbnail&&e.jsx("img",{src:b.thumbnail,alt:b.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:b.label})]},`${b.type}-${b.imageUrl||j}`)}),e.jsxs("button",{type:"button",disabled:n||l,onClick:()=>{var b;return(b=i.current)==null?void 0:b.click()},className:zt("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 border-dashed p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30","border-muted-foreground/30 bg-muted/30",(n||l)&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:l?e.jsx(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Ys,{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:n,onClick:()=>t({...s,mirror:!s.mirror}),className:zt("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all ml-1","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",s.mirror?"border-primary bg-primary/10":"border-transparent bg-muted/50",n&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:e.jsx(kF,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var ZL=typeof self<"u"?self:{};function dyt(s,t){e:{for(var r=["CLOSURE_FLAGS"],n=ZL,a=0;a>6|192;else{if(t>=55296&&t<=57343){if(t<=56319&&a=56320&&i<=57343){t=1024*(t-55296)+i-56320+65536,n[r++]=t>>18|240,n[r++]=t>>12&63|128,n[r++]=t>>6&63|128,n[r++]=63&t|128;continue}a--}t=65533}n[r++]=t>>12|224,n[r++]=t>>6&63|128}n[r++]=63&t|128}}s=r===n.length?n:n.subarray(0,r)}return s}function hyt(s){ZL.setTimeout(()=>{throw s},0)}var fCe,VBs=dyt(610401301,!1),gWe=dyt(748402147,!0);function yWe(){var s=ZL.navigator;return s&&(s=s.userAgent)?s:""}const vWe=ZL.navigator;function jye(s){return jye[" "](s),s}fCe=vWe&&vWe.userAgentData||null,jye[" "]=function(){};const myt={};let HO=null;function HBs(s){const t=s.length;let r=3*t/4;r%3?r=Math.floor(r):"=.".indexOf(s[t-1])!=-1&&(r="=.".indexOf(s[t-2])!=-1?r-2:r-1);const n=new Uint8Array(r);let a=0;return function(i,l){function o(d){for(;c>4),m!=64&&(l(u<<4&240|m>>2),f!=64&&l(m<<6&192|f))}}(s,function(i){n[a++]=i}),a!==r?n.subarray(0,a):n}function fyt(){if(!HO){HO={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let r=0;r<5;r++){const n=s.concat(t[r].split(""));myt[r]=n;for(let a=0;a0)&&(yWe().indexOf("Trident")!=-1||yWe().indexOf("MSIE")!=-1))&&typeof btoa=="function";const bWe=/[-_.]/g,WBs={"-":"+",_:"/",".":"="};function KBs(s){return WBs[s]||""}function xyt(s){if(!pyt)return HBs(s);s=bWe.test(s)?s.replace(bWe,KBs):s,s=atob(s);const t=new Uint8Array(s.length);for(let r=0;r=t||(r[s]=n+1,yyt(s=Error(),"incident"),hyt(s))}}function aD(){return typeof BigInt=="function"}var iD=typeof Symbol=="function"&&typeof Symbol()=="symbol";function hw(s,t,r=!1){return typeof Symbol=="function"&&typeof Symbol()=="symbol"?r&&Symbol.for&&s?Symbol.for(s):s!=null?Symbol(s):Symbol():t}var XBs=hw("jas",void 0,!0),_We=hw(void 0,"0di"),fO=hw(void 0,"1oa"),D0=hw(void 0,Symbol()),QBs=hw(void 0,"0ub"),JBs=hw(void 0,"0ubs"),xCe=hw(void 0,"0ubsb"),e$s=hw(void 0,"0actk"),JL=hw("m_m","Pa",!0),wWe=hw();const vyt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},byt=Object.defineProperties,fi=iD?XBs:"Ga";var hM;const jWe=[];function s$(s,t){iD||fi in s||byt(s,vyt),s[fi]|=t}function Sm(s,t){iD||fi in s||byt(s,vyt),s[fi]=t}function r$(s){return s$(s,34),s}function Lz(s){return s$(s,8192),s}Sm(jWe,7),hM=Object.freeze(jWe);var e8={};function z0(s,t){return t===void 0?s.h!==$A&&!!(2&(0|s.v[fi])):!!(2&t)&&s.h!==$A}const $A={};function h6e(s,t){if(s!=null){if(typeof s=="string")s=s?new O_(s,XL):BA();else if(s.constructor!==O_)if(d6e(s))s=s.length?new O_(new Uint8Array(s),XL):BA();else{if(!t)throw Error();s=void 0}}return s}class NWe{constructor(t,r,n){this.g=t,this.h=r,this.l=n}next(){const t=this.g.next();return t.done||(t.value=this.h.call(this.l,t.value)),t}[Symbol.iterator](){return this}}var t$s=Object.freeze({});function _yt(s,t,r){const n=128&t?0:-1,a=s.length;var i;(i=!!a)&&(i=(i=s[a-1])!=null&&typeof i=="object"&&i.constructor===Object);const l=a+(i?-1:0);for(t=128&t?1:0;ttypeof s=="number"),kWe=Nye(s=>typeof s=="string"),r$s=Nye(s=>typeof s=="boolean"),kye=typeof ZL.BigInt=="function"&&typeof ZL.BigInt(0)=="bigint";function R0(s){var t=s;if(kWe(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(s$s(t)&&!Number.isSafeInteger(t))throw Error(String(t));return kye?BigInt(s):s=r$s(s)?s?"1":"0":kWe(s)?s.trim()||"0":String(s)}var gCe=Nye(s=>kye?s>=a$s&&s<=o$s:s[0]==="-"?SWe(s,n$s):SWe(s,i$s));const n$s=Number.MIN_SAFE_INTEGER.toString(),a$s=kye?BigInt(Number.MIN_SAFE_INTEGER):void 0,i$s=Number.MAX_SAFE_INTEGER.toString(),o$s=kye?BigInt(Number.MAX_SAFE_INTEGER):void 0;function SWe(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(n>>0;lu=t,Ih=(s-t)/4294967296>>>0}function t8(s){if(s<0){CWe(-s);const[t,r]=p6e(lu,Ih);lu=t>>>0,Ih=r>>>0}else CWe(s)}function m6e(s){const t=c$s||(c$s=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Ih=0,lu=t.getUint32(0,!0)}function jyt(s,t){const r=4294967296*t+(s>>>0);return Number.isSafeInteger(r)?r:Dz(s,t)}function d$s(s,t){return R0(aD()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):Dz(s,t))}function Nyt(s,t){return aD()?R0(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var r=""+(4294967296*t+s);else aD()?r=""+(BigInt(t)<>>24|t<<8))+6710656*(t=t>>16&65535),r+=8147497*t,t*=2,s>=1e7&&(r+=s/1e7>>>0,s%=1e7),r>=1e7&&(t+=r/1e7>>>0,r%=1e7),r=t+TWe(r)+TWe(s));return r}function TWe(s){return s=String(s),"0000000".slice(s.length)+s}function f6e(s,t){if(2147483648&t)if(aD())s=""+(BigInt(0|t)<>>0));else{const[r,n]=p6e(s,t);s="-"+Dz(r,n)}else s=Dz(s,t);return s}function Sye(s){if(s.length<16)t8(Number(s));else if(aD())s=BigInt(s),lu=Number(s&BigInt(4294967295))>>>0,Ih=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Ih=lu=0;const r=s.length;for(let n=t,a=(r-t)%6+t;a<=r;n=a,a+=6){const i=Number(s.slice(n,a));Ih*=1e6,lu=1e6*lu+i,lu>=4294967296&&(Ih+=Math.trunc(lu/4294967296),Ih>>>=0,lu>>>=0)}if(t){const[n,a]=p6e(lu,Ih);lu=n,Ih=a}}}function p6e(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function L1(s){return Array.prototype.slice.call(s)}const n$=typeof BigInt=="function"?BigInt.asIntN:void 0,u$s=typeof BigInt=="function"?BigInt.asUintN:void 0,UA=Number.isSafeInteger,Cye=Number.isFinite,s8=Math.trunc,h$s=R0(0);function GO(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 f_(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function Rz(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 kyt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const m$s=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function a$(s){switch(typeof s){case"bigint":return!0;case"number":return Cye(s);case"string":return m$s.test(s);default:return!1}}function lD(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return Cye(s)?0|s:void 0}function Syt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return Cye(s)?s>>>0:void 0}function Cyt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(Sye(s),f6e(lu,Ih))}function x6e(s){if(s=s8(s),!UA(s)){t8(s);var t=lu,r=Ih;(s=2147483648&r)&&(r=~r>>>0,(t=1+~t>>>0)==0&&(r=r+1>>>0)),s=typeof(t=jyt(t,r))=="number"?s?-t:t:s?"-"+t:t}return s}function Tyt(s){var t=s8(Number(s));return UA(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),Cyt(s))}function Eyt(s){var t=s8(Number(s));return UA(t)?R0(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),aD()?R0(n$(64,BigInt(s))):R0(Cyt(s)))}function Ayt(s){return UA(s)?s=R0(x6e(s)):(s=s8(s),UA(s)?s=String(s):(t8(s),s=f6e(lu,Ih)),s=R0(s)),s}function Dpe(s){const t=typeof s;return s==null?s:t==="bigint"?R0(n$(64,s)):a$(s)?t==="string"?Eyt(s):Ayt(s):void 0}function Myt(s){if(typeof s!="string")throw Error();return s}function i$(s){if(s!=null&&typeof s!="string")throw Error();return s}function Qf(s){return s==null||typeof s=="string"?s:void 0}function g6e(s,t,r,n){return s!=null&&s[JL]===e8?s:Array.isArray(s)?((n=(r=0|s[fi])|32&n|2&n)!==r&&Sm(s,n),new t(s)):(r?2&n?((s=t[_We])||(r$((s=new t).v),s=t[_We]=s),t=s):t=new t:t=void 0,t)}function f$s(s,t,r){if(t)e:{if(!a$(t=s))throw pCe("int64");switch(typeof t){case"string":t=Eyt(t);break e;case"bigint":t=R0(n$(64,t));break e;default:t=Ayt(t)}}else t=Dpe(s);return(s=t)==null?r?h$s:void 0:s}const p$s={};let x$s=function(){try{return jye(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class aje{constructor(){this.g=new Map}get(t){return this.g.get(t)}set(t,r){return this.g.set(t,r),this.size=this.g.size,this}delete(t){return t=this.g.delete(t),this.size=this.g.size,t}clear(){this.g.clear(),this.size=this.g.size}has(t){return this.g.has(t)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(t,r){return this.g.forEach(t,r)}[Symbol.iterator](){return this.entries()}}const g$s=x$s?(Object.setPrototypeOf(aje.prototype,Map.prototype),Object.defineProperties(aje.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),aje):class extends Map{constructor(){super()}};function EWe(s){return s}function ije(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var I2=class extends g$s{constructor(s,t,r=EWe,n=EWe){super(),this.J=0|s[fi],this.K=t,this.S=r,this.fa=this.K?y$s:n;for(let a=0;a{s.call(t,a.get(n),n,a)}):super.forEach(s,t)}set(s,t){return ije(this),(s=this.S(s,!0,!1))==null?this:t==null?(super.delete(s),this):super.set(s,this.fa(t,!0,!0,this.K,!1,this.J))}Ma(s){const t=this.S(s[0],!1,!0);s=s[1],s=this.K?s===void 0?null:s:this.fa(s,!1,!0,void 0,!1,this.J),super.set(t,s)}has(s){return super.has(this.S(s,!1,!1))}get(s){s=this.S(s,!1,!1);const t=super.get(s);if(t!==void 0){var r=this.K;return r?((r=this.fa(t,!1,!0,r,this.ra,this.J))!==t&&super.set(s,r),r):t}}[Symbol.iterator](){return this.entries()}};function y$s(s,t,r,n,a,i){return s=g6e(s,n,r,i),a&&(s=v6e(s)),s}function v$s(s){return[s,this.get(s)]}let b$s;function AWe(){return b$s||(b$s=new I2(r$([]),void 0,void 0,void 0,p$s))}function Tye(s){return D0?s[D0]:void 0}function Rpe(s,t){for(const r in s)!isNaN(r)&&t(s,+r,s[r])}I2.prototype.toJSON=void 0;var yCe=class{};const _$s={Ka:!0};function w$s(s,t){t<100||QL(JBs,1)}function Eye(s,t,r,n){const a=n!==void 0;n=!!n;var i,l=D0;!a&&iD&&l&&(i=s[l])&&Rpe(i,w$s),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),m=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-m+m)),t=void 0;for(var f=0;f=i){const y=f-m;(t??(t={}))[y]=x}else l[f]=x}if(c)for(let x in c){if((o=c[x])==null||(o=r(o,n))==null)continue;let y;f=+x,u&&!Number.isNaN(f)&&(y=f+m){y[b]=L1(j)}),y.da=x.da,y}(s)),l}function j$s(s){return s[0]=Oz(s[0]),s[1]=Oz(s[1]),s}function Oz(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return gCe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[fi];return s.length===0&&1&t?void 0:Eye(s,t,Oz)}if(s!=null&&s[JL]===e8)return Iyt(s);if(s instanceof O_){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(pyt){for(var r="",n=0,a=t.length-10240;n>2];i=r[(3&i)<<4|l>>4],l=r[(15&l)<<2|o>>6],o=r[63&o],n[u++]=c+i+l+o}switch(c=0,o=a,t.length-d){case 2:o=r[(15&(c=t[d+1]))<<2]||a;case 1:t=t[d],n[u]=r[t>>2]+r[(3&t)<<4|c>>4]+o+a}t=n.join("")}s=s.g=t}return s}return s instanceof I2?s=s.size!==0?s.V(j$s):void 0:void 0}return s}let N$s,k$s;function Iyt(s){return Eye(s=s.v,0|s[fi],Oz)}function nA(s,t){return Pyt(s,t[0],t[1])}function Pyt(s,t,r,n=0){if(s==null){var a=32;r?(s=[r],a|=128):s=[],t&&(a=-16760833&a|(1023&t)<<14)}else{if(!Array.isArray(s))throw Error("narr");if(a=0|s[fi],gWe&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(gWe)throw Error("carr");QL(e$s,5)}(),256&a)throw Error("farr");if(64&a)return(a|n)!==a&&Sm(s,a|n),s;if(r&&(a|=128,r!==s[0]))throw Error("mid");e:{a|=64;var i=(r=s).length;if(i){var l=i-1;const c=r[l];if(c!=null&&typeof c=="object"&&c.constructor===Object){if((l-=t=128&a?0:-1)>=1024)throw Error("pvtlmt");for(var o in c)(i=+o)1024)throw Error("spvt");a=-16760833&a|(1023&o)<<14}}}return Sm(s,64|a|n),s}function S$s(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var r=0|s[fi];return s.length===0&&1&r?void 0:MWe(s,r,t)}if(s!=null&&s[JL]===e8)return IWe(s);if(s instanceof I2){if(2&(t=s.J))return s;if(!s.size)return;if(r=r$(s.V()),s.K)for(s=0;s=i)if(l=s[i],l!=null&&typeof l=="object"&&l.constructor===Object)r=l[t],o=!0;else{if(a!==i)return;r=l}else r=s[a];if(n&&r!=null){if((n=n(r))==null)return n;if(!Object.is(n,r))return o?l[t]=n:s[a]=n,n}return r}}function Cc(s,t,r,n){uD(s),Nm(s=s.v,0|s[fi],t,r,n)}function Nm(s,t,r,n,a){const i=r+(a?0:-1);var l=s.length-1;if(l>=1+(a?0:-1)&&i>=l){const o=s[l];if(o!=null&&typeof o=="object"&&o.constructor===Object)return o[r]=n,t}return i<=l?(s[i]=n,t):(n!==void 0&&(r>=(l=(t??(t=0|s[fi]))>>14&1023||536870912)?n!=null&&(s[l+(a?0:-1)]={[r]:n}):s[i]=n),t)}function lE(){return t$s===void 0?2:4}function cE(s,t,r,n,a){let i=s.v,l=0|i[fi];n=z0(s,l)?1:n,a=!!a||n===3,n===2&&dD(s)&&(i=s.v,l=0|i[fi]);let o=(s=_6e(i,t))===hM?7:0|s[fi],c=w6e(o,l);var d=!(4&c);if(d){4&c&&(s=L1(s),o=0,c=iA(c,l),l=Nm(i,l,t,s));let u=0,m=0;for(;u{const o=g6e(l,r,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!z0(n)&&mM(s,t),n}function $l(s,t,r,n){let a=s.v,i=0|a[fi];if((t=zyt(a,i,t,r,n))==null)return t;if(i=0|a[fi],!z0(s,i)){const l=v6e(t);l!==t&&(dD(s)&&(a=s.v,i=0|a[fi]),i=Nm(a,i,r,t=l,n),mM(a,i))}return t}function Byt(s,t,r,n,a,i,l,o){var c=z0(s,r);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&dD(s)&&(r=0|(t=s.v)[fi]);var d=(s=_6e(t,a))===hM?7:0|s[fi],u=w6e(d,r);if(o=!(4&u)){var m=s,f=r;const x=!!(2&u);x&&(f|=2);let y=!x,_=!0,b=0,j=0;for(;b32)for(a|=(127&r)>>4,i=3;i<32&&128&r;i+=7)r=l[o++],a|=(127&r)<>>0,a>>>0);throw Error()}function E6e(s){let t=0,r=s.g;const n=r+10,a=s.h;for(;r>>0}function Fpe(s){var t=s.h;const r=s.g;var n=t[r],a=t[r+1];const i=t[r+2];return t=t[r+3],oA(s,s.g+4),s=2*((a=(n<<0|a<<8|i<<16|t<<24)>>>0)>>31)+1,n=a>>>23&255,a&=8388607,n==255?a?NaN:s*(1/0):n==0?1401298464324817e-60*s*a:s*Math.pow(2,n-150)*(a+8388608)}function C$s(s){return BS(s)}function oA(s,t){if(s.g=t,t>s.l)throw Error()}function Uyt(s,t){if(t<0)throw Error();const r=s.g;if((t=r+t)>s.l)throw Error();return s.g=t,r}function qyt(s,t){if(t==0)return BA();var r=Uyt(s,t);return s.Y&&s.j?r=s.h.subarray(r,r+t):(s=s.h,r=r===(t=r+t)?new Uint8Array(0):l$s?s.slice(r,t):new Uint8Array(s.subarray(r,t))),r.length==0?BA():new O_(r,XL)}var PWe=[];function Vyt(s,t,r,n){if(zpe.length){const a=zpe.pop();return a.o(n),a.g.init(s,t,r,n),a}return new T$s(s,t,r,n)}function Hyt(s){s.g.clear(),s.l=-1,s.h=-1,zpe.length<100&&zpe.push(s)}function Gyt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var r=K_(s.g);if(t=r>>>3,!((r&=7)>=0&&r<=5)||t<1)throw Error();return s.l=t,s.h=r,!0}function che(s){switch(s.h){case 0:s.h!=0?che(s):E6e(s.g);break;case 1:oA(s=s.g,s.g+8);break;case 2:if(s.h!=2)che(s);else{var t=K_(s.g);oA(s=s.g,s.g+t)}break;case 5:oA(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!Gyt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}che(s)}break;default:throw Error()}}function o$(s,t,r){const n=s.g.l;var a=K_(s.g);let i=(a=s.g.g+a)-n;if(i<=0&&(s.g.l=a,r(t,s,void 0,void 0,void 0),i=a-s.g.g),i)throw Error();return s.g.g=a,s.g.l=n,t}function A6e(s){var t=K_(s.g),r=Uyt(s=s.g,t);if(s=s.h,$Bs){var n,a=s;(n=nje)||(n=nje=new TextDecoder("utf-8",{fatal:!0})),t=r+t,a=r===0&&t===a.length?a:a.subarray(r,t);try{var i=n.decode(a)}catch(o){if(NV===void 0){try{n.decode(new Uint8Array([128]))}catch{}try{n.decode(new Uint8Array([97])),NV=!0}catch{NV=!1}}throw!NV&&(nje=void 0),o}}else{t=(i=r)+t,r=[];let o,c=null;for(;i=t?vC():(o=s[i++],l<194||(192&o)!=128?(i--,vC()):r.push((31&l)<<6|63&o)):l<240?i>=t-1?vC():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(n=s[i++]))!=128?(i--,vC()):r.push((15&l)<<12|(63&o)<<6|63&n)):l<=244?i>=t-2?vC():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(n=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,vC()):(l=(7&l)<<18|(63&o)<<12|(63&n)<<6|63&a,l-=65536,r.push(55296+(l>>10&1023),56320+(1023&l)))):vC(),r.length>=8192&&(c=xWe(c,r),r.length=0)}i=xWe(c,r)}return i}function Wyt(s){const t=K_(s.g);return qyt(s.g,t)}function Mye(s,t,r){var n=K_(s.g);for(n=s.g.g+n;s.g.g>>0,this.g=t>>>0}};let E$s;function DWe(s){return s?/^-?\d+$/.test(s)?(Sye(s),new bCe(lu,Ih)):null:A$s||(A$s=new bCe(0,0))}var bCe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let A$s;function PP(s,t,r){for(;r>0||t>127;)s.g.push(127&t|128),t=(t>>>7|r<<25)>>>0,r>>>=7;s.g.push(t)}function mD(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function Iye(s,t){if(t>=0)mD(s,t);else{for(let r=0;r<9;r++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function M6e(s){var t=lu;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 r8(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function xv(s,t,r){mD(s.g,8*t+r)}function I6e(s,t){return xv(s,t,2),t=s.g.end(),r8(s,t),t.push(s.h),t}function P6e(s,t){var r=t.pop();for(r=s.h+s.g.length()-r;r>127;)t.push(127&r|128),r>>>=7,s.h++;t.push(r),s.h++}function Pye(s,t,r){xv(s,t,2),mD(s.g,r.length),r8(s,s.g.end()),r8(s,r)}function Bpe(s,t,r,n){r!=null&&(t=I6e(s,t),n(r,s),P6e(s,t))}function mw(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var L6e=mw(),Kyt=mw(),D6e=mw(),R6e=mw(),O6e=mw(),Yyt=mw(),M$s=mw(),Lye=mw(),Zyt=mw(),Xyt=mw();function fw(s,t,r){var n=s.v;D0&&D0 in n&&(n=n[D0])&&delete n[t.g],t.h?t.j(s,t.h,t.g,r,t.l):t.j(s,t.g,r,t.l)}var pi=class{constructor(s,t){this.v=Pyt(s,t,void 0,2048)}toJSON(){return Iyt(this)}j(){var a;var s=hUs,t=this.v,r=s.g,n=D0;if(iD&&n&&((a=t[n])==null?void 0:a[r])!=null&&QL(QBs,3),t=s.g,wWe&&D0&&wWe===void 0&&(n=(r=this.v)[D0])&&(n=n.da))try{n(r,t,_$s)}catch(i){hyt(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[fi];return b6e(this,s,t)?y6e(this,s,!0):new this.constructor(cD(s,t,!1))}};pi.prototype[JL]=e8,pi.prototype.toString=function(){return this.v.toString()};var fD=class{constructor(s,t,r){this.g=s,this.h=t,s=L6e,this.l=!!s&&r===s||!1}};function Dye(s,t){return new fD(s,t,L6e)}function Qyt(s,t,r,n,a){Bpe(s,r,svt(t,n),a)}const I$s=Dye(function(s,t,r,n,a){return s.h===2&&(o$(s,k6e(t,n,r),a),!0)},Qyt),P$s=Dye(function(s,t,r,n,a){return s.h===2&&(o$(s,k6e(t,n,r),a),!0)},Qyt);var Rye=Symbol(),Oye=Symbol(),_Ce=Symbol(),RWe=Symbol(),OWe=Symbol();let Jyt,evt;function fM(s,t,r,n){var a=n[s];if(a)return a;(a={}).qa=n,a.T=function(m){switch(typeof m){case"boolean":return N$s||(N$s=[0,void 0,!0]);case"number":return m>0?void 0:m===0?k$s||(k$s=[0,void 0]):[-m,void 0];case"string":return[0,m];case"object":return m}}(n[0]);var i=n[1];let l=1;i&&i.constructor===Object&&(a.ba=i,typeof(i=n[++l])=="function"&&(a.ma=!0,Jyt??(Jyt=i),evt??(evt=n[l+1]),i=n[l+=2]));const o={};for(;i&&Array.isArray(i)&&i.length&&typeof i[0]=="number"&&i[0]>0;){for(var c=0;ca(i,l,o,n):a}function z6e(s,t,r,n,a){const i=r.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=fM(Oye,F6e,z6e,n).T),l||(l=B6e(n)),a)}function B6e(s){let t=s[_Ce];if(t!=null)return t;const r=fM(Oye,F6e,z6e,s);return t=r.ma?(n,a)=>Jyt(n,a,r):(n,a)=>{for(;Gyt(a)&&a.h!=4;){var i=a.l,l=r[i];if(l==null){var o=r.ba;o&&(o=o[i])&&(o=D$s(o))!=null&&(l=r[i]=o)}if(l==null||!l(a,n,i)){if(l=(o=a).m,che(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=qyt(o.g,c);l=void 0,o=n,c&&((l=o[D0]??(o[D0]=new yCe))[i]??(l[i]=[])).push(c)}}return(n=Tye(n))&&(n.da=r.qa[OWe]),!0},s[_Ce]=t,s[OWe]=L$s.bind(s),t}function L$s(s,t,r,n){var a=this[Oye];const i=this[_Ce],l=nA(void 0,a.T),o=Tye(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,m,f)=>{if(f.length!==0)if(d[m])for(const x of f){u=Vyt(x);try{c=!0,i(l,u)}finally{Hyt(u)}}else n==null||n(s,m,f)},t==null)Rpe(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[fi];if(2&u&&2048&u&&!(r!=null&&r.Ka))throw Error();const m=oD(u),f=(x,y)=>{if(P2(s,x,m)!=null){if((r==null?void 0:r.Qa)===1)return;throw Error()}y!=null&&(u=Nm(s,u,x,y,m)),delete o[x]};t==null?_yt(l,0|l[fi],(x,y)=>{f(x,y)}):f(t,P2(l,t,m))}}}}function D$s(s){const t=(s=tvt(s))[0].g;if(s=s[1]){const r=B6e(s),n=fM(Oye,F6e,z6e,s).T;return(a,i,l)=>t(a,i,l,n,r)}return t}function Fye(s,t,r){s[t]=r.h}function zye(s,t,r,n){let a,i;const l=r.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=fM(Rye,Fye,zye,n).T),a||(a=rvt(n)))}function rvt(s){let t=s[RWe];if(!t){const r=fM(Rye,Fye,zye,s);t=(n,a)=>nvt(n,a,r),s[RWe]=t}return t}function nvt(s,t,r){_yt(s,0|s[fi],(n,a)=>{if(a!=null){var i=function(l,o){var c=l[o];if(c)return c;if((c=l.ba)&&(c=c[o])){var d=(c=tvt(c))[0].h;if(c=c[1]){const u=rvt(c),m=fM(Rye,Fye,zye,c).T;c=l.ma?evt(m,u):(f,x,y)=>d(f,x,y,m,u)}else c=d;return l[o]=c}}(r,n);i?i(t,a,n):n<500||QL(xCe,3)}}),(s=Tye(s))&&Rpe(s,(n,a,i)=>{for(r8(t,t.g.end()),n=0;n{Bpe(s,r,nA([l,i],n),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),PP(s.g,r.h,r.g);break;default:r=DWe(t),PP(s.g,r.h,r.g)}}function ovt(s,t,r){(t=lD(t))!=null&&t!=null&&(xv(s,r,0),Iye(s.g,t))}function lvt(s,t,r){(t=kyt(t))!=null&&(xv(s,r,0),s.g.g.push(t?1:0))}function cvt(s,t,r){(t=Qf(t))!=null&&Pye(s,r,uyt(t))}function dvt(s,t,r,n,a){Bpe(s,r,svt(t,n),a)}function uvt(s,t,r){(t=t==null||typeof t=="string"||t instanceof O_?t:void 0)!=null&&Pye(s,r,C6e(t,!0).buffer)}function hvt(s,t,r){(t=Syt(t))!=null&&t!=null&&(xv(s,r,0),mD(s.g,t))}function mvt(s,t,r){return(s.h===5||s.h===2)&&(t=hD(t,0|t[fi],r),s.h==2?Mye(s,Fpe,t):t.push(Fpe(s.g)),!0)}var Dh=Fp(function(s,t,r){return s.h===5&&(zp(t,r,Fpe(s.g)),!0)},avt,Lye),F$s=xD(mvt,function(s,t,r){if((t=pD(f_,t))!=null)for(let l=0;l=0?n=String(a):((a=n.indexOf("."))!==-1&&(n=n.substring(0,a)),(a=n[0]!=="-"&&((a=n.length)<20||a===20&&n<="18446744073709551615"))||(Sye(n),n=Dz(lu,Ih))),n;if(a==="number")return(n=s8(n))>=0&&UA(n)||(t8(n),n=jyt(lu,Ih)),n}}(t),t!=null&&(typeof t=="string"&&LWe(t),t!=null))switch(xv(s,r,0),typeof t){case"number":s=s.g,t8(t),PP(s,lu,Ih);break;case"bigint":r=BigInt.asUintN(64,t),r=new vCe(Number(r&BigInt(4294967295)),Number(r>>BigInt(32))),PP(s.g,r.h,r.g);break;default:r=LWe(t),PP(s.g,r.h,r.g)}},M$s),pm=Fp(function(s,t,r){return s.h===0&&(zp(t,r,BS(s.g)),!0)},ovt,R6e),l$=xD(function(s,t,r){return(s.h===0||s.h===2)&&(t=hD(t,0|t[fi],r),s.h==2?Mye(s,BS,t):t.push(BS(s.g)),!0)},function(s,t,r){if((t=pD(lD,t))!=null&&t.length){r=I6e(s,r);for(let n=0;n{{const i={ea:!0};n&&Object.assign(i,n),r=Vyt(r,void 0,void 0,i);try{const l=new s,o=l.v;B6e(t)(o,r);var a=l}finally{Hyt(r)}}return a}}function Bye(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}}}};nvt(this.v,t,fM(Rye,Fye,zye,s)),r8(t,t.g.end());const r=new Uint8Array(t.h),n=t.l,a=n.length;let i=0;for(let l=0;la;r=BWe.createPolicy("goog#html",{createHTML:n,createScript:n,createScriptURL:n})}catch{}return r}()),s=(t=cje)?t.createScriptURL(s):s,new class{constructor(r){this.g=r}toString(){return this.g+""}}(s)}function kV(s,...t){if(t.length===0)return $We(s[0]);let r=s[0];for(let n=0;n({index:Ky(n,1)??0??-1,score:ah(n,2)??0,categoryName:Qf(mu(n,3))??""??"",displayName:Qf(mu(n,4))??""??""})),headIndex:t,headName:r}}function xUs(s){const t={classifications:L2(s,X$s,1).map(r=>{var n;return Y6e(((n=$l(r,wvt,4))==null?void 0:n.g())??[],Ky(r,2)??0,Qf(mu(r,3))??"")})};return function(r){return r==null?r:typeof r=="bigint"?(gCe(r)?r=Number(r):(r=n$(64,r),r=gCe(r)?Number(r):String(r)),r):a$(r)?typeof r=="number"?x6e(r):Tyt(r):void 0}(mu(s,2,void 0,void 0,Dpe))!=null&&(t.timestampMs=Yvt(mu(s,2,void 0,void 0,Dpe)??Lyt)),t}function Zvt(s){var l,o;var t=cE(s,3,f_,lE()),r=cE(s,2,lD,lE()),n=cE(s,1,Qf,lE()),a=cE(s,9,Qf,lE());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function JWe(s,t){if(s.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${s.length} vs. ${t.length}).`);let r=0,n=0,a=0;for(let i=0;i=1&&Number(s[1])>=17))}async function eKe(s){if(typeof importScripts!="function"){const t=document.createElement("script");return t.src=s.toString(),t.crossOrigin="anonymous",new Promise((r,n)=>{t.addEventListener("load",()=>{r()},!1),t.addEventListener("error",a=>{n(a)},!1),document.body.appendChild(t)})}try{importScripts(s.toString())}catch(t){if(!(t instanceof TypeError))throw t;await self.import(s.toString())}}function Jvt(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 gi(s,t,r){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),r(t=s.i.stringToNewUTF8(t)),s.i._free(t)}function tKe(s,t,r){if(!s.i.canvas)throw Error("No OpenGL canvas configured.");if(r?s.i._bindTextureToStream(r):s.i._bindTextureToCanvas(),!(r=s.i.canvas.getContext("webgl2")||s.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");s.i.gpuOriginForWebTexturesIsBottomLeft&&r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!0),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t),s.i.gpuOriginForWebTexturesIsBottomLeft&&r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1);const[n,a]=Jvt(t);return!s.l||n===s.i.canvas.width&&a===s.i.canvas.height||(s.i.canvas.width=n,s.i.canvas.height=a),[n,a]}function sKe(s,t,r){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const n=new Uint32Array(t.length);for(let a=0;a>2),r(t);for(const a of n)s.i._free(a);s.i._free(t)}function Rb(s,t,r){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=r}function $N(s,t,r){let n=[];s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=(a,i,l)=>{i?(r(n,l),n=[]):n.push(a)}}nI.forVisionTasks=function(s,t=!1){return CV("vision",s??kV``,t)},nI.forTextTasks=function(s,t=!1){return CV("text",s??kV``,t)},nI.forGenAiTasks=function(s,t=!1){return CV("genai",s??kV``,t)},nI.forAudioTasks=function(s,t=!1){return CV("audio",s??kV``,t)},nI.isSimdSupported=function(s=!1){return Xvt(s)};async function yUs(s,t,r,n){return s=await(async(a,i,l,o,c)=>{if(i&&await eKe(i),!self.ModuleFactory||l&&(await eKe(l),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((i=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(i.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new a(c,o)})(s,r.wasmLoaderPath,r.assetLoaderPath,t,{locateFile:a=>a.endsWith(".wasm")?r.wasmBinaryPath.toString():r.assetBinaryPath&&a.endsWith(".data")?r.assetBinaryPath.toString():a}),await s.o(n),s}function hje(s,t){const r=$l(s.baseOptions,$pe,1)||new $pe;typeof t=="string"?(Cc(r,2,i$(t)),Cc(r,1)):t instanceof Uint8Array&&(Cc(r,1,h6e(t,!1)),Cc(r,2)),$i(s.baseOptions,0,1,r)}function rKe(s){try{const t=s.H.length;if(t===1)throw Error(s.H[0].message);if(t>1)throw Error("Encountered multiple errors: "+s.H.map(r=>r.message).join(", "))}finally{s.H=[]}}function oi(s,t){s.C=Math.max(s.C,t)}function Vye(s,t){s.B=new Ig,B0(s.B,2,"PassThroughCalculator"),Kd(s.B,"free_memory"),Tl(s.B,"free_memory_unused_out"),yu(t,"free_memory"),gv(t,s.B)}function n8(s,t){Kd(s.B,t),Tl(s.B,t+"_unused_out")}function Hye(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var SCe=class{constructor(s){this.g=s,this.H=[],this.C=0,this.g.setAutoRenderToScreen(!1)}l(s,t=!0){var r,n,a,i,l,o;if(t){const c=s.baseOptions||{};if((r=s.baseOptions)!=null&&r.modelAssetBuffer&&((n=s.baseOptions)!=null&&n.modelAssetPath))throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!((a=$l(this.baseOptions,$pe,1))!=null&&a.g()||(i=$l(this.baseOptions,$pe,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 m=$l(d.baseOptions,KWe,3);if(!m){var f=m=new KWe,x=new UWe;W7(f,4,dhe,x)}"delegate"in u&&(u.delegate==="GPU"?(u=m,f=new V$s,W7(u,2,dhe,f)):(u=m,f=new UWe,W7(u,4,dhe,f))),$i(d.baseOptions,0,3,m)}(this,c),c.modelAssetPath)return fetch(c.modelAssetPath.toString()).then(d=>{if(d.ok)return d.arrayBuffer();throw Error(`Failed to fetch model: ${c.modelAssetPath} (${d.status})`)}).then(d=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(d),!0,!1,!1),hje(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)hje(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var m=0;;){const{done:f,value:x}=await d.read();if(f)break;u.push(x),m+=x.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(m),m=0;for(const f of u)d.set(f,m),m+=f.length;return d}(c.modelAssetBuffer).then(d=>{hje(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=H$s(t)}),!s)throw Error("Failed to retrieve CalculatorGraphConfig");return s}setGraph(s,t){this.g.attachErrorListener((r,n)=>{this.H.push(Error(n))}),this.g.Ja(),this.g.setGraph(s,t),this.B=void 0,rKe(this)}finishProcessing(){this.g.finishProcessing(),rKe(this)}close(){this.B=void 0,this.g.closeGraph()}};function kS(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}SCe.prototype.close=SCe.prototype.close;class vUs{constructor(t,r,n,a){this.g=t,this.h=r,this.m=n,this.l=a}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function nKe(s,t,r){const n=s.g;if(r=kS(n.createShader(r),"Failed to create WebGL shader"),n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,n.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${n.getShaderInfoLog(r)}`);return n.attachShader(s.h,r),r}function aKe(s,t){const r=s.g,n=kS(r.createVertexArray(),"Failed to create vertex array");r.bindVertexArray(n);const a=kS(r.createBuffer(),"Failed to create buffer");r.bindBuffer(r.ARRAY_BUFFER,a),r.enableVertexAttribArray(s.O),r.vertexAttribPointer(s.O,2,r.FLOAT,!1,0,0),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),r.STATIC_DRAW);const i=kS(r.createBuffer(),"Failed to create buffer");return r.bindBuffer(r.ARRAY_BUFFER,i),r.enableVertexAttribArray(s.L),r.vertexAttribPointer(s.L,2,r.FLOAT,!1,0,0),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),r.STATIC_DRAW),r.bindBuffer(r.ARRAY_BUFFER,null),r.bindVertexArray(null),new vUs(r,n,a,i)}function Z6e(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function bUs(s,t,r,n){return Z6e(s,t),s.h||(s.m(),s.D()),r?(s.u||(s.u=aKe(s,!0)),r=s.u):(s.A||(s.A=aKe(s,!1)),r=s.A),t.useProgram(s.h),r.bind(),s.l(),s=n(),r.g.bindVertexArray(null),s}function e1t(s,t,r){return Z6e(s,t),s=kS(t.createTexture(),"Failed to create texture"),t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r??t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r??t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),s}function t1t(s,t,r){Z6e(s,t),s.B||(s.B=kS(t.createFramebuffer(),"Failed to create framebuffe.")),t.bindFramebuffer(t.FRAMEBUFFER,s.B),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0)}function _Us(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var s1t=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=kS(s.createProgram(),"Failed to create WebGL program"),this.X=nKe(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=nKe(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 qj(s,t){switch(t){case 0:return s.g.find(r=>r instanceof Uint8Array);case 1:return s.g.find(r=>r instanceof Float32Array);case 2:return s.g.find(r=>typeof WebGLTexture<"u"&&r instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function CCe(s){var t=qj(s,1);if(!t){if(t=qj(s,0))t=new Float32Array(t).map(n=>n/255);else{t=new Float32Array(s.width*s.height);const n=a8(s);var r=X6e(s);if(t1t(r,n,r1t(s)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){r=new Float32Array(s.width*s.height*4),n.readPixels(0,0,s.width,s.height,n.RGBA,n.FLOAT,r);for(let a=0,i=0;aMath.round(255*r))),s.g.push(t)),t;var s,t}ia(){return CCe(this)}N(){return r1t(this)}clone(){const s=[];for(const t of this.g){let r;if(t instanceof Uint8Array)r=new Uint8Array(t);else if(t instanceof Float32Array)r=new Float32Array(t);else{if(!(t instanceof WebGLTexture))throw Error(`Type is not supported: ${t}`);{const n=a8(this),a=X6e(this);n.activeTexture(n.TEXTURE1),r=e1t(a,n,this.m?n.LINEAR:n.NEAREST),n.bindTexture(n.TEXTURE_2D,r);const i=n1t(this);n.texImage2D(n.TEXTURE_2D,0,i,this.width,this.height,0,n.RED,n.FLOAT,null),n.bindTexture(n.TEXTURE_2D,null),t1t(a,n,r),bUs(a,n,!1,()=>{a1t(this),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.TRIANGLE_FAN,0,4),TCe(this)}),_Us(a),TCe(this)}}s.push(r)}return new Ym(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&a8(this).deleteTexture(qj(this,2)),iKe=-1}};Ym.prototype.close=Ym.prototype.close,Ym.prototype.clone=Ym.prototype.clone,Ym.prototype.getAsWebGLTexture=Ym.prototype.N,Ym.prototype.getAsFloat32Array=Ym.prototype.ia,Ym.prototype.getAsUint8Array=Ym.prototype.ja,Ym.prototype.hasWebGLTexture=Ym.prototype.R,Ym.prototype.hasFloat32Array=Ym.prototype.ka,Ym.prototype.hasUint8Array=Ym.prototype.Fa;var iKe=250;function K1(...s){return s.map(([t,r])=>({start:t,end:r}))}const wUs=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((oKe=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:Qvt()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(s){const t=await(await fetch(s)).arrayBuffer();s=!(s.endsWith(".pbtxt")||s.endsWith(".textproto")),this.setGraph(new Uint8Array(t),s)}setGraphFromString(s){this.setGraph(new TextEncoder().encode(s),!1)}setGraph(s,t){const r=s.length,n=this.i._malloc(r);this.i.HEAPU8.set(s,n),t?this.i._changeBinaryGraph(r,n):this.i._changeTextGraph(r,n),this.i._free(n)}configureAudio(s,t,r,n,a){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),gi(this,n||"input_audio",i=>{gi(this,a=a||"audio_header",l=>{this.i._configureAudio(i,l,s,t??0,r)})})}setAutoResizeCanvas(s){this.l=s}setAutoRenderToScreen(s){this.i._setAutoRenderToScreen(s)}setGpuBufferVerticalFlip(s){this.i.gpuOriginForWebTexturesIsBottomLeft=s}ca(s){Rb(this,"__graph_config__",t=>{s(t)}),gi(this,"__graph_config__",t=>{this.i._getGraphConfig(t,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(s){this.i.errorListener=s}attachEmptyPacketListener(s,t){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[s]=t}addAudioToStream(s,t,r){this.addAudioToStreamWithShape(s,0,0,t,r)}addAudioToStreamWithShape(s,t,r,n,a){const i=4*s.length;this.h!==i&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(i),this.h=i),this.i.HEAPF32.set(s,this.g/4),gi(this,n,l=>{this.i._addAudioToInputStream(this.g,t,r,l,a)})}addGpuBufferToStream(s,t,r){gi(this,t,n=>{const[a,i]=tKe(this,s,n);this.i._addBoundTextureToStream(n,a,i,r)})}addBoolToStream(s,t,r){gi(this,t,n=>{this.i._addBoolToInputStream(s,n,r)})}addDoubleToStream(s,t,r){gi(this,t,n=>{this.i._addDoubleToInputStream(s,n,r)})}addFloatToStream(s,t,r){gi(this,t,n=>{this.i._addFloatToInputStream(s,n,r)})}addIntToStream(s,t,r){gi(this,t,n=>{this.i._addIntToInputStream(s,n,r)})}addUintToStream(s,t,r){gi(this,t,n=>{this.i._addUintToInputStream(s,n,r)})}addStringToStream(s,t,r){gi(this,t,n=>{gi(this,s,a=>{this.i._addStringToInputStream(a,n,r)})})}addStringRecordToStream(s,t,r){gi(this,t,n=>{sKe(this,Object.keys(s),a=>{sKe(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,n,r)})})})}addProtoToStream(s,t,r,n){gi(this,r,a=>{gi(this,t,i=>{const l=this.i._malloc(s.length);this.i.HEAPU8.set(s,l),this.i._addProtoToInputStream(l,s.length,i,a,n),this.i._free(l)})})}addEmptyPacketToStream(s,t){gi(this,s,r=>{this.i._addEmptyPacketToInputStream(r,t)})}addBoolVectorToStream(s,t,r){gi(this,t,n=>{const a=this.i._allocateBoolVector(s.length);if(!a)throw Error("Unable to allocate new bool vector on heap.");for(const i of s)this.i._addBoolVectorEntry(a,i);this.i._addBoolVectorToInputStream(a,n,r)})}addDoubleVectorToStream(s,t,r){gi(this,t,n=>{const a=this.i._allocateDoubleVector(s.length);if(!a)throw Error("Unable to allocate new double vector on heap.");for(const i of s)this.i._addDoubleVectorEntry(a,i);this.i._addDoubleVectorToInputStream(a,n,r)})}addFloatVectorToStream(s,t,r){gi(this,t,n=>{const a=this.i._allocateFloatVector(s.length);if(!a)throw Error("Unable to allocate new float vector on heap.");for(const i of s)this.i._addFloatVectorEntry(a,i);this.i._addFloatVectorToInputStream(a,n,r)})}addIntVectorToStream(s,t,r){gi(this,t,n=>{const a=this.i._allocateIntVector(s.length);if(!a)throw Error("Unable to allocate new int vector on heap.");for(const i of s)this.i._addIntVectorEntry(a,i);this.i._addIntVectorToInputStream(a,n,r)})}addUintVectorToStream(s,t,r){gi(this,t,n=>{const a=this.i._allocateUintVector(s.length);if(!a)throw Error("Unable to allocate new unsigned int vector on heap.");for(const i of s)this.i._addUintVectorEntry(a,i);this.i._addUintVectorToInputStream(a,n,r)})}addStringVectorToStream(s,t,r){gi(this,t,n=>{const a=this.i._allocateStringVector(s.length);if(!a)throw Error("Unable to allocate new string vector on heap.");for(const i of s)gi(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,n,r)})}addBoolToInputSidePacket(s,t){gi(this,t,r=>{this.i._addBoolToInputSidePacket(s,r)})}addDoubleToInputSidePacket(s,t){gi(this,t,r=>{this.i._addDoubleToInputSidePacket(s,r)})}addFloatToInputSidePacket(s,t){gi(this,t,r=>{this.i._addFloatToInputSidePacket(s,r)})}addIntToInputSidePacket(s,t){gi(this,t,r=>{this.i._addIntToInputSidePacket(s,r)})}addUintToInputSidePacket(s,t){gi(this,t,r=>{this.i._addUintToInputSidePacket(s,r)})}addStringToInputSidePacket(s,t){gi(this,t,r=>{gi(this,s,n=>{this.i._addStringToInputSidePacket(n,r)})})}addProtoToInputSidePacket(s,t,r){gi(this,r,n=>{gi(this,t,a=>{const i=this.i._malloc(s.length);this.i.HEAPU8.set(s,i),this.i._addProtoToInputSidePacket(i,s.length,a,n),this.i._free(i)})})}addBoolVectorToInputSidePacket(s,t){gi(this,t,r=>{const n=this.i._allocateBoolVector(s.length);if(!n)throw Error("Unable to allocate new bool vector on heap.");for(const a of s)this.i._addBoolVectorEntry(n,a);this.i._addBoolVectorToInputSidePacket(n,r)})}addDoubleVectorToInputSidePacket(s,t){gi(this,t,r=>{const n=this.i._allocateDoubleVector(s.length);if(!n)throw Error("Unable to allocate new double vector on heap.");for(const a of s)this.i._addDoubleVectorEntry(n,a);this.i._addDoubleVectorToInputSidePacket(n,r)})}addFloatVectorToInputSidePacket(s,t){gi(this,t,r=>{const n=this.i._allocateFloatVector(s.length);if(!n)throw Error("Unable to allocate new float vector on heap.");for(const a of s)this.i._addFloatVectorEntry(n,a);this.i._addFloatVectorToInputSidePacket(n,r)})}addIntVectorToInputSidePacket(s,t){gi(this,t,r=>{const n=this.i._allocateIntVector(s.length);if(!n)throw Error("Unable to allocate new int vector on heap.");for(const a of s)this.i._addIntVectorEntry(n,a);this.i._addIntVectorToInputSidePacket(n,r)})}addUintVectorToInputSidePacket(s,t){gi(this,t,r=>{const n=this.i._allocateUintVector(s.length);if(!n)throw Error("Unable to allocate new unsigned int vector on heap.");for(const a of s)this.i._addUintVectorEntry(n,a);this.i._addUintVectorToInputSidePacket(n,r)})}addStringVectorToInputSidePacket(s,t){gi(this,t,r=>{const n=this.i._allocateStringVector(s.length);if(!n)throw Error("Unable to allocate new string vector on heap.");for(const a of s)gi(this,a,i=>{this.i._addStringVectorEntry(n,i)});this.i._addStringVectorToInputSidePacket(n,r)})}attachBoolListener(s,t){Rb(this,s,t),gi(this,s,r=>{this.i._attachBoolListener(r)})}attachBoolVectorListener(s,t){$N(this,s,t),gi(this,s,r=>{this.i._attachBoolVectorListener(r)})}attachIntListener(s,t){Rb(this,s,t),gi(this,s,r=>{this.i._attachIntListener(r)})}attachIntVectorListener(s,t){$N(this,s,t),gi(this,s,r=>{this.i._attachIntVectorListener(r)})}attachUintListener(s,t){Rb(this,s,t),gi(this,s,r=>{this.i._attachUintListener(r)})}attachUintVectorListener(s,t){$N(this,s,t),gi(this,s,r=>{this.i._attachUintVectorListener(r)})}attachDoubleListener(s,t){Rb(this,s,t),gi(this,s,r=>{this.i._attachDoubleListener(r)})}attachDoubleVectorListener(s,t){$N(this,s,t),gi(this,s,r=>{this.i._attachDoubleVectorListener(r)})}attachFloatListener(s,t){Rb(this,s,t),gi(this,s,r=>{this.i._attachFloatListener(r)})}attachFloatVectorListener(s,t){$N(this,s,t),gi(this,s,r=>{this.i._attachFloatVectorListener(r)})}attachStringListener(s,t){Rb(this,s,t),gi(this,s,r=>{this.i._attachStringListener(r)})}attachStringVectorListener(s,t){$N(this,s,t),gi(this,s,r=>{this.i._attachStringVectorListener(r)})}attachProtoListener(s,t,r){Rb(this,s,t),gi(this,s,n=>{this.i._attachProtoListener(n,r||!1)})}attachProtoVectorListener(s,t,r){$N(this,s,t),gi(this,s,n=>{this.i._attachProtoVectorListener(n,r||!1)})}attachAudioListener(s,t,r){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),Rb(this,s,(n,a)=>{n=new Float32Array(n.buffer,n.byteOffset,n.length/4),t(n,a)}),gi(this,s,n=>{this.i._attachAudioListener(n,r||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends oKe{get ga(){return this.i}pa(s,t,r){gi(this,t,n=>{const[a,i]=tKe(this,s,n);this.ga._addBoundTextureAsImageToStream(n,a,i,r)})}Z(s,t){Rb(this,s,t),gi(this,s,r=>{this.ga._attachImageListener(r)})}aa(s,t){$N(this,s,t),gi(this,s,r=>{this.ga._attachImageVectorListener(r)})}}));var oKe,Y1=class extends wUs{};async function Fl(s,t,r){return async function(n,a,i,l){return yUs(n,a,i,l)}(s,r.canvas??(Qvt()?void 0:document.createElement("canvas")),t,r)}function i1t(s,t,r,n){if(s.U){const i=new Cvt;if(r!=null&&r.regionOfInterest){if(!s.oa)throw Error("This task doesn't support region-of-interest.");var a=r.regionOfInterest;if(a.left>=a.right||a.top>=a.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(a.left<0||a.top<0||a.right>1||a.bottom>1)throw Error("Expected RectF values to be in [0,1].");Ni(i,1,(a.left+a.right)/2),Ni(i,2,(a.top+a.bottom)/2),Ni(i,4,a.right-a.left),Ni(i,3,a.bottom-a.top)}else Ni(i,1,.5),Ni(i,2,.5),Ni(i,4,1),Ni(i,3,1);if(r!=null&&r.rotationDegrees){if((r==null?void 0:r.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(Ni(i,5,-Math.PI*r.rotationDegrees/180),(r==null?void 0:r.rotationDegrees)%180!=0){const[l,o]=Jvt(t);r=ah(i,3)*o/l,a=ah(i,4)*l/o,Ni(i,4,r),Ni(i,3,a)}}s.g.addProtoToStream(i.g(),"mediapipe.NormalizedRect",s.U,n)}s.g.pa(t,s.X,n??performance.now()),s.finishProcessing()}function Z1(s,t,r){var n;if((n=s.baseOptions)!=null&&n.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");i1t(s,t,r,s.C+1)}function xw(s,t,r,n){var a;if(!((a=s.baseOptions)!=null&&a.g()))throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");i1t(s,t,r,n)}function i8(s,t,r,n){var a=t.data;const i=t.width,l=i*(t=t.height);if((a instanceof Uint8Array||a instanceof Float32Array)&&a.length!==l)throw Error("Unsupported channel count: "+a.length/l);return s=new Ym([a],r,!1,s.g.i.canvas,s.P,i,t),n?s.clone():s}var $0=class extends SCe{constructor(s,t,r,n){super(s),this.g=s,this.X=t,this.U=r,this.oa=n,this.P=new s1t}l(s,t=!0){if("runningMode"in s&&Cc(this.baseOptions,2,Rz(!!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()}};$0.prototype.close=$0.prototype.close;var ky=class extends $0{constructor(s,t){super(new Y1(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},$i(s=this.h=new Uye,0,1,t=new Ku),Ni(this.h,2,.5),Ni(this.h,3,.3)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Ni(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Ni(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},Z1(this,s,t),this.j}G(s,t,r){return this.j={detections:[]},xw(this,s,r,t),this.j}m(){var s=new W0;yu(s,"image_in"),yu(s,"norm_rect_in"),Zl(s,"detections");const t=new G0;fw(t,rUs,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Kd(r,"IMAGE:image_in"),Kd(r,"NORM_RECT:norm_rect_in"),Tl(r,"DETECTIONS:detections"),r.o(t),gv(s,r),this.g.attachProtoVectorListener("detections",(n,a)=>{for(const i of n)n=Nvt(i),this.j.detections.push(Zvt(n));oi(this,a)}),this.g.attachEmptyPacketListener("detections",n=>{oi(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};ky.prototype.detectForVideo=ky.prototype.G,ky.prototype.detect=ky.prototype.F,ky.prototype.setOptions=ky.prototype.o,ky.createFromModelPath=async function(s,t){return Fl(ky,s,{baseOptions:{modelAssetPath:t}})},ky.createFromModelBuffer=function(s,t){return Fl(ky,s,{baseOptions:{modelAssetBuffer:t}})},ky.createFromOptions=function(s,t){return Fl(ky,s,t)};var Q6e=K1([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]),J6e=K1([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]),eIe=K1([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),o1t=K1([474,475],[475,476],[476,477],[477,474]),tIe=K1([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]),sIe=K1([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),l1t=K1([469,470],[470,471],[471,472],[472,469]),rIe=K1([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]),c1t=[...Q6e,...J6e,...eIe,...tIe,...sIe,...rIe],d1t=K1([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 lKe(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var Mu=class extends $0{constructor(s,t){super(new Y1(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,$i(s=this.h=new Ivt,0,1,t=new Ku),this.A=new Mvt,$i(this.h,0,3,this.A),this.u=new Uye,$i(this.h,0,2,this.u),D2(this.u,4,1),Ni(this.u,2,.5),Ni(this.A,2,.5),Ni(this.h,4,.5)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){return"numFaces"in s&&D2(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Ni(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Ni(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Ni(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 lKe(this),Z1(this,s,t),this.j}G(s,t,r){return lKe(this),xw(this,s,r,t),this.j}m(){var s=new W0;yu(s,"image_in"),yu(s,"norm_rect"),Zl(s,"face_landmarks");const t=new G0;fw(t,aUs,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Kd(r,"IMAGE:image_in"),Kd(r,"NORM_RECT:norm_rect"),Tl(r,"NORM_LANDMARKS:face_landmarks"),r.o(t),gv(s,r),this.g.attachProtoVectorListener("face_landmarks",(n,a)=>{for(const i of n)n=c$(i),this.j.faceLandmarks.push(qye(n));oi(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",n=>{oi(this,n)}),this.outputFaceBlendshapes&&(Zl(s,"blendshapes"),Tl(r,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(n,a)=>{if(this.outputFaceBlendshapes)for(const i of n)n=$ye(i),this.j.faceBlendshapes.push(Y6e(n.g()??[]));oi(this,a)}),this.g.attachEmptyPacketListener("blendshapes",n=>{oi(this,n)})),this.outputFacialTransformationMatrixes&&(Zl(s,"face_geometry"),Tl(r,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(n,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of n)(n=$l(n=nUs(i),Y$s,2))&&this.j.facialTransformationMatrixes.push({rows:Ky(n,1)??0??0,columns:Ky(n,2)??0??0,data:cE(n,3,f_,lE()).slice()??[]});oi(this,a)}),this.g.attachEmptyPacketListener("face_geometry",n=>{oi(this,n)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Mu.prototype.detectForVideo=Mu.prototype.G,Mu.prototype.detect=Mu.prototype.F,Mu.prototype.setOptions=Mu.prototype.o,Mu.createFromModelPath=function(s,t){return Fl(Mu,s,{baseOptions:{modelAssetPath:t}})},Mu.createFromModelBuffer=function(s,t){return Fl(Mu,s,{baseOptions:{modelAssetBuffer:t}})},Mu.createFromOptions=function(s,t){return Fl(Mu,s,t)},Mu.FACE_LANDMARKS_LIPS=Q6e,Mu.FACE_LANDMARKS_LEFT_EYE=J6e,Mu.FACE_LANDMARKS_LEFT_EYEBROW=eIe,Mu.FACE_LANDMARKS_LEFT_IRIS=o1t,Mu.FACE_LANDMARKS_RIGHT_EYE=tIe,Mu.FACE_LANDMARKS_RIGHT_EYEBROW=sIe,Mu.FACE_LANDMARKS_RIGHT_IRIS=l1t,Mu.FACE_LANDMARKS_FACE_OVAL=rIe,Mu.FACE_LANDMARKS_CONTOURS=c1t,Mu.FACE_LANDMARKS_TESSELATION=d1t;var nIe=K1([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 cKe(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function dKe(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 uKe(s,t=!0){const r=[];for(const a of s){var n=$ye(a);s=[];for(const i of n.g())n=t&&Ky(i,1)!=null?Ky(i,1)??0:-1,s.push({score:ah(i,2)??0,index:n,categoryName:Qf(mu(i,3))??""??"",displayName:Qf(mu(i,4))??""??""});r.push(s)}return r}var e0=class extends $0{constructor(s,t){super(new Y1(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],$i(s=this.j=new Dvt,0,1,t=new Ku),this.u=new H6e,$i(this.j,0,2,this.u),this.D=new V6e,$i(this.u,0,3,this.D),this.A=new Lvt,$i(this.u,0,2,this.A),this.h=new iUs,$i(this.j,0,3,this.h),Ni(this.A,2,.5),Ni(this.u,4,.5),Ni(this.D,2,.5)}get baseOptions(){return $l(this.j,Ku,1)}set baseOptions(s){$i(this.j,0,1,s)}o(s){var a,i,l,o;if(D2(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ni(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ni(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ni(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new U6,r=t,n=kCe(s.cannedGesturesClassifierOptions,(a=$l(this.h,U6,3))==null?void 0:a.l());$i(r,0,2,n),$i(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=$l(this.h,U6,3))==null||i.g());return s.customGesturesClassifierOptions?($i(r=t=new U6,0,2,n=kCe(s.customGesturesClassifierOptions,(l=$l(this.h,U6,4))==null?void 0:l.l())),$i(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=$l(this.h,U6,4))==null||o.g()),this.l(s)}Ha(s,t){return cKe(this),Z1(this,s,t),dKe(this)}Ia(s,t,r){return cKe(this),xw(this,s,r,t),dKe(this)}m(){var s=new W0;yu(s,"image_in"),yu(s,"norm_rect"),Zl(s,"hand_gestures"),Zl(s,"hand_landmarks"),Zl(s,"world_hand_landmarks"),Zl(s,"handedness");const t=new G0;fw(t,oUs,this.j);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Kd(r,"IMAGE:image_in"),Kd(r,"NORM_RECT:norm_rect"),Tl(r,"HAND_GESTURES:hand_gestures"),Tl(r,"LANDMARKS:hand_landmarks"),Tl(r,"WORLD_LANDMARKS:world_hand_landmarks"),Tl(r,"HANDEDNESS:handedness"),r.o(t),gv(s,r),this.g.attachProtoVectorListener("hand_landmarks",(n,a)=>{for(const i of n){n=c$(i);const l=[];for(const o of L2(n,Svt,1))l.push({x:ah(o,1)??0,y:ah(o,2)??0,z:ah(o,3)??0,visibility:ah(o,4)??0});this.landmarks.push(l)}oi(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",n=>{oi(this,n)}),this.g.attachProtoVectorListener("world_hand_landmarks",(n,a)=>{for(const i of n){n=LP(i);const l=[];for(const o of L2(n,kvt,1))l.push({x:ah(o,1)??0,y:ah(o,2)??0,z:ah(o,3)??0,visibility:ah(o,4)??0});this.worldLandmarks.push(l)}oi(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",n=>{oi(this,n)}),this.g.attachProtoVectorListener("hand_gestures",(n,a)=>{this.gestures.push(...uKe(n,!1)),oi(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",n=>{oi(this,n)}),this.g.attachProtoVectorListener("handedness",(n,a)=>{this.handedness.push(...uKe(n)),oi(this,a)}),this.g.attachEmptyPacketListener("handedness",n=>{oi(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function hKe(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}e0.prototype.recognizeForVideo=e0.prototype.Ia,e0.prototype.recognize=e0.prototype.Ha,e0.prototype.setOptions=e0.prototype.o,e0.createFromModelPath=function(s,t){return Fl(e0,s,{baseOptions:{modelAssetPath:t}})},e0.createFromModelBuffer=function(s,t){return Fl(e0,s,{baseOptions:{modelAssetBuffer:t}})},e0.createFromOptions=function(s,t){return Fl(e0,s,t)},e0.HAND_CONNECTIONS=nIe;var t0=class extends $0{constructor(s,t){super(new Y1(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],$i(s=this.h=new H6e,0,1,t=new Ku),this.u=new V6e,$i(this.h,0,3,this.u),this.j=new Lvt,$i(this.h,0,2,this.j),D2(this.j,3,1),Ni(this.j,2,.5),Ni(this.u,2,.5),Ni(this.h,4,.5)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){return"numHands"in s&&D2(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ni(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ni(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ni(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Z1(this,s,t),hKe(this)}G(s,t,r){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],xw(this,s,r,t),hKe(this)}m(){var s=new W0;yu(s,"image_in"),yu(s,"norm_rect"),Zl(s,"hand_landmarks"),Zl(s,"world_hand_landmarks"),Zl(s,"handedness");const t=new G0;fw(t,lUs,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Kd(r,"IMAGE:image_in"),Kd(r,"NORM_RECT:norm_rect"),Tl(r,"LANDMARKS:hand_landmarks"),Tl(r,"WORLD_LANDMARKS:world_hand_landmarks"),Tl(r,"HANDEDNESS:handedness"),r.o(t),gv(s,r),this.g.attachProtoVectorListener("hand_landmarks",(n,a)=>{for(const i of n)n=c$(i),this.landmarks.push(qye(n));oi(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",n=>{oi(this,n)}),this.g.attachProtoVectorListener("world_hand_landmarks",(n,a)=>{for(const i of n)n=LP(i),this.worldLandmarks.push(Y7(n));oi(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",n=>{oi(this,n)}),this.g.attachProtoVectorListener("handedness",(n,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of n){n=$ye(c);const d=[];for(const u of n.g())d.push({score:ah(u,2)??0,index:Ky(u,1)??0??-1,categoryName:Qf(mu(u,3))??""??"",displayName:Qf(mu(u,4))??""??""});o.push(d)}l.call(i,...o),oi(this,a)}),this.g.attachEmptyPacketListener("handedness",n=>{oi(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};t0.prototype.detectForVideo=t0.prototype.G,t0.prototype.detect=t0.prototype.F,t0.prototype.setOptions=t0.prototype.o,t0.createFromModelPath=function(s,t){return Fl(t0,s,{baseOptions:{modelAssetPath:t}})},t0.createFromModelBuffer=function(s,t){return Fl(t0,s,{baseOptions:{modelAssetBuffer:t}})},t0.createFromOptions=function(s,t){return Fl(t0,s,t)},t0.HAND_CONNECTIONS=nIe;var u1t=K1([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 mKe(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function fKe(s){try{if(!s.D)return s.h;s.D(s.h)}finally{Hye(s)}}function EV(s,t){s=c$(s),t.push(qye(s))}var Od=class extends $0{constructor(s,t){super(new Y1(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,$i(s=this.j=new Bvt,0,1,t=new Ku),this.I=new V6e,$i(this.j,0,2,this.I),this.W=new cUs,$i(this.j,0,3,this.W),this.u=new Uye,$i(this.j,0,4,this.u),this.O=new Mvt,$i(this.j,0,5,this.O),this.A=new Fvt,$i(this.j,0,6,this.A),this.M=new zvt,$i(this.j,0,7,this.M),Ni(this.u,2,.5),Ni(this.u,3,.3),Ni(this.O,2,.5),Ni(this.A,2,.5),Ni(this.A,3,.3),Ni(this.M,2,.5),Ni(this.I,2,.5)}get baseOptions(){return $l(this.j,Ku,1)}set baseOptions(s){$i(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Ni(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Ni(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Ni(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Ni(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Ni(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Ni(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Ni(this.I,2,s.minHandLandmarksConfidence??.5),this.l(s)}F(s,t,r){const n=typeof t!="function"?t:{};return this.D=typeof t=="function"?t:r,mKe(this),Z1(this,s,n),fKe(this)}G(s,t,r,n){const a=typeof r!="function"?r:{};return this.D=typeof r=="function"?r:n,mKe(this),xw(this,s,a,t),fKe(this)}m(){var s=new W0;yu(s,"input_frames_image"),Zl(s,"pose_landmarks"),Zl(s,"pose_world_landmarks"),Zl(s,"face_landmarks"),Zl(s,"left_hand_landmarks"),Zl(s,"left_hand_world_landmarks"),Zl(s,"right_hand_landmarks"),Zl(s,"right_hand_world_landmarks");const t=new G0,r=new FWe;B0(r,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))Cc(a,2,Eye(i,0,Oz));else{if(!(typeof i=="string"||i instanceof O_||d6e(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");uk(a,2,h6e(i,!1),BA())}}(r,this.j.g());const n=new Ig;B0(n,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),S6e(n,8,FWe,r),Kd(n,"IMAGE:input_frames_image"),Tl(n,"POSE_LANDMARKS:pose_landmarks"),Tl(n,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Tl(n,"FACE_LANDMARKS:face_landmarks"),Tl(n,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Tl(n,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Tl(n,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Tl(n,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),n.o(t),gv(s,n),Vye(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{EV(a,this.h.poseLandmarks),oi(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{oi(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=LP(a),l.push(Y7(a)),oi(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{oi(this,a)}),this.outputPoseSegmentationMasks&&(Tl(n,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),n8(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[i8(this,a,!0,!this.D)],oi(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],oi(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{EV(a,this.h.faceLandmarks),oi(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{oi(this,a)}),this.outputFaceBlendshapes&&(Zl(s,"extra_blendshapes"),Tl(n,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=$ye(a),l.push(Y6e(a.g()??[]))),oi(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{oi(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{EV(a,this.h.leftHandLandmarks),oi(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{oi(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=LP(a),l.push(Y7(a)),oi(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{oi(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{EV(a,this.h.rightHandLandmarks),oi(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{oi(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=LP(a),l.push(Y7(a)),oi(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{oi(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Od.prototype.detectForVideo=Od.prototype.G,Od.prototype.detect=Od.prototype.F,Od.prototype.setOptions=Od.prototype.o,Od.createFromModelPath=function(s,t){return Fl(Od,s,{baseOptions:{modelAssetPath:t}})},Od.createFromModelBuffer=function(s,t){return Fl(Od,s,{baseOptions:{modelAssetBuffer:t}})},Od.createFromOptions=function(s,t){return Fl(Od,s,t)},Od.HAND_CONNECTIONS=nIe,Od.POSE_CONNECTIONS=u1t,Od.FACE_LANDMARKS_LIPS=Q6e,Od.FACE_LANDMARKS_LEFT_EYE=J6e,Od.FACE_LANDMARKS_LEFT_EYEBROW=eIe,Od.FACE_LANDMARKS_LEFT_IRIS=o1t,Od.FACE_LANDMARKS_RIGHT_EYE=tIe,Od.FACE_LANDMARKS_RIGHT_EYEBROW=sIe,Od.FACE_LANDMARKS_RIGHT_IRIS=l1t,Od.FACE_LANDMARKS_FACE_OVAL=rIe,Od.FACE_LANDMARKS_CONTOURS=c1t,Od.FACE_LANDMARKS_TESSELATION=d1t;var Sy=class extends $0{constructor(s,t){super(new Y1(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},$i(s=this.h=new $vt,0,1,t=new Ku)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){return $i(this.h,0,2,kCe(s,$l(this.h,U6e,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},Z1(this,s,t),this.j}ta(s,t,r){return this.j={classifications:[]},xw(this,s,r,t),this.j}m(){var s=new W0;yu(s,"input_image"),yu(s,"norm_rect"),Zl(s,"classifications");const t=new G0;fw(t,dUs,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Kd(r,"IMAGE:input_image"),Kd(r,"NORM_RECT:norm_rect"),Tl(r,"CLASSIFICATIONS:classifications"),r.o(t),gv(s,r),this.g.attachProtoListener("classifications",(n,a)=>{this.j=xUs(Q$s(n)),oi(this,a)}),this.g.attachEmptyPacketListener("classifications",n=>{oi(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Sy.prototype.classifyForVideo=Sy.prototype.ta,Sy.prototype.classify=Sy.prototype.sa,Sy.prototype.setOptions=Sy.prototype.o,Sy.createFromModelPath=function(s,t){return Fl(Sy,s,{baseOptions:{modelAssetPath:t}})},Sy.createFromModelBuffer=function(s,t){return Fl(Sy,s,{baseOptions:{modelAssetBuffer:t}})},Sy.createFromOptions=function(s,t){return Fl(Sy,s,t)};var s0=class extends $0{constructor(s,t){super(new Y1(s,t),"image_in","norm_rect",!0),this.h=new Uvt,this.embeddings={embeddings:[]},$i(s=this.h,0,1,t=new Ku)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){var t=this.h,r=$l(this.h,WWe,2);return r=r?r.clone():new WWe,s.l2Normalize!==void 0?Cc(r,1,Rz(s.l2Normalize)):"l2Normalize"in s&&Cc(r,1),s.quantize!==void 0?Cc(r,2,Rz(s.quantize)):"quantize"in s&&Cc(r,2),$i(t,0,2,r),this.l(s)}za(s,t){return Z1(this,s,t),this.embeddings}Aa(s,t,r){return xw(this,s,r,t),this.embeddings}m(){var s=new W0;yu(s,"image_in"),yu(s,"norm_rect"),Zl(s,"embeddings_out");const t=new G0;fw(t,uUs,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Kd(r,"IMAGE:image_in"),Kd(r,"NORM_RECT:norm_rect"),Tl(r,"EMBEDDINGS:embeddings_out"),r.o(t),gv(s,r),this.g.attachProtoListener("embeddings_out",(n,a)=>{n=tUs(n),this.embeddings=function(i){return{embeddings:L2(i,eUs,1).map(l=>{var d,u;const o={headIndex:Ky(l,3)??0??-1,headName:Qf(mu(l,4))??""??""};var c=l.v;return zyt(c,0|c[fi],GWe,oje(l,1))!==void 0?(l=cE(l=$l(l,GWe,oje(l,1),void 0),1,f_,lE()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=$l(l,J$s,oje(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:Yvt(mu(i,2,void 0,void 0,Dpe)??Lyt)}}(n),oi(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",n=>{oi(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};s0.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=JWe(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=JWe(QWe(s.quantizedEmbedding),QWe(t.quantizedEmbedding))}return s},s0.prototype.embedForVideo=s0.prototype.Aa,s0.prototype.embed=s0.prototype.za,s0.prototype.setOptions=s0.prototype.o,s0.createFromModelPath=function(s,t){return Fl(s0,s,{baseOptions:{modelAssetPath:t}})},s0.createFromModelBuffer=function(s,t){return Fl(s0,s,{baseOptions:{modelAssetBuffer:t}})},s0.createFromOptions=function(s,t){return Fl(s0,s,t)};var ECe=class{constructor(s,t,r){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=r}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(r=>{r.close()}),(t=this.categoryMask)==null||t.close()}};function jUs(s){var r,n;const t=function(a){return L2(a,Ig,1)}(s.ca()).filter(a=>(Qf(mu(a,1))??"").includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(s.u=[],t.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");t.length===1&&(((n=(r=$l(t[0],G0,7))==null?void 0:r.j())==null?void 0:n.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=Qf(mu(a,1))??""})}function pKe(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function xKe(s){try{const t=new ECe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{Hye(s)}}ECe.prototype.close=ECe.prototype.close;var ux=class extends $0{constructor(s,t){super(new Y1(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new K6e,this.A=new qvt,$i(this.h,0,3,this.A),$i(s=this.h,0,1,t=new Ku)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Cc(this.h,2,i$(s.displayNamesLocale)):"displayNamesLocale"in s&&Cc(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){jUs(this)}segment(s,t,r){const n=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:r,pKe(this),Z1(this,s,n),xKe(this)}La(s,t,r,n){const a=typeof r!="function"?r:{};return this.j=typeof r=="function"?r:n,pKe(this),xw(this,s,a,t),xKe(this)}Da(){return this.u}m(){var s=new W0;yu(s,"image_in"),yu(s,"norm_rect");const t=new G0;fw(t,Hvt,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Kd(r,"IMAGE:image_in"),Kd(r,"NORM_RECT:norm_rect"),r.o(t),gv(s,r),Vye(this,s),this.outputConfidenceMasks&&(Zl(s,"confidence_masks"),Tl(r,"CONFIDENCE_MASKS:confidence_masks"),n8(this,"confidence_masks"),this.g.aa("confidence_masks",(n,a)=>{this.confidenceMasks=n.map(i=>i8(this,i,!0,!this.j)),oi(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",n=>{this.confidenceMasks=[],oi(this,n)})),this.outputCategoryMask&&(Zl(s,"category_mask"),Tl(r,"CATEGORY_MASK:category_mask"),n8(this,"category_mask"),this.g.Z("category_mask",(n,a)=>{this.categoryMask=i8(this,n,!1,!this.j),oi(this,a)}),this.g.attachEmptyPacketListener("category_mask",n=>{this.categoryMask=void 0,oi(this,n)})),Zl(s,"quality_scores"),Tl(r,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(n,a)=>{this.qualityScores=n,oi(this,a)}),this.g.attachEmptyPacketListener("quality_scores",n=>{this.categoryMask=void 0,oi(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};ux.prototype.getLabels=ux.prototype.Da,ux.prototype.segmentForVideo=ux.prototype.La,ux.prototype.segment=ux.prototype.segment,ux.prototype.setOptions=ux.prototype.o,ux.createFromModelPath=function(s,t){return Fl(ux,s,{baseOptions:{modelAssetPath:t}})},ux.createFromModelBuffer=function(s,t){return Fl(ux,s,{baseOptions:{modelAssetBuffer:t}})},ux.createFromOptions=function(s,t){return Fl(ux,s,t)};var ACe=class{constructor(s,t,r){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=r}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(r=>{r.close()}),(t=this.categoryMask)==null||t.close()}};ACe.prototype.close=ACe.prototype.close;var Ob=class extends $0{constructor(s,t){super(new Y1(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new K6e,this.u=new qvt,$i(this.h,0,3,this.u),$i(s=this.h,0,1,t=new Ku)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){return"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}segment(s,t,r,n){const a=typeof r!="function"?r:{};if(this.j=typeof r=="function"?r:n,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,r=this.C+1,n=new Gvt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new uje;uk(i,3,Rz(!0),!1),uk(i,1,GO(t.keypoint.x),0),uk(i,2,GO(t.keypoint.y),0),W7(n,1,NCe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new mUs;for(i of t.scribble)uk(t=new uje,3,Rz(!0),!1),uk(t,1,GO(i.x),0),uk(t,2,GO(i.y),0),S6e(o,1,uje,t);W7(n,2,NCe,o)}}this.g.addProtoToStream(n.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",r),Z1(this,s,a);e:{try{const o=new ACe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{Hye(this)}l=void 0}return l}m(){var s=new W0;yu(s,"image_in"),yu(s,"roi_in"),yu(s,"norm_rect_in");const t=new G0;fw(t,Hvt,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),Kd(r,"IMAGE:image_in"),Kd(r,"ROI:roi_in"),Kd(r,"NORM_RECT:norm_rect_in"),r.o(t),gv(s,r),Vye(this,s),this.outputConfidenceMasks&&(Zl(s,"confidence_masks"),Tl(r,"CONFIDENCE_MASKS:confidence_masks"),n8(this,"confidence_masks"),this.g.aa("confidence_masks",(n,a)=>{this.confidenceMasks=n.map(i=>i8(this,i,!0,!this.j)),oi(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",n=>{this.confidenceMasks=[],oi(this,n)})),this.outputCategoryMask&&(Zl(s,"category_mask"),Tl(r,"CATEGORY_MASK:category_mask"),n8(this,"category_mask"),this.g.Z("category_mask",(n,a)=>{this.categoryMask=i8(this,n,!1,!this.j),oi(this,a)}),this.g.attachEmptyPacketListener("category_mask",n=>{this.categoryMask=void 0,oi(this,n)})),Zl(s,"quality_scores"),Tl(r,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(n,a)=>{this.qualityScores=n,oi(this,a)}),this.g.attachEmptyPacketListener("quality_scores",n=>{this.categoryMask=void 0,oi(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ob.prototype.segment=Ob.prototype.segment,Ob.prototype.setOptions=Ob.prototype.o,Ob.createFromModelPath=function(s,t){return Fl(Ob,s,{baseOptions:{modelAssetPath:t}})},Ob.createFromModelBuffer=function(s,t){return Fl(Ob,s,{baseOptions:{modelAssetBuffer:t}})},Ob.createFromOptions=function(s,t){return Fl(Ob,s,t)};var Cy=class extends $0{constructor(s,t){super(new Y1(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},$i(s=this.h=new Wvt,0,1,t=new Ku)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Cc(this.h,2,i$(s.displayNamesLocale)):"displayNamesLocale"in s&&Cc(this.h,2),s.maxResults!==void 0?D2(this.h,3,s.maxResults):"maxResults"in s&&Cc(this.h,3),s.scoreThreshold!==void 0?Ni(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&Cc(this.h,4),s.categoryAllowlist!==void 0?Ope(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&Cc(this.h,5),s.categoryDenylist!==void 0?Ope(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&Cc(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},Z1(this,s,t),this.j}G(s,t,r){return this.j={detections:[]},xw(this,s,r,t),this.j}m(){var s=new W0;yu(s,"input_frame_gpu"),yu(s,"norm_rect"),Zl(s,"detections");const t=new G0;fw(t,fUs,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),Kd(r,"IMAGE:input_frame_gpu"),Kd(r,"NORM_RECT:norm_rect"),Tl(r,"DETECTIONS:detections"),r.o(t),gv(s,r),this.g.attachProtoVectorListener("detections",(n,a)=>{for(const i of n)n=Nvt(i),this.j.detections.push(Zvt(n));oi(this,a)}),this.g.attachEmptyPacketListener("detections",n=>{oi(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Cy.prototype.detectForVideo=Cy.prototype.G,Cy.prototype.detect=Cy.prototype.F,Cy.prototype.setOptions=Cy.prototype.o,Cy.createFromModelPath=async function(s,t){return Fl(Cy,s,{baseOptions:{modelAssetPath:t}})},Cy.createFromModelBuffer=function(s,t){return Fl(Cy,s,{baseOptions:{modelAssetBuffer:t}})},Cy.createFromOptions=function(s,t){return Fl(Cy,s,t)};var MCe=class{constructor(s,t,r){this.landmarks=s,this.worldLandmarks=t,this.segmentationMasks=r}close(){var s;(s=this.segmentationMasks)==null||s.forEach(t=>{t.close()})}};function gKe(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function yKe(s){try{const t=new MCe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{Hye(s)}}MCe.prototype.close=MCe.prototype.close;var r0=class extends $0{constructor(s,t){super(new Y1(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,$i(s=this.h=new Kvt,0,1,t=new Ku),this.A=new zvt,$i(this.h,0,3,this.A),this.j=new Fvt,$i(this.h,0,2,this.j),D2(this.j,4,1),Ni(this.j,2,.5),Ni(this.A,2,.5),Ni(this.h,4,.5)}get baseOptions(){return $l(this.h,Ku,1)}set baseOptions(s){$i(this.h,0,1,s)}o(s){return"numPoses"in s&&D2(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Ni(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Ni(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Ni(this.A,2,s.minPosePresenceConfidence??.5),"outputSegmentationMasks"in s&&(this.outputSegmentationMasks=s.outputSegmentationMasks??!1),this.l(s)}F(s,t,r){const n=typeof t!="function"?t:{};return this.u=typeof t=="function"?t:r,gKe(this),Z1(this,s,n),yKe(this)}G(s,t,r,n){const a=typeof r!="function"?r:{};return this.u=typeof r=="function"?r:n,gKe(this),xw(this,s,a,t),yKe(this)}m(){var s=new W0;yu(s,"image_in"),yu(s,"norm_rect"),Zl(s,"normalized_landmarks"),Zl(s,"world_landmarks"),Zl(s,"segmentation_masks");const t=new G0;fw(t,pUs,this.h);const r=new Ig;B0(r,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Kd(r,"IMAGE:image_in"),Kd(r,"NORM_RECT:norm_rect"),Tl(r,"NORM_LANDMARKS:normalized_landmarks"),Tl(r,"WORLD_LANDMARKS:world_landmarks"),r.o(t),gv(s,r),Vye(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(n,a)=>{this.landmarks=[];for(const i of n)n=c$(i),this.landmarks.push(qye(n));oi(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",n=>{this.landmarks=[],oi(this,n)}),this.g.attachProtoVectorListener("world_landmarks",(n,a)=>{this.worldLandmarks=[];for(const i of n)n=LP(i),this.worldLandmarks.push(Y7(n));oi(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",n=>{this.worldLandmarks=[],oi(this,n)}),this.outputSegmentationMasks&&(Tl(r,"SEGMENTATION_MASK:segmentation_masks"),n8(this,"segmentation_masks"),this.g.aa("segmentation_masks",(n,a)=>{this.segmentationMasks=n.map(i=>i8(this,i,!0,!this.u)),oi(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",n=>{this.segmentationMasks=[],oi(this,n)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};r0.prototype.detectForVideo=r0.prototype.G,r0.prototype.detect=r0.prototype.F,r0.prototype.setOptions=r0.prototype.o,r0.createFromModelPath=function(s,t){return Fl(r0,s,{baseOptions:{modelAssetPath:t}})},r0.createFromModelBuffer=function(s,t){return Fl(r0,s,{baseOptions:{modelAssetBuffer:t}})},r0.createFromOptions=function(s,t){return Fl(r0,s,t)},r0.POSE_CONNECTIONS=u1t;let dE=null,WO=null;async function NUs(){return dE||WO||(WO=(async()=>{const s=await nI.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return dE=await ux.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}),dE})(),WO)}function kUs(s,t,r,n,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+u]);const f=Math.min(m,r-1)-Math.max(u+1,0)+1;i[c+d]=o/f}}for(let l=0;l=0&&(o-=i[d*r+l]);const m=Math.min(u,n-1)-Math.max(d+1,0)+1;t[c*r+l]=o/m}}}function SUs(){dE&&(dE.close(),dE=null,WO=null)}function CUs(s,t){const r=k.useRef(null),n=k.useRef(null),a=k.useRef(null),i=k.useRef(null),l=k.useRef(0);k.useRef(0);const[o,c]=k.useState(null),[d,u]=k.useState(!1),[m,f]=k.useState(null),x=t.type!=="none"&&s!==null;return k.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]),k.useEffect(()=>{if(!x||!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}},[x,s]),k.useEffect(()=>{if(!x){c(null),f(null);return}let y=!1;return(async()=>{u(!0),f(null);try{const b=await NUs();if(y)return;u(!1);const j=a.current;if(!j||(await new Promise(Ie=>{if(j.videoWidth>0)return Ie();j.onloadedmetadata=()=>Ie(),setTimeout(Ie,2e3)}),y))return;const N=j.videoWidth||640,C=j.videoHeight||480,A=r.current;if(!A)return;A.width=N,A.height=C;const E=A.getContext("2d",{willReadFrequently:!1,alpha:!1});n.current||(n.current=document.createElement("canvas"));const D=n.current;D.width=N,D.height=C;const R=D.getContext("2d",{willReadFrequently:!1}),F=document.createElement("canvas");F.width=N,F.height=C;const O=F.getContext("2d",{alpha:!1}),B=document.createElement("canvas");B.width=N,B.height=C;const K=B.getContext("2d",{willReadFrequently:!1}),Z=K.createImageData(N,C),Q=Z.data;for(let Ie=0;IeW.addTrack(Ie)),y||c(W);const ne=t.blurRadius??15,ae=t.mirror??!1,ue=new Float32Array(N*C),me=new Float32Array(N*C),de=new Float32Array(N*C);let fe=!1;const je=4,xe=.35,Ee=typeof j.requestVideoFrameCallback=="function",Me=()=>{if(y||!a.current)return;const Ie=a.current;if(Ie.readyState<2){Oe(Ie);return}try{const ze=performance.now(),Le=b.segmentForVideo(Ie,ze).confidenceMasks;if(Le&&Le.length>0){me.fill(0);for(let $e=1;$e1?1:nt}}if(kUs(me,ue,N,C,je),fe)for(let $e=0;$e=1?255:Qe*255|0}if(K.putImageData(Z,0,0),t.type==="blur")O.filter=`blur(${ne}px)`,O.drawImage(Ie,0,0,N,C),O.filter="none",E.drawImage(F,0,0);else if(t.type==="image"&&i.current){const $e=i.current,ve=$e.width/$e.height,Qe=N/C;let we=0,nt=0,Se=$e.width,Ge=$e.height;ve>Qe?(Se=$e.height*Qe,we=($e.width-Se)/2):(Ge=$e.width/Qe,nt=($e.height-Ge)/2),E.drawImage($e,we,nt,Se,Ge,0,0,N,C)}else E.fillStyle="#000",E.fillRect(0,0,N,C);R.globalCompositeOperation="source-over",R.clearRect(0,0,N,C),R.drawImage(Ie,0,0,N,C),R.globalCompositeOperation="destination-in",R.drawImage(B,0,0),R.globalCompositeOperation="source-over",ae?(E.save(),E.translate(N,0),E.scale(-1,1),E.drawImage(D,0,0),E.restore()):E.drawImage(D,0,0);for(const $e of Le)$e.close()}else E.drawImage(Ie,0,0,N,C)}catch{E.drawImage(Ie,0,0,N,C)}Oe(Ie)},Oe=Ie=>{y||(Ee?Ie.requestVideoFrameCallback(()=>Me()):l.current=requestAnimationFrame(Me))};Oe(j)}catch(b){console.error("[useVirtualBackground] init error:",b),y||(u(!1),f(b.message||"Failed to initialize virtual background"))}})(),()=>{y=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[x,t.type,t.blurRadius,t.imageUrl,s]),k.useEffect(()=>()=>{SUs()},[]),{canvasRef:r,compositedStream:o,isLoading:d,isActive:x,error:m}}function pM({maxDurationSeconds:s=600,onRecordingComplete:t,onError:r,onRecordingStateChange:n,className:a,teleprompterContent:i}){const l=k.useRef(null),o=k.useRef(null),c=k.useRef(null),[d,u]=k.useState(null),m=k.useRef([]),f=k.useRef(null),x=k.useRef(null),y=k.useRef(null),_=k.useRef(null),b=rD(),[j,N]=k.useState("camera"),C=k.useRef(null),A=k.useRef(null),E=k.useRef(null),D=k.useRef(null),R=k.useRef(null),F=k.useRef(null),[O,B]=k.useState(!0),[K,Z]=k.useState(!0),[Q,W]=k.useState(null),[te,ne]=k.useState(!1),[ae,ue]=k.useState(!1),[me,de]=k.useState(null),[fe,je]=k.useState(null),[xe,Ee]=k.useState(0),[Me,Oe]=k.useState("user"),[Ie,ze]=k.useState(0),[Ve,Le]=k.useState(!1),[$e,ve]=k.useState(!0),[Qe,we]=k.useState(null),[nt,Se]=k.useState(!1),[Ge,We]=k.useState(null),Ce=k.useRef(null),[qe,et]=k.useState(()=>{try{const Br=localStorage.getItem("video-bg-config");if(Br)return JSON.parse(Br)}catch{}return{type:"none"}});k.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(qe))}catch{}},[qe]);const[Ze,rt]=k.useState([]),[ct,vt]=k.useState([]),[kt,St]=k.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Yt,es]=k.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});k.useEffect(()=>{try{localStorage.setItem("video-mic-id",kt)}catch{}},[kt]),k.useEffect(()=>{try{localStorage.setItem("video-cam-id",Yt)}catch{}},[Yt]),k.useEffect(()=>{var ps,Or,Qr;if(!((ps=navigator.mediaDevices)!=null&&ps.enumerateDevices))return;const Br=async()=>{try{const Tn=await navigator.mediaDevices.enumerateDevices();rt(Tn.filter(Qt=>Qt.kind==="audioinput")),vt(Tn.filter(Qt=>Qt.kind==="videoinput"))}catch(Tn){console.warn("[VideoRecorder] enumerateDevices failed",Tn)}};return Br(),(Qr=(Or=navigator.mediaDevices).addEventListener)==null||Qr.call(Or,"devicechange",Br),()=>{var Tn,Qt;return(Qt=(Tn=navigator.mediaDevices).removeEventListener)==null?void 0:Qt.call(Tn,"devicechange",Br)}},[Q]);const{canvasRef:zs,compositedStream:sr,isLoading:ms,isActive:gt,error:Ut}=CUs(d,qe),ht=k.useRef(r);ht.current=r;const Jt=k.useCallback(Br=>{B(Br)},[]),Ms=k.useRef(O),ts=k.useCallback(()=>{E.current&&(cancelAnimationFrame(E.current),E.current=null),D.current&&(D.current.terminate(),D.current=null),C.current&&(C.current.getTracks().forEach(Br=>Br.stop()),C.current=null),R.current&&(R.current.getTracks().forEach(Br=>Br.stop()),R.current=null),F.current&&(F.current.srcObject=null,F.current=null)},[]),Xs=k.useCallback(async()=>{var Br;try{const ps=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});C.current=ps;let Or=null;try{Or=await navigator.mediaDevices.getUserMedia({video:Yt?{deviceId:{exact:Yt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let Qr=null;try{Qr=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...kt?{deviceId:{exact:kt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",Qr.getAudioTracks().map(Kr=>Kr.label))}catch(Kr){console.warn("[VideoRecorder] No mic audio for screen recording",Kr);try{Qr=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Tn=ps.getVideoTracks()[0],Qt=Tn.getSettings(),Re=Qt.width||1920,Ke=Qt.height||1080,at=document.createElement("canvas");at.width=Re,at.height=Ke,A.current=at;const Nt=at.getContext("2d");let Ft=null;Or&&(Ft=document.createElement("video"),Ft.srcObject=Or,Ft.muted=!0,Ft.playsInline=!0,Ft.autoplay=!0,await Ft.play(),F.current=Ft);const qt=document.createElement("video");qt.srcObject=ps,qt.muted=!0,qt.playsInline=!0,qt.autoplay=!0,await qt.play();const cs=()=>{if(Nt.drawImage(qt,0,0,Re,Ke),Ft&&Ft.readyState>=2){const Kr=Math.round(Re*.2),mn=Math.round(Kr*(Ft.videoHeight/Ft.videoWidth||.75)),pn=Re-Kr-20,wn=Ke-mn-20,ca=12;Nt.save(),Nt.beginPath(),Nt.moveTo(pn+ca,wn),Nt.lineTo(pn+Kr-ca,wn),Nt.quadraticCurveTo(pn+Kr,wn,pn+Kr,wn+ca),Nt.lineTo(pn+Kr,wn+mn-ca),Nt.quadraticCurveTo(pn+Kr,wn+mn,pn+Kr-ca,wn+mn),Nt.lineTo(pn+ca,wn+mn),Nt.quadraticCurveTo(pn,wn+mn,pn,wn+mn-ca),Nt.lineTo(pn,wn+ca),Nt.quadraticCurveTo(pn,wn,pn+ca,wn),Nt.closePath(),Nt.clip(),Nt.translate(pn+Kr,wn),Nt.scale(-1,1),Nt.drawImage(Ft,0,0,Kr,mn),Nt.restore(),Nt.strokeStyle="rgba(255,255,255,0.6)",Nt.lineWidth=2,Nt.beginPath(),Nt.moveTo(pn+ca,wn),Nt.lineTo(pn+Kr-ca,wn),Nt.quadraticCurveTo(pn+Kr,wn,pn+Kr,wn+ca),Nt.lineTo(pn+Kr,wn+mn-ca),Nt.quadraticCurveTo(pn+Kr,wn+mn,pn+Kr-ca,wn+mn),Nt.lineTo(pn+ca,wn+mn),Nt.quadraticCurveTo(pn,wn+mn,pn,wn+mn-ca),Nt.lineTo(pn,wn+ca),Nt.quadraticCurveTo(pn,wn,pn+ca,wn),Nt.closePath(),Nt.stroke()}},it="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}}",Xt=new Blob([it],{type:"application/javascript"}),Bs=new Worker(URL.createObjectURL(Xt));D.current=Bs,Bs.onmessage=()=>cs(),Bs.postMessage({type:"start",fps:30}),cs();const us=at.captureStream(30),cr=[],Ar=ps.getAudioTracks();Ar.length&&cr.push(...Ar),Qr&&cr.push(...Qr.getAudioTracks());const xr=new MediaStream([...us.getVideoTracks(),...cr]);return R.current=xr,Tn.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),ts()},xr}catch(ps){return console.error("[VideoRecorder] Screen capture error:",ps),ps.name!=="NotAllowedError"&&((Br=ht.current)==null||Br.call(ht,"Failed to start screen capture: "+(ps.message||"Unknown error"))),null}},[ts]),js=k.useCallback(async()=>{var ps,Or;Z(!0),we(null);const Br=b&&O;console.log("[VideoRecorder] initCamera start",{isMobile:b,usePortraitMode:O,shouldBePortrait:Br,facingMode:Me});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");c.current&&(console.log("[VideoRecorder] stopping existing stream"),c.current.getTracks().forEach(Nt=>Nt.stop()));const Qr=b&&Br?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Tn=Yt?{...Qr,deviceId:{exact:Yt}}:{...Qr,facingMode:{ideal:Me}},Qt={echoCancellation:!0,noiseSuppression:!0,...kt?{deviceId:{exact:kt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Tn);const Re=await navigator.mediaDevices.getUserMedia({video:Tn,audio:Qt});if(console.log("[VideoRecorder] getUserMedia success"),Re.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=Re,u(Re),W(!0);const at=Re.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",at.width,"x",at.height),l.current){const Nt=l.current;Nt.srcObject=Re,Nt.muted=!0,Nt.playsInline=!0,Nt.autoplay=!0,Nt.setAttribute("muted",""),Nt.setAttribute("playsinline",""),Nt.setAttribute("autoplay","");try{(ps=Nt.load)==null||ps.call(Nt)}catch(qt){console.warn("[VideoRecorder] videoEl.load failed",qt)}const Ft=async()=>{try{return await Nt.play(),console.log("[VideoRecorder] preview play ok"),Se(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Nt.readyState,videoWidth:Nt.videoWidth,videoHeight:Nt.videoHeight})},300),!0}catch(qt){return console.warn("[VideoRecorder] preview play blocked",qt),Se(!0),!1}};await new Promise(qt=>{let cs=!1;const it=()=>{cs||(cs=!0,qt())},Xt=()=>{Ft().finally(it)};Nt.onloadedmetadata=Xt,Nt.onloadeddata=Xt,setTimeout(it,1500)})}try{x.current=new AudioContext;const Nt=x.current.createMediaStreamSource(Re);y.current=x.current.createAnalyser(),y.current.fftSize=256,Nt.connect(y.current);const Ft=()=>{if(y.current){const qt=new Uint8Array(y.current.frequencyBinCount);y.current.getByteFrequencyData(qt);const cs=qt.reduce((it,Xt)=>it+Xt)/qt.length;ze(Math.min(100,cs/128*100))}_.current=requestAnimationFrame(Ft)};Ft()}catch(Nt){console.warn("Audio context not available:",Nt)}}catch(Qr){console.error("Camera initialization error:",Qr),W(!1);let Tn="Failed to access camera or microphone.";Qr.name==="NotAllowedError"?Tn="Camera permission denied. Please allow camera access in your browser settings.":Qr.name==="NotFoundError"?Tn="No camera found. Please connect a camera and try again.":Qr.name==="NotReadableError"?Tn="Camera is in use by another application. Please close other apps using the camera.":Qr.message&&(Tn=Qr.message),we(Tn),(Or=ht.current)==null||Or.call(ht,Tn)}finally{Z(!1)}},[Me,b,O,kt,Yt]);k.useEffect(()=>{Ms.current!==O&&Q&&!te&&!fe&&(Ms.current=O,js())},[O,Q,te,fe,js]),k.useEffect(()=>(js(),()=>{c.current&&c.current.getTracks().forEach(Br=>Br.stop()),f.current&&clearInterval(f.current),_.current&&cancelAnimationFrame(_.current),x.current&&x.current.close(),Ce.current&&clearInterval(Ce.current),fe&&URL.revokeObjectURL(fe),ts()}),[js,fe]),k.useEffect(()=>{if(K||Q!==!0||fe)return;const Br=c.current,ps=l.current;!Br||!ps||gt||(ps.srcObject!==Br&&(ps.srcObject=Br,ps.muted=!0,ps.playsInline=!0,ps.autoplay=!0,ps.setAttribute("muted",""),ps.setAttribute("playsinline",""),ps.setAttribute("autoplay","")),ps.play().then(()=>Se(!1)).catch(Or=>{Se(!0),console.warn("Live preview play blocked on mount:",Or)}))},[Q,K,fe,gt]),k.useEffect(()=>{n==null||n(te)},[te,n]);const $s=k.useCallback(async()=>{if(fe)return;const Br=l.current;if(Br)try{await Br.play(),Se(!1)}catch(ps){Se(!0),console.warn("Live preview still blocked (needs user gesture):",ps)}},[fe]),Js=k.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),f.current&&(clearInterval(f.current),f.current=null),ts(),ne(!1),ue(!1)},[ts]),or=k.useCallback(async()=>{let Br=null;if(j==="screen"){if(Br=await Xs(),!Br)return}else Br=gt&&sr?sr:c.current;if(!Br)return;$s(),m.current=[],Ee(0);const Or=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Tn=>MediaRecorder.isTypeSupported(Tn)),Qr=new MediaRecorder(Br,Or?{mimeType:Or,videoBitsPerSecond:j==="screen"?4e6:25e5}:{videoBitsPerSecond:j==="screen"?4e6:25e5});Qr.ondataavailable=Tn=>{Tn.data.size>0&&m.current.push(Tn.data)},Qr.onstop=()=>{var Ke;const Tn=Qr.mimeType||Or||((Ke=m.current[0])==null?void 0:Ke.type)||"video/webm",Qt=new Blob(m.current,{type:Tn});de(Qt);const Re=URL.createObjectURL(Qt);je(Re)},o.current=Qr,Qr.start(100),ne(!0),f.current=setInterval(()=>{Ee(Tn=>Tn>=s-1?(Js(),s):Tn+1)},1e3)},[$s,s,Js,gt,sr,j,Xs]),Er=k.useCallback(()=>{Ce.current&&(clearInterval(Ce.current),Ce.current=null),We(3);let Br=3;Ce.current=setInterval(()=>{Br-=1,Br<=0?(Ce.current&&clearInterval(Ce.current),Ce.current=null,We(null),or()):We(Br)},1e3)},[or]),Sr=k.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),ue(!0),f.current&&clearInterval(f.current))},[]),Gr=k.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),ue(!1),f.current=setInterval(()=>{Ee(Br=>Br>=s-1?(Js(),s):Br+1)},1e3))},[s,Js]),Yr=k.useCallback(()=>{fe&&URL.revokeObjectURL(fe),de(null),je(null),Ee(0),Le(!1),ve(!0),l.current&&c.current&&!gt&&(l.current.srcObject=c.current,l.current.muted=!0,$s())},[$s,fe,gt]),Fn=k.useCallback(()=>{Oe(Br=>Br==="user"?"environment":"user")},[]),sa=k.useCallback(()=>{me&&t(me,xe)},[me,xe,t]),gs=k.useCallback(()=>{l.current&&fe&&(Ve?l.current.pause():(ve(!1),l.current.muted=!1,l.current.play()),Le(!Ve))},[fe,Ve]);k.useEffect(()=>{if(!fe)return;const Br=l.current;if(!Br)return;ve(!1),Br.pause(),Br.removeAttribute("src"),Br.srcObject=null,Br.load(),Br.src=fe,Br.currentTime=0,Br.playsInline=!0,Br.muted=!1,Br.onended=()=>Le(!1);const ps=()=>{var Tn;const Or=Br.error,Qr=Or?`Recorded video failed to play (code ${Or.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",Or),(Tn=ht.current)==null||Tn.call(ht,Qr)};return Br.addEventListener("error",ps),Br.load(),()=>{Br.removeEventListener("error",ps)}},[fe]);const mi=Br=>{const ps=Math.floor(Br/60),Or=Br%60;return`${ps}:${Or.toString().padStart(2,"0")}`},In=j==="screen"?"aspect-video":b&&O?"aspect-[9/16]":"aspect-video";return K?e.jsx("div",{className:zt("flex items-center justify-center bg-black rounded-lg",In,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):Q===!1?e.jsx("div",{className:zt("flex items-center justify-center bg-black rounded-lg",In,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(go,{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:Qe||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(q,{onClick:()=>js(),variant:"secondary",className:"w-full",children:[e.jsx(lo,{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:zt("flex flex-col gap-2",a),children:[!te&&!fe&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(q,{variant:j==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>N("camera"),children:[e.jsx(Tp,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(q,{variant:j==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>N("screen"),children:[e.jsx($E,{className:"h-4 w-4"}),"Screen"]})]}),j==="camera"&&!te&&!fe&&e.jsx(BBs,{value:qe,onChange:et,isLoading:ms,disabled:te}),!te&&!fe&&(Ze.length>0||ct.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[Ze.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(BE,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Ds,{value:kt||"default",onValueChange:Br=>St(Br==="default"?"":Br),children:[e.jsx(Ps,{className:"h-8 text-xs",children:e.jsx(Fs,{placeholder:"Default microphone"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"default",children:"Default microphone"}),Ze.map(Br=>e.jsx(lt,{value:Br.deviceId,children:Br.label||`Microphone ${Br.deviceId.slice(0,6)}`},Br.deviceId))]})]})]}),ct.length>1&&j==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Tp,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Ds,{value:Yt||"default",onValueChange:Br=>es(Br==="default"?"":Br),children:[e.jsx(Ps,{className:"h-8 text-xs",children:e.jsx(Fs,{placeholder:"Default camera"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"default",children:"Default camera"}),ct.map(Br=>e.jsx(lt,{value:Br.deviceId,children:Br.label||`Camera ${Br.deviceId.slice(0,6)}`},Br.deviceId))]})]})]})]}),j==="camera"&&b&&!te&&!fe&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(k_,{className:zt("h-4 w-4",O?"text-muted-foreground":"text-primary")}),e.jsx(ce,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(Rr,{id:"orientation-toggle",checked:O,onCheckedChange:Jt}),e.jsx(ce,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(yg,{className:zt("h-4 w-4",O?"text-primary":"text-muted-foreground")})]}),j==="screen"&&!te&&!fe&&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($E,{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:zt("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{$s()},children:[e.jsx("video",{ref:l,src:fe??void 0,className:zt("w-full bg-black",O&&!fe?"object-contain":"object-cover",In,!fe&&Me==="user"!==(qe.mirror??!1)&&"scale-x-[-1]",gt&&!fe&&"hidden"),playsInline:!0,controls:!!fe,muted:fe?$e:!0,autoPlay:!fe},fe??"live"),gt&&!fe&&e.jsx("canvas",{ref:zs,className:zt("w-full bg-black",O?"object-contain":"object-cover",In,Me==="user"!==(qe.mirror??!1)&&"scale-x-[-1]")}),gt&&ms&&!fe&&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(ls,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!fe&&nt&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(q,{type:"button",variant:"secondary",onClick:()=>void $s(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!fe&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Ge!==null&&!fe&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-30 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:Ge},Ge),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),te&&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:zt("w-3 h-3 rounded-full",ae?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[mi(xe)," / ",mi(s)]})]}),te&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(ki,{value:xe/s*100,className:"h-1 rounded-none"})}),!fe&&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(BE,{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:`${Ie}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:fe?e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:Yr,children:[e.jsx(lo,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(q,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:gs,children:Ve?e.jsx(Xf,{className:"h-5 w-5"}):e.jsx(Al,{className:"h-5 w-5"})}),e.jsxs(q,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:sa,children:[e.jsx(la,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[j==="camera"?e.jsx(q,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Fn,disabled:te||Ge!==null,children:e.jsx(ev,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!te&&Ge===null?e.jsx(q,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:j==="screen"?or:Er,children:j==="screen"?e.jsx($E,{className:"h-6 w-6"}):e.jsx(bn,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(q,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:ae?Gr:Sr,children:ae?e.jsx(Al,{className:"h-5 w-5"}):e.jsx(Xf,{className:"h-5 w-5"})}),e.jsx(q,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Js,children:e.jsx(C0,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function TUs({open:s,onOpenChange:t,onUploaded:r}){const{user:n}=Cs(),{toast:a}=Ba(),[i,l]=k.useState(!1),o=async(c,d)=>{if(n){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",m=`${n.id}/${crypto.randomUUID()}.${u}`,{error:f}=await U.storage.from("cma-videos").upload(m,c,{contentType:c.type||"video/webm",upsert:!1});if(f)throw f;const{data:x,error:y}=await U.storage.from("cma-videos").createSignedUrl(m,60*60*24*365*5);if(y||!(x!=null&&x.signedUrl))throw y||new Error("Could not sign video URL");r(x.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(vs,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(_s,{children:[e.jsx(bs,{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(ls,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(pM,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function EUs({value:s,onChange:t}){const{user:r}=Cs(),[n,a]=k.useState(!1);return e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(bn,{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(Pe,{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($r,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(Al,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(cM,{userId:r==null?void 0:r.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(q,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(bn,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(TUs,{open:n,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function m1(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function AUs({open:s,onOpenChange:t,subject:r,onSave:n,isSaving:a}){const[i,l]=k.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});k.useEffect(()=>{s&&l({bedrooms:(r==null?void 0:r.bedrooms)!=null?String(r.bedrooms):"",bathrooms:(r==null?void 0:r.bathrooms)!=null?String(r.bathrooms):"",sqft:(r==null?void 0:r.sqft)!=null?String(r.sqft):"",yearBuilt:(r==null?void 0:r.yearBuilt)!=null?String(r.yearBuilt):"",propertyType:(r==null?void 0:r.propertyType)||"Residential",propertySubType:(r==null?void 0:r.propertySubType)||"Single Family"})},[s,r]);const o=async()=>{await n({bedrooms:m1(i.bedrooms),bathrooms:m1(i.bathrooms),sqft:m1(i.sqft),yearBuilt:m1(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{className:"text-xs",children:"Beds"}),e.jsx(Ne,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Baths"}),e.jsx(Ne,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Sq Ft"}),e.jsx(Ne,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Year Built"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"Property Type"}),e.jsx(Ne,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Subtype"}),e.jsx(Ne,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs(q,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(ls,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function MUs({open:s,onOpenChange:t,subject:r,onAdd:n}){const[a,i]=k.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});k.useEffect(()=>{s&&i({address:"",city:(r==null?void 0:r.city)||"",state:(r==null?void 0:r.state)||"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""})},[s,r]);const l=()=>{const o=m1(a.price),c=m1(a.sqft);!a.address.trim()||!o||!c||(n({mlsNumber:`manual-${Date.now()}`,source_provider:"manual",manual:!0,selected:!0,score:100,address:a.address.trim(),city:a.city||(r==null?void 0:r.city)||"",state:(a.state||(r==null?void 0:r.state)||"").toUpperCase(),status:a.status||"Closed",price:o,soldPrice:/closed|sold/i.test(a.status)?o:null,bedrooms:m1(a.bedrooms),bathrooms:m1(a.bathrooms),sqft:c,yearBuilt:m1(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{className:"text-xs",children:"Address"}),e.jsx(Ne,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"City"}),e.jsx(Ne,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"State"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"Status"}),e.jsx(Ne,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Price"}),e.jsx(Ne,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Sq Ft"}),e.jsx(Ne,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Beds"}),e.jsx(Ne,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Baths"}),e.jsx(Ne,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Year Built"}),e.jsx(Ne,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs(q,{className:"w-full",onClick:l,disabled:!a.address.trim()||!m1(a.price)||!m1(a.sqft),children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function IUs(){var Oe,Ie,ze,Ve,Le,$e,ve;const{id:s}=xo(),t=qr(),{toast:r}=Ba(),{data:n,isLoading:a}=Jzs(s),{data:i}=eBs(s),l=tBs(),o=nBs(),c=aBs(),{leadSite:d,isLoading:u}=hf(),[m,f]=k.useState([]),[x,y]=k.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[_,b]=k.useState(null),[j,N]=k.useState(!1),[C,A]=k.useState({low:"",likely:"",high:"",note:""}),[E,D]=k.useState(!1),[R,F]=k.useState(!1),[O,B]=k.useState(!1),[K,Z]=k.useState(null),Q=async Qe=>{var Ce,qe;if(!n||!(Qe!=null&&Qe.address)||!(Qe!=null&&Qe.city)||!(Qe!=null&&Qe.state))return Qe;let we={...Qe};const nt=async et=>{const{data:Ze,error:rt}=await U.functions.invoke("cma-subject-lookup",{body:{address:et.address,city:et.city,state:et.state,zip:et.zip,latitude:et.latitude,longitude:et.longitude,leadSiteId:(d==null?void 0:d.id)??n.lead_site_id}});if(rt)throw rt;return(Ze==null?void 0:Ze.matches)||[]},Se=et=>{const rt=et.find(St=>Number.isFinite(Number(St.latitude))&&Number.isFinite(Number(St.longitude)))||et[0];if(!rt)return;const ct=typeof rt.match_type=="string"&&rt.match_type.startsWith("nearby-"),vt=ct&&Number.isFinite(Number(we.latitude))&&Number.isFinite(Number(we.longitude)),kt=St=>rt[St]!==void 0&&rt[St]!==null&&rt[St]!==""&&rt[St]!==0?rt[St]:we[St];we={...we,bedrooms:kt("bedrooms"),bathrooms:kt("bathrooms"),sqft:kt("sqft"),yearBuilt:kt("yearBuilt"),lotSize:kt("lotSize"),propertyType:kt("propertyType"),propertySubType:kt("propertySubType"),source_provider:rt.source_provider??we.source_provider,match_type:rt.match_type??we.match_type,matched_mls_address:ct?rt.address:we.matched_mls_address,latitude:vt?we.latitude:rt.latitude??we.latitude,longitude:vt?we.longitude:rt.longitude??we.longitude,mlsNumber:ct?we.mlsNumber:rt.mlsNumber??we.mlsNumber,photos:!ct&&Array.isArray(rt.photos)&&rt.photos.length?rt.photos:we.photos}};Se(await nt(we));const Ge=()=>Number.isFinite(Number(we.latitude))&&Number.isFinite(Number(we.longitude));if(!Ge()){const{data:et}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),Ze=et==null?void 0:et.value;if(Ze){const rt=encodeURIComponent(`${we.address}, ${we.city}, ${we.state} ${we.zip||""}`.trim()),vt=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${rt}.json?access_token=${Ze}&limit=1&country=us`)).json(),kt=(qe=(Ce=vt==null?void 0:vt.features)==null?void 0:Ce[0])==null?void 0:qe.center;Array.isArray(kt)&&kt.length===2&&(we.longitude=kt[0],we.latitude=kt[1])}}if((!we.bedrooms||!we.bathrooms||!we.sqft||!we.yearBuilt)&&Ge())try{Se(await nt(we))}catch(et){console.warn("second-pass subject lookup failed",et)}return JSON.stringify(we)!==JSON.stringify(Qe)&&await l.mutateAsync({id:n.id,patch:{subject:we}}),we};k.useEffect(()=>{var nt,Se;n!=null&&n.settings&&y({sqftPct:n.settings.sqftPct??.2,monthsBack:n.settings.monthsBack??6,maxMiles:n.settings.maxMiles??5,statuses:n.settings.statuses??["Active","Pending","Closed"]});const Qe=(nt=n==null?void 0:n.settings)==null?void 0:nt.priceOverride;Qe!=null&&Qe.enabled&&(N(!0),A({low:Qe.low!=null?String(Qe.low):"",likely:Qe.likely!=null?String(Qe.likely):"",high:Qe.high!=null?String(Qe.high):"",note:Qe.note??""}));const we=(Se=n==null?void 0:n.settings)==null?void 0:Se.personalVideo;we!=null&&we.url&&Z({url:we.url,thumb:we.thumb,label:we.label})},[n==null?void 0:n.id]);const W=k.useRef(!1);k.useEffect(()=>{W.current||i!=null&&i.length&&(f(i.map(Qe=>({...Qe.snapshot,selected:Qe.selected,manual:Qe.manual,score:Qe.score}))),W.current=!0)},[i]);const te=k.useRef(null);k.useEffect(()=>{if(!n||u)return;const Qe=n.subject||{},we=Number.isFinite(Number(Qe.latitude))&&Number.isFinite(Number(Qe.longitude)),nt=!!(Number(Qe.bedrooms)||Number(Qe.bathrooms)||Number(Qe.sqft)||Number(Qe.yearBuilt));if(we&&nt)return;const Se=`${n.id}:${(d==null?void 0:d.id)??n.lead_site_id??"no-site"}`;te.current!==Se&&(!Qe.address||!Qe.city||!Qe.state||(te.current=Se,(async()=>{try{await Q(Qe)}catch(Ge){console.warn("subject enrich failed",Ge)}})()))},[n==null?void 0:n.id,n==null?void 0:n.lead_site_id,d==null?void 0:d.id,u]);const ne=k.useMemo(()=>n?dWe(n.subject,m):null,[n,m]),ae=async()=>{if(n)try{const Qe=await Q(n.subject),we=await o.mutateAsync({subject:Qe,filters:x,leadSiteId:(d==null?void 0:d.id)??n.lead_site_id});f(we.comps.map(nt=>({...nt,selected:!0})).slice(0,12)),r({title:`Found ${we.comps.length} comps`,description:`Top ${Math.min(12,we.comps.length)} auto-selected.`})}catch(Qe){r({title:"Search failed",description:Qe.message,variant:"destructive"})}},ue=Qe=>{f(we=>we.map((nt,Se)=>Se===Qe?{...nt,selected:!nt.selected}:nt))},me=Qe=>{f(we=>we.filter((nt,Se)=>Se!==Qe))},de=async Qe=>{if(!n)return;const we=Object.fromEntries(Object.entries(Qe).filter(([,Se])=>Se!=null&&Se!=="")),nt={...n.subject,...we,manually_enriched:!0};await l.mutateAsync({id:n.id,patch:{subject:nt}}),r({title:"Subject details saved",description:nt.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},fe=Qe=>{f(we=>[{...Qe,selected:!0,manual:!0},...we]),r({title:"Manual comp added"})},je=async(Qe=!1)=>{if(!n)return;const we=dWe(n.subject,m),nt=qe=>{const et=Number(String(qe).replace(/[^0-9.]/g,""));return Number.isFinite(et)&&et>0?Math.round(et):null},Se=j?nt(C.likely):null,Ge=j?nt(C.low):null,We=j?nt(C.high):null,Ce=j&&Se;await l.mutateAsync({id:n.id,patch:{settings:{...x,priceOverride:{enabled:j,low:Ge,likely:Se,high:We,note:C.note||null},personalVideo:K},price_low:Ce?Ge??Se:we.low??null,price_likely:Ce?Se:we.likely??null,price_high:Ce?We??Se:we.high??null,status:Qe?"shared":n.status}}),await c.mutateAsync({cmaId:n.id,comps:m}),r({title:Qe?"CMA published":"CMA saved"})},xe=n?`https://cma.relevelup.com/${n.share_token}`:"";if(a||!n)return e.jsx(ws,{children:e.jsx("div",{className:"p-6",children:e.jsx(ls,{className:"w-6 h-6 animate-spin"})})});const Ee=m.filter(Qe=>Qe.selected).length,Me=!((Oe=n.subject)!=null&&Oe.bedrooms)||!((Ie=n.subject)!=null&&Ie.bathrooms)||!((ze=n.subject)!=null&&ze.sqft)||!((Ve=n.subject)!=null&&Ve.yearBuilt);return e.jsx(ws,{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(q,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(Aa,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{variant:"outline",onClick:()=>je(!1),disabled:l.isPending,children:[e.jsx(Ml,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(q,{onClick:()=>je(!0),disabled:l.isPending,children:[e.jsx(Ec,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),n.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(xe),r({title:"Link copied"})},children:[e.jsx(un,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(q,{onClick:()=>D(!0),children:[e.jsx(Ks,{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(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Subject Property"})}),e.jsxs(Pe,{className:"space-y-2 text-sm",children:[e.jsx("div",{className:"font-semibold",children:n.subject.address}),e.jsxs("div",{className:"text-muted-foreground",children:[n.subject.city,", ",n.subject.state," ",n.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:"})," ",n.subject.bedrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Baths:"})," ",n.subject.bathrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"SqFt:"})," ",((Le=n.subject.sqft)==null?void 0:Le.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",n.subject.yearBuilt??"—"]})]}),Me&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs(q,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>F(!0),children:[e.jsx(Ua,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!Me&&e.jsxs(q,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>F(!0),children:[e.jsx(Ua,{className:"w-3.5 h-3.5 mr-1"}),"Edit details"]}),!n.subject.sqft&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsx(ce,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(Ne,{type:"number",defaultValue:"",onBlur:async Qe=>{const we=Number(Qe.target.value);we>0&&await l.mutateAsync({id:n.id,patch:{subject:{...n.subject,sqft:we}}})}})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(__,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Pe,{className:"space-y-3",children:[ne!=null&&ne.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(j&&Number(C.likely)>0?Number(C.likely):ne.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",($e=ne.low)==null?void 0:$e.toLocaleString()," – $",(ve=ne.high)==null?void 0:ve.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",ne.ppsf,"/sqft median · ",Ee," 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(ce,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(Rr,{id:"override-toggle",checked:j,onCheckedChange:N})]}),j&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"My suggested price"}),e.jsx(Ne,{type:"number",placeholder:"e.g. 750000",value:C.likely,onChange:Qe=>A(we=>({...we,likely:Qe.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Range low"}),e.jsx(Ne,{type:"number",placeholder:"optional",value:C.low,onChange:Qe=>A(we=>({...we,low:Qe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Range high"}),e.jsx(Ne,{type:"number",placeholder:"optional",value:C.high,onChange:Qe=>A(we=>({...we,high:Qe.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(pr,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:C.note,onChange:Qe=>A(we=>({...we,note:Qe.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(EUs,{value:K,onChange:Z}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Filters"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(x.sqftPct*100),"%"]}),e.jsx(nf,{value:[x.sqftPct*100],min:5,max:50,step:5,onValueChange:([Qe])=>y(we=>({...we,sqftPct:Qe/100}))})]}),e.jsxs("div",{children:[e.jsxs(ce,{className:"text-xs",children:["Search radius: ",x.maxMiles," mi"]}),e.jsx(nf,{value:[x.maxMiles],min:1,max:25,step:1,onValueChange:([Qe])=>y(we=>({...we,maxMiles:Qe}))})]}),e.jsxs("div",{children:[e.jsxs(ce,{className:"text-xs",children:["Sold within: ",x.monthsBack," months"]}),e.jsx(nf,{value:[x.monthsBack],min:1,max:24,step:1,onValueChange:([Qe])=>y(we=>({...we,monthsBack:Qe}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Qe=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ri,{checked:x.statuses.includes(Qe),onCheckedChange:we=>y(nt=>({...nt,statuses:we?[...nt.statuses,Qe]:nt.statuses.filter(Se=>Se!==Qe)}))})," ",Qe]},Qe))]}),e.jsxs(q,{className:"w-full",onClick:ae,disabled:o.isPending,children:[o.isPending?e.jsx(ls,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(Ir,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(q,{variant:"outline",className:"w-full",onClick:()=>B(!0),children:[e.jsx(Ys,{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(OBs,{subject:n.subject,comps:m,radiusMiles:x.maxMiles,onMarkerClick:Qe=>b(Qe)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Comparables (",m.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ee," selected"]})]}),m.length?e.jsx("div",{className:"space-y-2",children:m.map((Qe,we)=>{var nt;return e.jsx(ke,{className:Qe.selected?"":"opacity-50",children:e.jsxs(Pe,{className:"p-3 flex gap-3 items-center",children:[e.jsx(Ri,{checked:Qe.selected,onCheckedChange:()=>ue(we)}),e.jsxs("button",{type:"button",onClick:()=>b(we),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(kme,{photos:Qe.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:Qe.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Qe.city,", ",Qe.state," · ",Qe.bedrooms??"?","bd/",Qe.bathrooms??"?","ba · ",((nt=Qe.sqft)==null?void 0:nt.toLocaleString())??"?"," sqft",Qe.yearBuilt?` · ${Qe.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(Xe,{variant:"outline",className:"mr-1",children:Qe.status}),Qe.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Qe.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Qe.soldPrice||Qe.price||0).toLocaleString()]}),Qe.sqft&&(Qe.soldPrice||Qe.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Qe.soldPrice||Qe.price)/Qe.sqft),"/sqft"]}):null]})]}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>b(we),title:"View details",children:e.jsx(Nn,{className:"w-4 h-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>me(we),title:"Remove",children:e.jsx(zr,{className:"w-4 h-4"})})]})},we)})}):e.jsx(ke,{children:e.jsx(Pe,{className:"py-12 text-center text-muted-foreground",children:e.jsxs("div",{className:"max-w-md mx-auto space-y-3",children:[e.jsxs("p",{children:["Click ",e.jsx("strong",{children:"Find Comps"})," to auto-pull from your MLS."]}),e.jsx("p",{className:"text-sm",children:"If nothing comes back, you are not stuck — use LevelUp's fallback template: enter the subject details, add 2–3 known comps, then set your suggested price."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[Me&&e.jsx(q,{variant:"outline",size:"sm",onClick:()=>F(!0),children:"Fill subject details"}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>B(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(_lt,{comp:_!=null?m[_]:null,open:_!=null,onClose:()=>b(null)}),e.jsx(AUs,{open:R,onOpenChange:F,subject:n.subject,onSave:de,isSaving:l.isPending}),e.jsx(MUs,{open:O,onOpenChange:B,subject:n.subject,onAdd:fe}),e.jsx(cyt,{open:E,onOpenChange:D,cma:n})]})})}function PUs(s,t,r,n){const a=d=>d*Math.PI/180,l=a(r-s),o=a(n-t),c=Math.sin(l/2)**2+Math.cos(a(s))*Math.cos(a(r))*Math.sin(o/2)**2;return 2*3958.8*Math.asin(Math.sqrt(c))}const h1t="popby_geocode_cache_v1";function LUs(){try{return JSON.parse(localStorage.getItem(h1t)||"{}")}catch{return{}}}function DUs(s){try{localStorage.setItem(h1t,JSON.stringify(s))}catch{}}function RUs({contacts:s,onLogPopby:t}){const[r,n]=k.useState(null),[a,i]=k.useState("idle"),[l,o]=k.useState(5),[c,d]=k.useState(""),[u,m]=k.useState(new Map),[f,x]=k.useState(!1);k.useEffect(()=>{(async()=>{const{data:N}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();N!=null&&N.value&&d(N.value)})()},[]);const y=k.useMemo(()=>s.filter(N=>N.isDue&&(N.address||N.city&&N.state||N.zip)),[s]),_=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(N=>{n({lat:N.coords.latitude,lng:N.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};k.useEffect(()=>{if(!c||!r||y.length===0)return;let N=!1;const C=LUs(),A=new Map;y.forEach(D=>{const R=[D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase();C[R]&&A.set(D.id,C[R])}),m(new Map(A));const E=y.filter(D=>!([D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase()in C));if(E.length!==0)return x(!0),(async()=>{const D=[...E],R=async()=>{var F,O;for(;D.length&&!N;){const B=D.shift(),K=[B.address,B.city,B.state,B.zip].filter(Boolean),Z=K.join("|").toLowerCase(),Q=K.join(", ");try{const te=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(Q)}.json?limit=1&access_token=${c}`)).json();if((O=(F=te==null?void 0:te.features)==null?void 0:F[0])!=null&&O.center){const[ne,ae]=te.features[0].center;C[Z]={lat:ae,lng:ne},A.set(B.id,{lat:ae,lng:ne})}else C[Z]=null}catch{}}};await Promise.all([R(),R(),R(),R()]),N||(DUs(C),m(new Map(A)),x(!1))})(),()=>{N=!0}},[c,r,y]);const b=k.useMemo(()=>{if(!r)return[];const N=[];return y.forEach(C=>{const A=u.get(C.id);if(!A)return;const E=PUs(r.lat,r.lng,A.lat,A.lng);E<=l&&N.push({...C,distanceMiles:E,lat:A.lat,lng:A.lng})}),N.sort((C,A)=>C.distanceMiles-A.distanceMiles)},[r,y,u,l]),j=N=>{const A=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${N.lat},${N.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${N.lat},${N.lng}`;window.open(A,"_blank","noopener")};return e.jsxs(ke,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(QI,{className:"h-5 w-5 text-primary"}),"Nearby Now"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Due contacts within driving distance — perfect for errand-day pop-bys."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ds,{value:String(l),onValueChange:N=>o(Number(N)),children:[e.jsx(Ps,{className:"w-[110px] h-9",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"2",children:"2 miles"}),e.jsx(lt,{value:"5",children:"5 miles"}),e.jsx(lt,{value:"10",children:"10 miles"}),e.jsx(lt,{value:"25",children:"25 miles"})]})]}),e.jsxs(q,{size:"sm",variant:a==="ok"?"outline":"default",onClick:_,disabled:a==="loading",children:[a==="loading"?e.jsx(lo,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(QI,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(Ma,{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(go,{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&&f&&b.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(dr,{className:"h-14 w-full"}),e.jsx(dr,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!f&&b.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."]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Xe,{variant:"secondary",className:"font-medium",children:[b.length," nearby"]}),f&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(lo,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:b.map(N=>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:[N.first_name," ",N.last_name]}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:N.distanceMiles<1?`${(N.distanceMiles*5280).toFixed(0)} ft`:`${N.distanceMiles.toFixed(1)} mi`}),N.daysOverdue>0&&e.jsxs(Xe,{variant:"destructive",className:"text-xs",children:[N.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[N.address,N.city,N.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[N.phone&&e.jsx(q,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${N.phone}`,children:e.jsx(Mn,{className:"h-4 w-4"})})}),e.jsx(q,{size:"icon",variant:"ghost",onClick:()=>j(N),className:"h-9 w-9",title:"Directions",children:e.jsx(FF,{className:"h-4 w-4"})}),e.jsxs(q,{size:"sm",onClick:()=>t(N),children:[e.jsx(Di,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},N.id))})]})]})]})}const OUs="0dde5abb-0005-4c8c-a471-30d0cbc9e280",FUs=[{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 zUs(){const s=qr(),t=V0t(),{data:r}=$9s(),{data:n}=H0(),{data:a}=o6e(),{data:i}=bye(90),{data:l}=Lp(),o=G9s(),c=V9s(),d=q9s(),u=H9s(),{data:m=[],isLoading:f}=pt({queryKey:["popby-templates"],queryFn:async()=>{const{data:te,error:ne}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",OUs).order("publish_date",{ascending:!1});if(ne)throw ne;const{data:ae}=await U.from("template_likes").select("template_id"),{data:ue}=await U.from("template_comments").select("template_id"),me=new Map;ae==null||ae.forEach(fe=>{me.set(fe.template_id,(me.get(fe.template_id)||0)+1)});const de=new Map;return ue==null||ue.forEach(fe=>{de.set(fe.template_id,(de.get(fe.template_id)||0)+1)}),(te||[]).map(fe=>({...fe,likesCount:me.get(fe.id)||0,commentsCount:de.get(fe.id)||0}))}}),x=te=>{const ne=l==null?void 0:l.find(ae=>ae.id===te);return ne?`${ne.first_name} ${ne.last_name||""}`.trim():"Unknown"},y=te=>{if(!te)return null;const ne=r==null?void 0:r.find(ae=>ae.id===te);return(ne==null?void 0:ne.name)||null},[_,b]=k.useState(null),[j,N]=k.useState(!1),[C,A]=k.useState(!1),[E,D]=k.useState(!1),[R,F]=k.useState({popby_item_id:"",notes:""}),[O,B]=k.useState({name:"",description:""}),K=async()=>{_&&(await c.mutateAsync({contact_id:_.id,popby_item_id:R.popby_item_id||void 0,notes:R.notes||void 0}),N(!1),b(null),F({popby_item_id:"",notes:""}))},Z=async()=>{O.name.trim()&&(await d.mutateAsync({name:O.name.trim(),description:O.description.trim()||void 0}),D(!1),B({name:"",description:""}))},Q=async(te,ne)=>{await u.mutateAsync({relationship_type_id:te,frequency_days:parseInt(ne)})},W=te=>{var ae;const ne=a==null?void 0:a.find(ue=>ue.relationship_type_id===te);return((ae=ne==null?void 0:ne.frequency_days)==null?void 0:ae.toString())||"90"};return e.jsx(ws,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:o.thisWeekCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Week"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-emerald-500",children:o.thisMonthCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Month"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-amber-500",children:o.dueCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Due Now"})]})})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(q,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(Ma,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(q,{variant:"outline",onClick:()=>A(!0),children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(q,{variant:"outline",onClick:()=>D(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(ta,{defaultValue:"due",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"due",children:"Due for Popby"}),e.jsx(rs,{value:"activity",children:"Recent Activity"}),e.jsx(rs,{value:"library",children:"Popby Library"}),e.jsx(rs,{value:"templates",children:"Popby Templates"})]}),e.jsxs(fs,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(RUs,{contacts:t||[],onLogPopby:te=>{b(te),N(!0)}}),!t||t.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Di,{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(te=>e.jsx(ke,{className:"hover:shadow-md transition-shadow",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[te.first_name," ",te.last_name]}),te.daysOverdue>0&&e.jsxs(Xe,{variant:"destructive",className:"text-xs",children:[te.daysOverdue,"+ days overdue"]}),te.daysSinceLastPopby===null&&e.jsx(Xe,{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:[te.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ma,{className:"h-3 w-3"}),te.city||te.address]}),te.tags&&te.tags.length>0&&e.jsx("span",{children:te.tags.map(ne=>{var ae;return(ae=ne.relationship_type)==null?void 0:ae.name}).join(", ")})]}),te.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",As(new Date(te.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[te.phone&&e.jsx(q,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${te.phone}`,children:e.jsx(Mn,{className:"h-4 w-4"})})}),e.jsxs(q,{size:"sm",onClick:()=>{b(te),N(!0)},children:[e.jsx(Ti,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},te.id))})]}),e.jsx(fs,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(jn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby activity yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Start logging popbys to see your history here."})]})}):e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Pe,{className:"space-y-3",children:i.map(te=>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(Di,{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:x(te.contact_id)}),y(te.popby_item_id)&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:y(te.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:As(new Date(te.completed_at),"MMM d, yyyy h:mm a")}),te.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:te.notes})]})]},te.id))})]})}),e.jsx(fs,{value:"library",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[r==null?void 0:r.map(te=>e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Di,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:te.name}),te.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:te.description}),!te.owner_user_id&&e.jsx(Xe,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},te.id)),e.jsx(ke,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>D(!0),children:e.jsx(Pe,{className:"p-4 flex items-center justify-center h-full min-h-[100px]",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ys,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(fs,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length," template",m.length!==1?"s":""," found"]}),f&&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((te,ne)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(dr,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(dr,{className:"h-5 w-3/4 mb-2"}),e.jsx(dr,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(dr,{className:"h-5 w-16"}),e.jsx(dr,{className:"h-5 w-20"})]})]})},ne))}),!f&&m.length===0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(yc,{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."})]})}),!f&&m.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:m.map(te=>e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${te.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:te.preview_image_url?e.jsx("img",{src:te.preview_image_url,alt:te.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})}),e.jsxs(Pe,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:te.name}),te.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:x9(te.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(Xe,{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(wm,{className:"h-3.5 w-3.5"}),te.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gc,{className:"h-3.5 w-3.5"}),te.commentsCount]})]}),e.jsxs(q,{size:"sm",className:"w-full gap-2",onClick:ne=>{ne.stopPropagation(),s(`/templates/${te.id}`)},children:[e.jsx(un,{className:"h-4 w-4"}),"View Template"]})]})]},te.id))})]})]}),e.jsx(vs,{open:j,onOpenChange:N,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsxs(bs,{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(ce,{children:"Popby Item (optional)"}),e.jsxs(Ds,{value:R.popby_item_id,onValueChange:te=>F(ne=>({...ne,popby_item_id:te})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a popby item..."})}),e.jsx(Ls,{children:r==null?void 0:r.map(te=>e.jsx(lt,{value:te.id,children:te.name},te.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Notes (optional)"}),e.jsx(pr,{placeholder:"Any notes about this popby...",value:R.notes,onChange:te=>F(ne=>({...ne,notes:te.target.value}))})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>N(!1),children:"Cancel"}),e.jsx(q,{onClick:K,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(vs,{open:C,onOpenChange:A,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),n==null?void 0:n.map(te=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(ce,{className:"font-medium",children:te.name}),e.jsxs(Ds,{value:W(te.id),onValueChange:ne=>Q(te.id,ne),children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:FUs.map(ne=>e.jsx(lt,{value:ne.value,children:ne.label},ne.value))})]})]},te.id))]}),e.jsx(fn,{children:e.jsx(q,{onClick:()=>A(!1),children:"Done"})})]})}),e.jsx(vs,{open:E,onOpenChange:D,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Name *"}),e.jsx(Ne,{placeholder:"e.g., Homemade cookies",value:O.name,onChange:te=>B(ne=>({...ne,name:te.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{placeholder:"Optional description...",value:O.description,onChange:te=>B(ne=>({...ne,description:te.target.value}))})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(q,{onClick:Z,disabled:!O.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const BUs=tw({property_address:ho().min(1,"Property address is required"),city:ho().optional(),state:ho().optional(),zip:ho().optional(),transaction_type:_Te(["buyer","seller"]),close_date:ho().min(1,"Close date is required"),sale_price:m7().min(0,"Sale price must be positive"),commission_amount:m7().optional(),lead_source_id:ho().optional(),client_type_id:ho().optional(),contact_id:ho().optional(),notes:ho().optional(),is_win:j$t()});function m1t({open:s,onOpenChange:t,transaction:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,u]=k.useState(""),m=Oge(),f=sJt(),{data:x}=I8(),{data:y}=H0(),{data:_}=Lp(),b=Dge(),j=jEe(),{data:N}=Fge(),C=(N==null?void 0:N.show_commission)??!0,A=Tge({resolver:Ege(BUs),defaultValues:{property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1}});k.useEffect(()=>{r?A.reset({property_address:r.property_address,city:r.city||"",state:r.state||"",zip:r.zip||"",transaction_type:r.transaction_type,close_date:r.close_date,sale_price:Number(r.sale_price),commission_amount:r.commission_amount?Number(r.commission_amount):void 0,lead_source_id:r.lead_source_id||void 0,client_type_id:r.client_type_id||void 0,contact_id:r.contact_id||void 0,notes:r.notes||"",is_win:r.is_win}):A.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[r,A]);const E=async O=>{const B={property_address:O.property_address,transaction_type:O.transaction_type,close_date:O.close_date,sale_price:O.sale_price,is_win:O.is_win,commission_amount:O.commission_amount||null,lead_source_id:O.lead_source_id||null,client_type_id:O.client_type_id||null,contact_id:O.contact_id||null,city:O.city||null,state:O.state||null,zip:O.zip||null,notes:O.notes||null};r?await f.mutateAsync({id:r.id,...B}):await m.mutateAsync(B),t(!1)},D=async()=>{if(!i.trim())return;const[O,...B]=i.trim().split(" "),K=B.join(" ")||null,Z=await b.mutateAsync({first_name:O,last_name:K,tagIds:[]});Z&&(A.setValue("contact_id",Z.id),l(""),c(!1),a(!1))},R=async()=>{if(!d.trim())return;const O=await j.mutateAsync(d.trim());O&&(A.setValue("lead_source_id",O.id),u(""))},F=_==null?void 0:_.find(O=>O.id===A.watch("contact_id"));return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(_s,{children:e.jsx(bs,{children:r?"Edit Transaction":"Add Transaction"})}),e.jsx(ui,{className:"max-h-[70vh] pr-4",children:e.jsx(Age,{...A,children:e.jsxs("form",{onSubmit:A.handleSubmit(E),className:"space-y-4",children:[e.jsx(au,{control:A.control,name:"property_address",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Property Address *"}),e.jsx($d,{children:e.jsx(Ne,{placeholder:"123 Main St",...O})}),e.jsx(wx,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(au,{control:A.control,name:"city",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"City"}),e.jsx($d,{children:e.jsx(Ne,{placeholder:"City",...O})})]})}),e.jsx(au,{control:A.control,name:"state",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"State"}),e.jsx($d,{children:e.jsx(Ne,{placeholder:"TX",...O})})]})}),e.jsx(au,{control:A.control,name:"zip",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Zip"}),e.jsx($d,{children:e.jsx(Ne,{placeholder:"75001",...O})})]})})]}),e.jsx(au,{control:A.control,name:"transaction_type",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Transaction Type *"}),e.jsxs(Ds,{onValueChange:O.onChange,value:O.value,children:[e.jsx($d,{children:e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select type"})})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"buyer",children:"Buyer"}),e.jsx(lt,{value:"seller",children:"Seller"})]})]}),e.jsx(wx,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(au,{control:A.control,name:"close_date",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Close Date *"}),e.jsx($d,{children:e.jsx(Ne,{type:"date",...O})}),e.jsx(wx,{})]})}),e.jsx(au,{control:A.control,name:"sale_price",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Sale Price *"}),e.jsx($d,{children:e.jsx(Ne,{type:"number",placeholder:"0",...O,onChange:B=>O.onChange(Number(B.target.value))})}),e.jsx(wx,{})]})})]}),C&&e.jsx(au,{control:A.control,name:"commission_amount",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Commission"}),e.jsx($d,{children:e.jsx(Ne,{type:"number",placeholder:"0",...O,value:O.value??"",onChange:B=>O.onChange(B.target.value?Number(B.target.value):void 0)})})]})}),e.jsx(au,{control:A.control,name:"lead_source_id",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Lead Source"}),e.jsxs(Ds,{onValueChange:O.onChange,value:O.value||"",children:[e.jsx($d,{children:e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select source"})})}),e.jsx(Ls,{children:x==null?void 0:x.map(B=>e.jsx(lt,{value:B.id,children:B.name},B.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Add custom source...",value:d,onChange:O=>u(O.target.value),className:"flex-1"}),e.jsx(q,{type:"button",variant:"outline",size:"icon",onClick:R,disabled:!d.trim(),children:e.jsx(Ys,{className:"h-4 w-4"})})]}),e.jsx(au,{control:A.control,name:"client_type_id",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Client Type"}),e.jsxs(Ds,{onValueChange:O.onChange,value:O.value||"",children:[e.jsx($d,{children:e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select client type"})})}),e.jsx(Ls,{children:y==null?void 0:y.map(B=>e.jsx(lt,{value:B.id,children:B.name},B.id))})]})]})}),e.jsx(au,{control:A.control,name:"contact_id",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Client Contact"}),e.jsxs(sl,{open:n,onOpenChange:a,children:[e.jsx(rl,{asChild:!0,children:e.jsx($d,{children:e.jsxs(q,{variant:"outline",role:"combobox",className:zt("w-full justify-between",!O.value&&"text-muted-foreground"),children:[F?`${F.first_name} ${F.last_name||""}`.trim():"Select contact",e.jsx(xg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Ko,{className:"w-full p-0",align:"start",children:[e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search contacts..."}),e.jsxs(kg,{children:[e.jsx(Sg,{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(q,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(Cg,{children:_==null?void 0:_.map(B=>e.jsxs(Sp,{value:`${B.first_name} ${B.last_name||""}`,onSelect:()=>{O.onChange(B.id),a(!1)},children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",B.id===O.value?"opacity-100":"opacity-0")}),B.first_name," ",B.last_name||""]},B.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(Ne,{placeholder:"Enter contact name...",value:i,onChange:B=>l(B.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{size:"sm",onClick:D,disabled:!i.trim()||b.isPending,children:"Add Contact"}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(au,{control:A.control,name:"notes",render:({field:O})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Notes"}),e.jsx($d,{children:e.jsx(pr,{placeholder:"Any notes about this transaction...",...O})})]})}),e.jsx(au,{control:A.control,name:"is_win",render:({field:O})=>e.jsxs(zd,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Bd,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx($d,{children:e.jsx(Rr,{checked:O.value,onCheckedChange:O.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:m.isPending||f.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}function aIe({transactions:s,showCommission:t,isLoading:r,agentNameMap:n,readOnly:a}){const[i,l]=k.useState(null),[o,c]=k.useState(null),[d,u]=k.useState(""),[m,f]=k.useState("all"),[x,y]=k.useState("all"),[_,b]=k.useState("all"),[j,N]=k.useState(!1),C=rJt(),A=Oge(),{data:E}=I8();H0();const D=rD(),R=B=>{const{id:K,created_at:Z,updated_at:Q,lead_source:W,client_type:te,contact:ne,...ae}=B;A.mutate(ae)},F=()=>{o&&(C.mutate(o),c(null))},O=s.filter(B=>{var ne,ae,ue,me;const K=d===""||B.property_address.toLowerCase().includes(d.toLowerCase())||((ae=(ne=B.contact)==null?void 0:ne.first_name)==null?void 0:ae.toLowerCase().includes(d.toLowerCase()))||((me=(ue=B.contact)==null?void 0:ue.last_name)==null?void 0:me.toLowerCase().includes(d.toLowerCase())),Z=m==="all"||B.transaction_type===m,Q=x==="all"||B.lead_source_id===x,W=_==="all"||B.client_type_id===_,te=!j||B.is_win;return K&&Z&&Q&&W&&te});return r?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 space-y-4",children:[1,2,3].map(B=>e.jsx(dr,{className:"h-16 w-full"},B))})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs(Dt,{children:["Transactions (",O.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search...",value:d,onChange:B=>u(B.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(Ds,{value:m,onValueChange:f,children:[e.jsx(Ps,{className:"w-[100px]",children:e.jsx(Fs,{placeholder:"Type"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),e.jsx(lt,{value:"buyer",children:"Buyer"}),e.jsx(lt,{value:"seller",children:"Seller"})]})]}),e.jsxs(Ds,{value:x,onValueChange:y,children:[e.jsx(Ps,{className:"w-[130px]",children:e.jsx(Fs,{placeholder:"Lead Source"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Sources"}),E==null?void 0:E.map(B=>e.jsx(lt,{value:B.id,children:B.name},B.id))]})]}),e.jsxs(q,{variant:j?"default":"outline",size:"sm",onClick:()=>N(!j),children:[e.jsx(Uc,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Pe,{children:O.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):D?e.jsx("div",{className:"space-y-3",children:O.map(B=>e.jsxs(ke,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:B.property_address}),B.is_win&&e.jsx(Uc,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[B.city,B.state?`, ${B.state}`:""]})]}),e.jsx(Xe,{variant:B.transaction_type==="buyer"?"default":"secondary",children:B.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: "}),MOe(B.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),nd(B.sale_price)]}),t&&B.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),nd(B.commission_amount)]}),B.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),B.lead_source.name]}),B.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),B.contact.first_name," ",B.contact.last_name]}),n&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),n[B.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>l(B),children:e.jsx(iu,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>R(B),children:e.jsx(si,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>c(B.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})]},B.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[n&&e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Property"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Close Date"}),e.jsx(At,{children:"Sale Price"}),t&&e.jsx(At,{children:"Commission"}),e.jsx(At,{children:"Lead Source"}),e.jsx(At,{children:"Client"}),!a&&e.jsx(At,{className:"w-[50px]"})]})}),e.jsx(ha,{children:O.map(B=>{var K;return e.jsxs(Ws,{children:[n&&e.jsx(xt,{className:"font-medium text-sm",children:n[B.owner_user_id]||"Unknown"}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[B.is_win&&e.jsx(Uc,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:B.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[B.city,B.state?`, ${B.state}`:""]})]})]})}),e.jsx(xt,{children:e.jsx(Xe,{variant:B.transaction_type==="buyer"?"default":"secondary",children:B.transaction_type})}),e.jsx(xt,{children:MOe(B.close_date)}),e.jsx(xt,{children:nd(B.sale_price)}),t&&e.jsx(xt,{children:B.commission_amount?nd(B.commission_amount):"-"}),e.jsx(xt,{children:((K=B.lead_source)==null?void 0:K.name)||"-"}),e.jsx(xt,{children:B.contact?`${B.contact.first_name} ${B.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(xt,{children:e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",children:e.jsx(Fy,{className:"h-4 w-4"})})}),e.jsxs(Sd,{align:"end",children:[e.jsxs(ti,{onClick:()=>l(B),children:[e.jsx(iu,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ti,{onClick:()=>R(B),children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(ti,{onClick:()=>c(B.id),className:"text-destructive",children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},B.id)})})]})})})]}),e.jsx(m1t,{open:!!i,onOpenChange:B=>!B&&l(null),transaction:i||void 0}),e.jsx(el,{open:!!o,onOpenChange:B=>!B&&c(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete Transaction?"}),e.jsx(Ho,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:F,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function f1t({goals:s,stats:t,year:r,showCommission:n}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===r?a:12,l=12-i,o=(f,x)=>{if(!x||x===0)return null;const y=Math.min(f/x*100,100),_=Math.max(x-f,0),b=l>0?_/l:0,j=i/12*100,N=y>=j?"ahead":y>=j*.8?"on-track":"behind";return{percent:y,remaining:_,pace:b,status:N}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=n?o(t.totalCommission,s.gci_goal):null,m=f=>{switch(f){case"ahead":return e.jsxs(Xe,{className:"bg-green-500 text-white",children:[e.jsx(Wo,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(Xe,{variant:"secondary",children:[e.jsx(N_,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(Xe,{variant:"destructive",children:[e.jsx(E_,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hu,{className:"h-5 w-5 text-primary"}),e.jsxs(Dt,{children:[r," Goals Progress"]})]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.transactions_goal&&c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),m(c.status)]}),e.jsx(ki,{value:c.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[t.totalTransactions," of ",s.transactions_goal]}),e.jsxs("span",{children:[Math.round(c.percent),"%"]})]}),c.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(c.pace),"/month to hit goal"]})]}),s.volume_goal&&d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Volume"}),m(d.status)]}),e.jsx(ki,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[nd(t.totalVolume,!0)," of ",nd(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 ",nd(d.pace,!0),"/month"]})]}),n&&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"}),m(u.status)]}),e.jsx(ki,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[nd(t.totalCommission,!0)," of ",nd(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 ",nd(u.pace,!0),"/month"]})]})]})})]})}const $Us={light:"",dark:".dark"},p1t=k.createContext(null);function x1t(){const s=k.useContext(p1t);if(!s)throw new Error("useChart must be used within a ");return s}const g1t=k.forwardRef(({id:s,className:t,children:r,config:n,...a},i)=>{const l=k.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(p1t.Provider,{value:{config:n},children:e.jsxs("div",{"data-chart":o,ref:i,className:zt("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(UUs,{id:o,config:n}),e.jsx(AP,{children:r})]})})});g1t.displayName="Chart";const UUs=({id:s,config:t})=>{const r=Object.entries(t).filter(([n,a])=>a.theme||a.color);return r.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries($Us).map(([n,a])=>` ${a} [data-chart=${s}] { ${r.map(([i,l])=>{var c;const o=((c=l.theme)==null?void 0:c[n])||l.color;return o?` --color-${i}: ${o};`:null}).join(` `)} } `).join(` `)}}):null},y1t=k.forwardRef(({active:s,payload:t,className:r,indicator:n="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:m,labelKey:f},x)=>{const{config:y}=x1t(),_=k.useMemo(()=>{var E;if(a||!(t!=null&&t.length))return null;const[j]=t,N=`${f||j.dataKey||j.name||"value"}`,C=ICe(y,j,N),A=!f&&typeof l=="string"?((E=y[l])==null?void 0:E.label)||l:C==null?void 0:C.label;return o?e.jsx("div",{className:zt("font-medium",c),children:o(A,t)}):A?e.jsx("div",{className:zt("font-medium",c),children:A}):null},[l,o,t,a,c,y,f]);if(!s||!(t!=null&&t.length))return null;const b=t.length===1&&n!=="dot";return e.jsxs("div",{ref:x,className:zt("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",r),children:[b?null:_,e.jsx("div",{className:"grid gap-1.5",children:t.map((j,N)=>{const C=`${m||j.name||j.dataKey||"value"}`,A=ICe(y,j,C),E=u||j.payload.fill||j.color;return e.jsx("div",{className:zt("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",n==="dot"&&"items-center"),children:d&&(j==null?void 0:j.value)!==void 0&&j.name?d(j.value,j.name,j,N,j.payload):e.jsxs(e.Fragment,{children:[A!=null&&A.icon?e.jsx(A.icon,{}):!i&&e.jsx("div",{className:zt("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":n==="dot","w-1":n==="line","w-0 border-[1.5px] border-dashed bg-transparent":n==="dashed","my-0.5":b&&n==="dashed"}),style:{"--color-bg":E,"--color-border":E}}),e.jsxs("div",{className:zt("flex flex-1 justify-between leading-none",b?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[b?_: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)})})]})});y1t.displayName="ChartTooltip";const qUs=k.forwardRef(({className:s,hideIcon:t=!1,payload:r,verticalAlign:n="bottom",nameKey:a},i)=>{const{config:l}=x1t();return r!=null&&r.length?e.jsx("div",{ref:i,className:zt("flex items-center justify-center gap-4",n==="top"?"pb-3":"pt-3",s),children:r.map(o=>{const c=`${a||o.dataKey||"value"}`,d=ICe(l,o,c);return e.jsxs("div",{className:zt("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});qUs.displayName="ChartLegend";function ICe(s,t,r){if(typeof t!="object"||t===null)return;const n="payload"in t&&typeof t.payload=="object"&&t.payload!==null?t.payload:void 0;let a=r;return r in t&&typeof t[r]=="string"?a=t[r]:n&&r in n&&typeof n[r]=="string"&&(a=n[r]),a in s?s[a]:s[r]}const AV=["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 iIe({stats:s,year:t}){const r=s.transactionsByMonth.some(a=>a.count>0),n=s.leadSourceBreakdown.length>0;return!r&&!n?e.jsx(ke,{children:e.jsx(Pe,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[r&&e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Pe,{className:"overflow-hidden",children:e.jsx(g1t,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(AP,{width:"100%",height:"100%",children:e.jsxs(L0t,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(g0t,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(FA,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(zA,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(rg,{content:e.jsx(y1t,{})}),e.jsx(M2,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Pe,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(AP,{width:"100%",height:"100%",children:e.jsxs(D0t,{children:[e.jsx(dw,{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(KB,{fill:AV[i%AV.length]},`cell-${i}`))}),e.jsx(rg,{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:AV[i%AV.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function VUs(s){if(!s||!s.trim())return null;const t=s.trim(),r=["yyyy-MM-dd","M/d/yyyy","MM/dd/yyyy","M-d-yyyy","MM-dd-yyyy","MM/dd/yy","M/d/yy"];for(const n of r)try{const a=hTe(t,n,new Date);if(ZNe(a))return As(a,"yyyy-MM-dd")}catch{}try{const n=new Date(t);if(ZNe(n))return As(n,"yyyy-MM-dd")}catch{}return null}const HUs=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function GUs({open:s,onOpenChange:t}){const[r,n]=k.useState([]),[a,i]=k.useState(!1),[l,o]=k.useState(0),{data:c}=I8(),{data:d}=H0(),u=Oge(),m=()=>{const j=HUs.join(","),N=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),C=`${j} ${N}`,A=new Blob([C],{type:"text/csv"}),E=URL.createObjectURL(A),D=document.createElement("a");D.href=E,D.download="transaction-import-template.csv",D.click(),URL.revokeObjectURL(E)},f=j=>{const N=j.split(` `).filter(A=>A.trim());if(N.length<2)return[];const C=N[0].split(",").map(A=>A.trim().toLowerCase().replace(/['"]/g,""));return N.slice(1).map((A,E)=>{var ae,ue,me,de;const D=[];let R="",F=!1;for(const fe of A)fe==='"'?F=!F:fe===","&&!F?(D.push(R.trim()),R=""):R+=fe;D.push(R.trim());const O=fe=>{var xe;const je=C.indexOf(fe);return je>=0?(xe=D[je])==null?void 0:xe.replace(/^["']|["']$/g,"").trim():""},B=(ae=O("transaction_type"))==null?void 0:ae.toLowerCase(),K=(ue=O("sale_price"))==null?void 0:ue.replace(/[$,]/g,""),Z=(me=O("commission_amount"))==null?void 0:me.replace(/[$,]/g,""),Q=(de=O("is_win"))==null?void 0:de.toLowerCase(),W=O("close_date"),te=VUs(W);let ne;return O("property_address")?["buyer","seller"].includes(B)?te?(!K||isNaN(Number(K)))&&(ne="Invalid sale price"):ne=`Invalid date format: "${W}" - use MM/DD/YYYY or YYYY-MM-DD`:ne='Transaction type must be "buyer" or "seller"':ne="Missing property address",{property_address:O("property_address"),city:O("city"),state:O("state"),zip:O("zip"),transaction_type:B==="seller"?"seller":"buyer",close_date:te||"",sale_price:Number(K)||0,commission_amount:Z?Number(Z):null,lead_source_name:O("lead_source"),client_type_name:O("client_type"),is_win:["yes","true","1"].includes(Q),notes:O("notes"),error:ne}})},x=j=>{var A;const N=(A=j.target.files)==null?void 0:A[0];if(!N)return;const C=new FileReader;C.onload=E=>{var F;const D=(F=E.target)==null?void 0:F.result,R=f(D);n(R)},C.readAsText(N)},y=async()=>{const j=r.filter(A=>!A.error);if(j.length===0){he.error("No valid transactions to import");return}i(!0),o(0);let N=0,C=0;for(let A=0;AF.name.toLowerCase()===E.lead_source_name.toLowerCase()),R=d==null?void 0:d.find(F=>F.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:(D==null?void 0:D.id)||null,client_type_id:(R==null?void 0:R.id)||null,contact_id:null,notes:E.notes||null,is_win:E.is_win}),N++}catch(D){C++,console.error("Failed to import transaction:",D)}o(Math.round((A+1)/j.length*100))}i(!1),N>0&&he.success(`Imported ${N} transaction${N>1?"s":""}`),C>0&&he.error(`Failed to import ${C} transaction${C>1?"s":""}`),n([]),t(!1)},_=r.filter(j=>!j.error).length,b=r.filter(j=>j.error).length;return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Import Transactions"}),e.jsx(an,{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(q,{variant:"outline",onClick:m,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(Ne,{id:"csv-file",type:"file",accept:".csv",onChange:x})]}),r.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Xe,{variant:"outline",children:[r.length," rows found"]}),_>0&&e.jsxs(Xe,{className:"bg-green-500 text-white",children:[e.jsx(la,{className:"h-3 w-3 mr-1"}),_," valid"]}),b>0&&e.jsxs(Xe,{variant:"destructive",children:[e.jsx(go,{className:"h-3 w-3 mr-1"}),b," errors"]})]}),e.jsx(ui,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((j,N)=>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(Xe,{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(jAe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(NAe,{className:"text-xs",children:j.error})})]},N)),r.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:y,disabled:_===0||a,children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Import ",_," Transaction",_!==1?"s":""]})]})]})]})})}const WUs=tw({transactions_goal:m7().min(0).optional(),volume_goal:m7().min(0).optional(),gci_goal:m7().min(0).optional()});function KUs({open:s,onOpenChange:t,year:r,existingGoals:n}){const a=nJt(),{data:i}=Fge(),l=(i==null?void 0:i.show_commission)??!0,o=Tge({resolver:Ege(WUs),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});k.useEffect(()=>{n?o.reset({transactions_goal:n.transactions_goal??void 0,volume_goal:n.volume_goal?Number(n.volume_goal):void 0,gci_goal:n.gci_goal?Number(n.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[n,o,s]);const c=async d=>{await a.mutateAsync({year:r,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{children:[r," Goals"]}),e.jsx(an,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(Age,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(au,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Transactions Goal"}),e.jsx($d,{children:e.jsx(Ne,{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(Yue,{children:"Total number of deals you want to close"}),e.jsx(wx,{})]})}),e.jsx(au,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"Volume Goal ($)"}),e.jsx($d,{children:e.jsx(Ne,{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(Yue,{children:"Total sales volume you want to achieve"}),e.jsx(wx,{})]})}),l&&e.jsx(au,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(zd,{children:[e.jsx(Bd,{children:"GCI Goal ($)"}),e.jsx($d,{children:e.jsx(Ne,{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(Yue,{children:"Gross commission income target"}),e.jsx(wx,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function oIe({transactions:s,isLoading:t}){const r=k.useRef(null),n=k.useRef(null),a=k.useRef([]),i=k.useRef(null),{isAdmin:l}=Cs(),[o,c]=k.useState(""),[d,u]=k.useState(!0),[m,f]=k.useState(0),[x,y]=k.useState(!1),_=s.filter(j=>j.latitude!=null&&j.longitude!=null),b=s.filter(j=>j.latitude==null||j.longitude==null);return k.useEffect(()=>{(async()=>{u(!0);try{const{data:N}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();N!=null&&N.value&&c(N.value)}catch(N){console.error("Error fetching mapbox token:",N)}u(!1)})()},[]),k.useEffect(()=>{if(!o||b.length===0||x)return;(async()=>{var C;y(!0);let N=0;for(const A of b){const E=[A.property_address,A.city,A.state,A.zip].filter(Boolean).join(", ");if(E)try{const R=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(E)}.json?access_token=${o}&limit=1`)).json();if((C=R.features)!=null&&C[0]){const[F,O]=R.features[0].center;await U.from("scorecard_transactions").update({latitude:O,longitude:F}).eq("id",A.id),A.latitude=O,A.longitude=F,N++}}catch(D){console.error("Geocode error:",D)}}f(N),y(!1)})()},[o,s]),k.useEffect(()=>{if(!r.current||!o||n.current)return;ol.accessToken=o;const j=s.filter(A=>A.latitude!=null&&A.longitude!=null);let N=[-98.5795,39.8283],C=4;if(j.length>0){const A=j.reduce((D,R)=>D+R.longitude,0)/j.length,E=j.reduce((D,R)=>D+R.latitude,0)/j.length;N=[A,E],C=j.length===1?12:10}return n.current=new ol.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:C,center:N}),n.current.addControl(new ol.NavigationControl,"top-right"),()=>{var A;(A=n.current)==null||A.remove(),n.current=null}},[o]),k.useEffect(()=>{var N;if(!n.current||!o)return;a.current.forEach(C=>C.remove()),a.current=[],(N=i.current)==null||N.remove();const j=s.filter(C=>C.latitude!=null&&C.longitude!=null);if(j.forEach(C=>{var O;const A=C.transaction_type==="buyer",E=A?"#3B82F6":"#10B981",D=document.createElement("div");D.className="cursor-pointer",D.innerHTML=`
${A?'':''}
`;const R=new ol.Popup({offset:25,closeButton:!0}).setHTML(`
${C.property_address}
${C.city?`
${C.city}${C.state?", "+C.state:""} ${C.zip||""}
`:""}
${A?"Buyer":"Seller"} $${Number(C.sale_price).toLocaleString()}
Closed: ${El(C.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(O=C.lead_source)!=null&&O.name?" · "+C.lead_source.name:""}
${C.contact?`
Client: ${C.contact.first_name} ${C.contact.last_name||""}
`:""}
`),F=new ol.Marker(D).setLngLat([C.longitude,C.latitude]).setPopup(R).addTo(n.current);a.current.push(F)}),j.length>1){const C=new ol.LngLatBounds;j.forEach(A=>C.extend([A.longitude,A.latitude])),n.current.fitBounds(C,{padding:60,maxZoom:13})}else j.length===1&&n.current.flyTo({center:[j[0].longitude,j[0].latitude],zoom:12})},[s,o,x]),d||t?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center h-[50vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Ma,{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",x&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(go,{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 v1t=()=>{const{data:s}=uv();return pt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:r}=await U.from("team_members").select("user_id").eq("team_id",s.teamId);if(r)throw r;const n=t.map(l=>l.user_id),{data:a,error:i}=await U.from("profiles").select("id, name, email, avatar_url").in("id",n);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},YUs=s=>{const{data:t}=uv(),{data:r}=v1t();return pt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const n=r.map(o=>o.id);let a=U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",n).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:!!r&&r.length>0})};function ZUs(s,t){const r=t.filter(i=>i.owner_user_id===s.id),n=r.reduce((i,l)=>i+Number(l.sale_price),0),a=r.reduce((i,l)=>i+(Number(l.commission_amount)||0),0);return{member:s,totalTransactions:r.length,buyerCount:r.filter(i=>i.transaction_type==="buyer").length,sellerCount:r.filter(i=>i.transaction_type==="seller").length,totalVolume:n,averagePrice:r.length>0?n/r.length:0,totalGCI:a}}function XUs(s,t){return s?s.split(" ").map(r=>r[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function QUs({year:s}){var f;const{data:t,isLoading:r}=v1t(),{data:n,isLoading:a}=YUs(s),i=qr(),l=r||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:m}=k.useMemo(()=>{if(!t||!n)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const x=t.map(B=>ZUs(B,n));x.sort((B,K)=>K.totalVolume-B.totalVolume);const y={};t.forEach(B=>{y[B.id]=B.name||B.email});const _=n.length,b=n.reduce((B,K)=>B+Number(K.sale_price),0),j=n.reduce((B,K)=>B+(Number(K.commission_amount)||0),0),N=n.filter(B=>B.transaction_type==="buyer").length,C=n.filter(B=>B.transaction_type==="seller").length,A={};n.forEach(B=>{var Z;const K=((Z=B.lead_source)==null?void 0:Z.name)||"Unknown";A[K]=(A[K]||0)+1});const E=Object.entries(A).sort((B,K)=>K[1]-B[1])[0],D={};n.forEach(B=>{const K=El(B.close_date).toLocaleString("default",{month:"short"});D[K]=(D[K]||0)+1});const F=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(B=>({month:B,count:D[B]||0})),O=Object.entries(A).map(([B,K])=>({name:B,count:K})).sort((B,K)=>K.count-B.count);return{aggregate:{totalTxns:_,buyerCount:N,sellerCount:C,totalVolume:b,avgPrice:_>0?b/_:0,totalGCI:j,topSource:E?{name:E[0],count:E[1]}:null,memberCount:t.length},memberStats:x,topPerformer:x[0]||null,agentNameMap:y,teamChartStats:{transactionsByMonth:F,leadSourceBreakdown:O}}},[t,n]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(x=>e.jsx(dr,{className:"h-24"},x))}),e.jsx(dr,{className:"h-64"})]}):!o||c.length===0?e.jsx(ke,{className:"py-12",children:e.jsxs(Pe,{className:"text-center space-y-2",children:[e.jsx(Dr,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),e.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",s,"."]})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.memberCount})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.totalTxns}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.buyerCount,"B / ",o.sellerCount,"S"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Xl,{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:nd(o.totalVolume,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Wo,{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:nd(o.avgPrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Xl,{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:nd(o.totalGCI,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Uc,{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:((f=o.topSource)==null?void 0:f.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(ke,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Pe,{className:"pt-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:e.jsx(wo,{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:nd(d.totalVolume,!0)})]})]})}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Member Performance"})}),e.jsx(Pe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{className:"text-center",children:"Transactions"}),e.jsx(At,{className:"text-center",children:"B / S"}),e.jsx(At,{className:"text-right",children:"Volume"}),e.jsx(At,{className:"text-right",children:"Avg Price"}),e.jsx(At,{className:"text-right",children:"GCI"}),e.jsx(At,{className:"text-right"})]})}),e.jsx(ha,{children:c.map((x,y)=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[y===0&&x.totalTransactions>0&&e.jsx(wo,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:x.member.avatar_url||void 0}),e.jsx(Kn,{className:"text-xs",children:XUs(x.member.name,x.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:x.member.name||x.member.email}),x.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:x.member.email})]})]})}),e.jsx(xt,{className:"text-center font-semibold",children:x.totalTransactions}),e.jsxs(xt,{className:"text-center text-sm",children:[x.buyerCount," / ",x.sellerCount]}),e.jsx(xt,{className:"text-right font-medium",children:nd(x.totalVolume,!0)}),e.jsx(xt,{className:"text-right text-sm",children:nd(x.averagePrice,!0)}),e.jsx(xt,{className:"text-right font-medium",children:nd(x.totalGCI,!0)}),e.jsx(xt,{className:"text-right",children:e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${x.member.id}`),children:e.jsx(Nn,{className:"h-4 w-4"})})})]},x.member.id))})]})})})]}),e.jsxs(ta,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"transactions",children:[e.jsx(Zf,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(rs,{value:"charts",children:[e.jsx(Mo,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(rs,{value:"map",children:[e.jsx(Ma,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(fs,{value:"transactions",children:e.jsx(aIe,{transactions:n||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(fs,{value:"charts",children:m&&e.jsx(iIe,{stats:m,year:s})}),e.jsx(fs,{value:"map",children:e.jsx(oIe,{transactions:n||[],isLoading:a})})]})]})}const uhe=new Date().getFullYear(),vKe=Array.from({length:10},(s,t)=>uhe-t),MV="all";function JUs(){var Z;const[s,t]=k.useState(uhe),r=s===null?MV:String(s),n=Q=>t(Q===MV?null:Number(Q)),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,m]=k.useState(!1),[f,x]=k.useState("my"),{data:y}=uv(),_=(y==null?void 0:y.role)==="team_leader",{data:b,isLoading:j}=NEe(s??void 0),{yearStats:N,lifetimeStats:C,isLoading:A,showCommission:E}=Wct(s??void 0),{data:D,isLoading:R}=Gct(s??uhe),{data:F}=Fge(),O=aJt(),B=()=>{if(!b||b.length===0)return;const Q=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...E?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],W=b.map(me=>{var de,fe;return[me.property_address,me.city||"",me.state||"",me.zip||"",me.transaction_type,me.close_date,me.sale_price,...E?[me.commission_amount||""]:[],((de=me.lead_source)==null?void 0:de.name)||"",((fe=me.client_type)==null?void 0:fe.name)||"",me.contact?`${me.contact.first_name} ${me.contact.last_name||""}`.trim():"",me.is_win?"Yes":"No",me.notes||""]}),te=[Q,...W].map(me=>me.map(de=>`"${String(de).replace(/"/g,'""')}"`).join(",")).join(` `),ne=new Blob([te],{type:"text/csv"}),ae=URL.createObjectURL(ne),ue=document.createElement("a");ue.href=ae,ue.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,ue.click(),URL.revokeObjectURL(ae)},K=!b||b.length===0;return e.jsxs(ws,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),_&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(q,{variant:f==="my"?"default":"ghost",size:"sm",onClick:()=>x("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(q,{variant:f==="team"?"default":"ghost",size:"sm",onClick:()=>x("team"),className:"h-8",children:[e.jsx(Dr,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),f==="team"&&_?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),e.jsxs(Ds,{value:r,onValueChange:n,children:[e.jsx(Ps,{className:"w-[140px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:MV,children:"All Years"}),vKe.map(Q=>e.jsx(lt,{value:String(Q),children:Q},Q))]})]})]}),e.jsx(QUs,{year:s??void 0})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ds,{value:r,onValueChange:n,children:[e.jsx(Ps,{className:"w-[140px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:MV,children:"All Years"}),vKe.map(Q=>e.jsx(lt,{value:String(Q),children:Q},Q))]})]}),e.jsx(q,{variant:"outline",size:"icon",onClick:()=>m(!u),children:e.jsx(Bo,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsx(Dt,{className:"text-lg",children:"Settings"})}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ce,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(Rr,{checked:(F==null?void 0:F.show_commission)??!0,onCheckedChange:Q=>O.mutate({show_commission:Q})})]})})]}),K&&!j?e.jsx(ke,{className:"py-12",children:e.jsxs(Pe,{className:"text-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Mo,{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(q,{onClick:()=>i(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(q,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(ka,{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(q,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(li,{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(q,{onClick:()=>i(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(q,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(Hu,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(q,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(q,{variant:"outline",onClick:B,disabled:K,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(q,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:N.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[C.totalTransactions," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Dr,{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:[N.buyerCount,"/",N.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Xl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:nd(N.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[nd(C.totalVolume,!0)," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Wo,{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:nd(N.averagePrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Uc,{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=N.topLeadSource)==null?void 0:Z.name)||"-"}),N.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N.topLeadSource.count," deals"]})]})}),E&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Xl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:nd(N.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[nd(C.totalCommission,!0)," lifetime"]})]})}),E&&N.totalNetToAgent>0&&N.totalNetToAgent!==N.totalCommission&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[e.jsx(Xl,{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:nd(N.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[nd(C.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&D&&e.jsx(f1t,{goals:D,stats:N,year:s,showCommission:E}),e.jsxs(ta,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"transactions",children:"Transactions"}),e.jsx(rs,{value:"charts",children:"Charts"}),e.jsxs(rs,{value:"map",children:[e.jsx(Ma,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(fs,{value:"transactions",children:e.jsx(aIe,{transactions:b||[],showCommission:E,isLoading:j})}),e.jsx(fs,{value:"charts",children:e.jsx(iIe,{stats:N,year:s??void 0})}),e.jsx(fs,{value:"map",children:e.jsx(oIe,{transactions:b||[],isLoading:j})})]})]})]})]}),e.jsx(m1t,{open:a,onOpenChange:i}),e.jsx(GUs,{open:l,onOpenChange:o}),e.jsx(KUs,{open:c,onOpenChange:d,year:s??uhe,existingGoals:D})]})}function b1t({open:s,onOpenChange:t,listingId:r,listingSlug:n,listingTitle:a}){const{user:i}=Cs(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,m]=k.useState(!1);k.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:b,error:j}=await U.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",r).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(j)throw j;if(b&&b.share_token)o(b);else if(b&&!b.share_token){const{data:N,error:C}=await U.from("listing_shares").update({share_type:"referral_link"}).eq("id",b.id).select("id, share_token, click_count, lead_count").single();if(C)throw C;o(N)}else{const{data:N,error:C}=await U.from("listing_shares").insert({listing_id:r,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(C)throw C;o(N)}}catch(b){console.error("Error creating share link:",b),he.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,r]);const f=l!=null&&l.share_token?`https://listings.relevelup.com/${n||r}?ref=${l.share_token}`:"",x=async()=>{try{await navigator.clipboard.writeText(f),m(!0),he.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{he.error("Failed to copy link")}},y=_=>{const b=encodeURIComponent(f),j=encodeURIComponent(`Check out this listing: ${a}`);switch(_){case"email":window.open(`mailto:?subject=${j}&body=${b}`);break;case"text":window.open(`sms:?body=${j}%20${b}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${b}`,"_blank");break}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(an,{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(ce,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:c?"Generating...":f,readOnly:!0,className:"font-mono text-sm"}),e.jsx(q,{onClick:x,disabled:c||!f,variant:u?"default":"outline",children:u?e.jsx(la,{className:"h-4 w-4"}):e.jsx(si,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{variant:"outline",className:"flex-1",onClick:()=>y("email"),disabled:c,children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(q,{variant:"outline",className:"flex-1",onClick:()=>y("text"),disabled:c,children:[e.jsx(Ui,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(q,{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(ce,{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(Nn,{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(Dr,{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 eqs={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"},tqs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},sqs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function rqs({listing:s,onClick:t,onEdit:r,onDelete:n,onCreateMusicVideo:a,showActions:i}){var b,j;const{user:l}=Cs(),{data:o}=Bct(s.id),c=zct(),[d,u]=k.useState(!1),m=N=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(N),f=((b=s.photos)==null?void 0:b.find(N=>N.is_primary))||((j=s.photos)==null?void 0:j[0]),x=(l==null?void 0:l.id)===s.agent_id,y=async N=>{N.stopPropagation();try{const C=await c.mutateAsync(s.id);he.success(C.saved?"Listing saved!":"Listing removed from saved")}catch{he.error("Failed to save listing")}},_=N=>{if(N.stopPropagation(),l)u(!0);else{const C=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(C),he.success("Link copied to clipboard!")}};return e.jsxs(ke,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:t,children:[e.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[f?e.jsx("img",{src:f.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(C0,{className:"h-12 w-12"})}),e.jsx(Xe,{className:`absolute top-2 left-2 ${eqs[s.status]} text-white border-0`,children:tqs[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(fa,{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(q,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:y,children:e.jsx(yi,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx(q,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:_,title:x?"Copy link":"Share & earn leads",children:x?e.jsx(Ec,{className:"h-4 w-4"}):e.jsx(Ir,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(b1t,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xl font-bold text-primary",children:m(s.price)}),s.open_to_referrals&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:[e.jsx(Dr,{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(Ma,{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(k0,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(of,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(C0,{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(Xe,{variant:"secondary",className:"text-xs",children:sqs[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(Nn,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ec,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yi,{className:"h-3 w-3"}),s.save_count]})]}),i&&(r||n||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&e.jsxs(q,{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:N=>{N.stopPropagation(),a()},children:[e.jsx(rP,{className:"h-4 w-4"}),"Music Video"]}),r&&e.jsxs(q,{variant:"outline",size:"sm",className:"flex-1",onClick:N=>{N.stopPropagation(),r()},children:[e.jsx(iu,{className:"h-4 w-4 mr-2"}),"Edit"]}),n&&e.jsx(q,{variant:"destructive",size:"sm",onClick:N=>{N.stopPropagation(),n()},children:e.jsx(zr,{className:"h-4 w-4"})})]})]})]})}const lIe="lu_listing_selection_v1",Upe=24,qpe=new Set;function _1t(){try{return JSON.parse(sessionStorage.getItem(lIe)||"{}")}catch{return{}}}function mje(s){try{sessionStorage.setItem(lIe,JSON.stringify(s))}catch{}qpe.forEach(t=>t())}let Tj=_1t();function nqs(){Tj=_1t(),qpe.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===lIe&&nqs()});const hk={getSnapshot:()=>Tj,subscribe(s){return qpe.add(s),()=>qpe.delete(s)},toggle(s){const t={...Tj};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=Upe)return!1;t[s.mlsNumber]=s}return Tj=t,mje(t),!0},remove(s){const t={...Tj};delete t[s],Tj=t,mje(t)},clear(){Tj={},mje({})},has(s){return!!Tj[s]},all(){return Object.values(Tj)}};function w1t(){const s=k.useSyncExternalStore(hk.subscribe,hk.getSnapshot,hk.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:hk.toggle,remove:hk.remove,clear:hk.clear}}const aqs=new Set(["office_exclusive","coming_soon","pre_market"]);function iqs(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),r=s.status||"active",n=aqs.has(r);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:r,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:n?null:`https://listings.relevelup.com/${s.slug||s.id}`,is_private:n}}function IV(s){const{has:t}=w1t(),r=`lx-${s.listing.id}`,n=t(r);return e.jsxs("div",{className:"relative",children:[e.jsx(rqs,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),hk.toggle(iqs(s.listing))||he.error(`You can select up to ${Upe} listings`)},title:n?"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 ${n?"bg-primary text-primary-foreground border-primary":"bg-white/95 text-foreground border-white hover:bg-white"}`,children:n?e.jsx(la,{className:"h-4 w-4"}):e.jsx(Ks,{className:"h-4 w-4"})})]})}function oqs({open:s,onOpenChange:t,listings:r}){const{user:n}=Cs(),{leadSite:a}=hf(),[i,l]=k.useState("grid"),[o,c]=k.useState(""),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(new Set),[_,b]=k.useState(!1),[j,N]=k.useState(!1),{data:C}=pye(),[A,E]=k.useState(!1);k.useEffect(()=>{!s||!(n!=null&&n.id)||U.from("gmail_integrations").select("gmail_email").eq("user_id",n.id).maybeSingle().then(({data:te})=>N(!!(te!=null&&te.gmail_email)))},[s,n==null?void 0:n.id]),k.useEffect(()=>{if(s){if(!o){const te=Array.from(new Set(r.map(ae=>ae.city).filter(Boolean))),ne=te.length===1?` in ${te[0]}`:"";c(r.length===1?`New listing for you${ne}`:`${r.length} hand-picked listings${ne}`)}d||u(`Hi {{first_name}}, Thought of you — I just picked a few properties I think you'll love. Take a look and let me know if anything catches your eye. Happy to set up a private showing whenever works.`)}},[s]);const{data:D=[],isLoading:R}=pt({queryKey:["send-listings-contacts",n==null?void 0:n.id],queryFn:async()=>{const{data:te}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, city").eq("owner_user_id",n.id).not("email","is",null).neq("email","").order("first_name");return te||[]},enabled:!!(n!=null&&n.id)&&s}),{data:F}=pt({queryKey:["send-listings-suggestions",r.map(te=>te.mlsNumber).join(",")],queryFn:async()=>{const{data:te,error:ne}=await U.functions.invoke("listing-email-suggestions",{body:{listings:r.map(ae=>({mlsNumber:ae.mlsNumber,city:ae.city,state:ae.state,price:ae.price,bedrooms:ae.bedrooms,bathrooms:ae.bathrooms}))}});if(ne)throw ne;return te},enabled:s&&r.length>0}),O=(F==null?void 0:F.suggestions)||[],B=k.useMemo(()=>{const te=m.trim().toLowerCase();return te?D.filter(ne=>`${ne.first_name??""} ${ne.last_name??""} ${ne.email} ${ne.city??""}`.toLowerCase().includes(te)):D},[D,m]),K=te=>{y(ne=>{const ae=new Set(ne);return ae.has(te)?ae.delete(te):ae.add(te),ae})},Z=()=>{y(te=>{const ne=new Set(te);return O.forEach(ae=>ne.add(ae.contact_id)),ne})},Q=r.length>0&&r.every(te=>te.mlsNumber.startsWith("lx-")),W=async()=>{if(!Q&&!(a!=null&&a.id)){he.error("You need an active lead site to send listings.");return}if(!o.trim())return he.error("Subject is required");if(x.size===0)return he.error("Pick at least one recipient");if(!j&&C&&!C.hasVerifiedSes){E(!0);return}const te=D.filter(ne=>x.has(ne.id)).map(ne=>({contact_id:ne.id,email:ne.email,first_name:ne.first_name,last_name:ne.last_name}));b(!0);try{const{data:ne,error:ae}=await U.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:r.map(ue=>({mlsNumber:ue.mlsNumber,address:ue.address,city:ue.city,state:ue.state,zip:ue.zip,price:ue.price,bedrooms:ue.bedrooms,bathrooms:ue.bathrooms,sqft:ue.sqft,status:ue.status,photos:(ue.photos||[]).slice(0,1),description:ue.description||"",external_url:ue.externalUrl||null,is_private:ue.is_private===!0})),recipients:te}});if(ae)throw ae;if(!(ne!=null&&ne.success))throw new Error((ne==null?void 0:ne.error)||"Send failed");he.success(`Sent ${ne.sent}/${te.length} via ${j?"Gmail":"Amazon SES"}${ne.failed?` · ${ne.failed} failed`:""}`),hk.clear(),y(new Set),t(!1)}catch(ne){he.error((ne==null?void 0:ne.message)||"Failed to send")}finally{b(!1)}};return e.jsxs(vs,{open:s,onOpenChange:t,children:[e.jsxs(ys,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(_s,{className:"px-6 pt-6 pb-2",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-primary"}),"Email ",r.length," ",r.length===1?"Listing":"Listings"]}),e.jsx(an,{children:Q?"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(ce,{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:r.map(te=>{var ne;return e.jsxs("div",{className:"shrink-0 w-32 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("div",{className:"h-20 w-full bg-muted",children:((ne=te.photos)==null?void 0:ne[0])&&e.jsx("img",{src:te.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:["$",(te.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[te.city,", ",te.state]})]})]},te.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(ce,{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(Ep,{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(zo,{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(ce,{htmlFor:"subject",children:"Subject"}),e.jsx(Ne,{id:"subject",value:o,onChange:te=>c(te.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"intro",children:"Personal message"}),e.jsx(pr,{id:"intro",value:d,onChange:te=>u(te.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:[O.length>0&&e.jsxs(ke,{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(Ir,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[O.length," smart ",O.length===1?"match":"matches"]})]}),e.jsx(q,{size:"sm",variant:"outline",onClick:Z,children:"Add all"})]}),e.jsx(ui,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:O.slice(0,12).map(te=>{const ne=x.has(te.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(Ri,{checked:ne,onCheckedChange:()=>K(te.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[te.first_name," ",te.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",te.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:te.reason})]})]},te.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ce,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",B.length,")"]}),x.size>0&&e.jsxs(Xe,{variant:"secondary",children:[x.size," selected"]})]}),e.jsx(Ne,{placeholder:"Search contacts…",value:m,onChange:te=>f(te.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(ui,{className:"h-full",children:R?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):B.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:B.map(te=>{const ne=x.has(te.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(Ri,{checked:ne,onCheckedChange:()=>K(te.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[te.first_name," ",te.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[te.email,te.city&&e.jsxs(e.Fragment,{children:[" · ",te.city]})]})]})]},te.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:x.size})," recipients"]}),x.size>0&&e.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>y(new Set),children:[e.jsx($r,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(fn,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsx(q,{onClick:W,disabled:_||x.size===0,children:_?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Send to ",x.size," ",x.size===1?"contact":"contacts"]})})]})]}),e.jsx(xye,{open:A,onOpenChange:E,hasPending:!!(C!=null&&C.hasPendingSes),pendingEmails:C==null?void 0:C.pendingEmails})]})}function lqs(){const{selected:s,count:t,remove:r,clear:n}=w1t(),[a,i]=k.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>=Upe?"Max reached":`Pick up to ${Upe}`})]})]}),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:()=>r(l.mlsNumber),className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center transition",children:e.jsx($r,{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(q,{variant:"ghost",size:"sm",onClick:n,className:"gap-1.5",children:[e.jsx(zr,{className:"h-4 w-4"})," Clear"]}),e.jsxs(q,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(hn,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(oqs,{open:a,onOpenChange:i,listings:s})]})}const cqs=[{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"}],dqs=[{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 uqs({filters:s,onFiltersChange:t,onClose:r}){const n=()=>{t({sortBy:"newest"})};return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Dt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:n,children:"Clear All"}),e.jsx(q,{variant:"ghost",size:"icon",onClick:r,children:e.jsx($r,{className:"h-4 w-4"})})]})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Status"}),e.jsxs(Ds,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"All statuses"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Statuses"}),cqs.map(a=>e.jsx(lt,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Property Type"}),e.jsxs(Ds,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"All types"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),dqs.map(a=>e.jsx(lt,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Min Price"}),e.jsx(Ne,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:a=>t({...s,minPrice:a.target.value?Number(a.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Max Price"}),e.jsx(Ne,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:a=>t({...s,maxPrice:a.target.value?Number(a.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(Rr,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function hqs({leaderboard:s}){const t=n=>{switch(n){case 0:return e.jsx(wo,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(c2,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Uc,{className:"h-5 w-5 text-amber-700"});default:return e.jsx("span",{className:"text-sm font-medium text-muted-foreground w-5 text-center",children:n+1})}},r=(n,a)=>!n||n.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No data yet. Start sharing to climb the leaderboard!"}):e.jsx("div",{className:"space-y-2",children:n.map((i,l)=>e.jsxs("div",{className:`flex items-center gap-4 p-3 rounded-lg ${l===0?"bg-gradient-to-r from-amber-500/10 to-amber-500/5 border border-amber-500/20":"bg-muted/50"}`,children:[e.jsx("div",{className:"flex items-center justify-center w-8",children:t(l)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-medium truncate",children:i.name})}),e.jsxs(Xe,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(wo,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-emerald-500/10 to-emerald-500/5 border border-emerald-500/20",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-emerald-500/20 flex items-center justify-center",children:e.jsx(Ec,{className:"h-6 w-6 text-emerald-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Listing Amplifier"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share 10+ listings"})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-sky-500/10 to-sky-500/5 border border-sky-500/20",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-sky-500/20 flex items-center justify-center",children:e.jsx(Pn,{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(c2,{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(wo,{className:"h-6 w-6 text-amber-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Community MVP"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Top performer"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Community Leaderboard"})}),e.jsx(Pe,{children:e.jsxs(ta,{defaultValue:"sharers",children:[e.jsxs(ea,{className:"w-full",children:[e.jsxs(rs,{value:"sharers",className:"flex-1",children:[e.jsx(Ec,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(rs,{value:"listers",className:"flex-1",children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(fs,{value:"sharers",className:"mt-4",children:r(s==null?void 0:s.topSharers,"shares")}),e.jsx(fs,{value:"listers",className:"mt-4",children:r(s==null?void 0:s.topListers,"listings")})]})})]})]})}const bKe={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},_Ke={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 mqs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function fqs({listings:s,isLoading:t}){const r=qr(),n=k.useRef(null),a=k.useRef(null),i=k.useRef([]),{isAdmin:l}=Cs(),[o,c]=k.useState(""),[d,u]=k.useState(!0),[m,f]=k.useState(!1),x=s.filter(_=>_.latitude!=null&&_.longitude!=null),y=s.filter(_=>(_.latitude==null||_.longitude==null)&&(_.property_address||_.city));return k.useEffect(()=>{(async()=>{u(!0);try{const{data:b}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&c(b.value)}catch(b){console.error("Error fetching mapbox token:",b)}u(!1)})()},[]),k.useEffect(()=>{if(!o||y.length===0||m)return;(async()=>{var b;f(!0);for(const j of y){const N=[j.property_address,j.city,j.state].filter(Boolean).join(", ");if(N)try{const A=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(N)}.json?access_token=${o}&limit=1`)).json();if((b=A.features)!=null&&b[0]){const[E,D]=A.features[0].center;await U.from("listings").update({latitude:D,longitude:E}).eq("id",j.id),j.latitude=D,j.longitude=E}}catch(C){console.error("Geocode error:",C)}}f(!1)})()},[o,s]),k.useEffect(()=>{if(!n.current||!o||a.current)return;ol.accessToken=o;const _=s.filter(N=>N.latitude!=null&&N.longitude!=null);let b=[-98.5795,39.8283],j=4;if(_.length>0){const N=_.reduce((A,E)=>A+E.longitude,0)/_.length,C=_.reduce((A,E)=>A+E.latitude,0)/_.length;b=[N,C],j=_.length===1?12:10}return a.current=new ol.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:j,center:b}),a.current.addControl(new ol.NavigationControl,"top-right"),()=>{var N;(N=a.current)==null||N.remove(),a.current=null}},[o]),k.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(b=>b.remove()),i.current=[];const _=s.filter(b=>b.latitude!=null&&b.longitude!=null);if(_.forEach(b=>{var D,R,F;const j=bKe[b.status]||"#10B981",N=((D=b.photos)==null?void 0:D.find(O=>O.is_primary))||((R=b.photos)==null?void 0:R[0]),C=document.createElement("div");C.className="cursor-pointer",C.innerHTML=`
`;const A=new ol.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${N!=null&&N.photo_url?``:""}
${mqs(b.price)}
${b.property_address||""}
${b.city}, ${b.state}
${_Ke[b.status]||b.status} ${b.bedrooms?`${b.bedrooms} bed`:""} ${b.bathrooms?`${b.bathrooms} bath`:""}
${(F=b.agent)!=null&&F.name?`
Listed by ${b.agent.name}
`:""}
Click to view details →
`),E=new ol.Marker(C).setLngLat([b.longitude,b.latitude]).setPopup(A).addTo(a.current);i.current.push(E)}),_.length>1){const b=new ol.LngLatBounds;_.forEach(j=>b.extend([j.longitude,j.latitude])),a.current.fitBounds(b,{padding:60,maxZoom:13})}else _.length===1&&a.current.flyTo({center:[_[0].longitude,_[0].latitude],zoom:12})},[s,o,m]),k.useEffect(()=>(window.__navigateToListing__=_=>{r(`/mission-control/listings/${_}`)},()=>{delete window.__navigateToListing__}),[r]),d||t?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center h-[60vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Ma,{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(bKe).map(([_,b])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:b}}),e.jsx("span",{className:"text-xs",children:_Ke[_]})]},_)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[x.length," of ",s.length," mapped",m&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(go,{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 PCe="homereel_mv_prefill",LCe="homereel_mv_badge_default";function j1t(s){try{sessionStorage.setItem(PCe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(LCe,JSON.stringify(s.badge))}catch{}}function par(){try{const s=sessionStorage.getItem(PCe);return s?(sessionStorage.removeItem(PCe),JSON.parse(s)):null}catch{return null}}function xar(){try{const s=sessionStorage.getItem(LCe);return s?(sessionStorage.removeItem(LCe),JSON.parse(s)):null}catch{return null}}function N1t(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 pqs(){var O,B,K,Z,Q,W,te,ne;const s=qr(),{brokerageId:t}=Cs(),{data:r,isLoading:n}=Dct(),[a,i]=k.useState("feed"),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,m]=k.useState({sortBy:"newest"}),{data:f,isLoading:x}=Rct({...u,city:c||u.city}),{data:y,isLoading:_}=$Qt(),{data:b,isLoading:j}=Oct(),{data:N,isLoading:C}=HQt(),{data:A,isLoading:E}=KQt(),{data:D}=WQt(),R=Fct(),F=async ae=>{if(confirm("Are you sure you want to delete this listing? This action cannot be undone."))try{await R.mutateAsync(ae),he.success("Listing deleted successfully")}catch{he.error("Failed to delete listing")}};return n?e.jsx(ws,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):r?e.jsxs(ws,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs(q,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Pn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(f==null?void 0:f.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(yi,{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(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(SE,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(Dr,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((O=N==null?void 0:N.sent)==null?void 0:O.length)||0)+(((B=N==null?void 0:N.received)==null?void 0:B.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(ta,{value:a,onValueChange:i,children:[e.jsxs(ea,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(rs,{value:"feed",children:"Community Feed"}),t&&e.jsx(rs,{value:"brokerage",children:"Brokerage"}),e.jsx(rs,{value:"my-listings",children:"My Listings"}),e.jsx(rs,{value:"saved",children:"Saved"}),e.jsx(rs,{value:"referrals",children:"Referrals"}),e.jsx(rs,{value:"map",children:"Map"}),e.jsx(rs,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(fs,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by city or neighborhood...",value:c,onChange:ae=>d(ae.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:u.sortBy,onValueChange:ae=>m({...u,sortBy:ae}),children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{placeholder:"Sort by"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"newest",children:"Newest First"}),e.jsx(lt,{value:"updated",children:"Recently Updated"}),e.jsx(lt,{value:"price_asc",children:"Price: Low to High"}),e.jsx(lt,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(q,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(C1,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(uqs,{filters:u,onFiltersChange:m,onClose:()=>o(!1)}),x?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((ae,ue)=>e.jsxs(ke,{children:[e.jsx(dr,{className:"h-48 w-full"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[e.jsx(dr,{className:"h-5 w-3/4"}),e.jsx(dr,{className:"h-4 w-1/2"}),e.jsx(dr,{className:"h-4 w-1/4"})]})]},ue))}):(f==null?void 0:f.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(Pn,{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(q,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ys,{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:f==null?void 0:f.map(ae=>e.jsx(IV,{listing:ae,onClick:()=>s(`/mission-control/listings/${ae.id}`)},ae.id))})]}),e.jsx(fs,{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((ae,ue)=>e.jsxs(ke,{children:[e.jsx(dr,{className:"h-48 w-full"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[e.jsx(dr,{className:"h-5 w-3/4"}),e.jsx(dr,{className:"h-4 w-1/2"})]})]},ue))}):(b==null?void 0:b.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(SE,{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(q,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b==null?void 0:b.map(ae=>e.jsx(IV,{listing:ae,showActions:!0,onClick:()=>s(`/mission-control/listings/${ae.id}`),onEdit:()=>s(`/mission-control/listings/${ae.id}/edit`),onDelete:()=>F(ae.id),onCreateMusicVideo:()=>{const ue=(ae.photos??[]).slice().sort((me,de)=>(de.is_primary?1:0)-(me.is_primary?1:0)||(me.sort_order??0)-(de.sort_order??0)).map(me=>me.photo_url).filter(Boolean);if(ue.length===0){he.error("Add photos to this listing first.");return}j1t({photos:ue,details:{address:ae.property_address||`${ae.city??""} ${ae.state??""}`.trim(),beds:ae.bedrooms?String(ae.bedrooms):"",baths:ae.bathrooms?String(ae.bathrooms):"",sqft:ae.square_footage?String(ae.square_footage):"",price:ae.price?String(ae.price):"",highlights:ae.description||""},sourceLabel:"My Listings",badge:N1t(ae.status,ae.price)}),s("/admin/beta/homereel?tab=music-video")}},ae.id))})}),e.jsx(fs,{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((ae,ue)=>e.jsxs(ke,{children:[e.jsx(dr,{className:"h-48 w-full"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[e.jsx(dr,{className:"h-5 w-3/4"}),e.jsx(dr,{className:"h-4 w-1/2"})]})]},ue))}):(y==null?void 0:y.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(yi,{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(ae=>e.jsx(IV,{listing:ae.listing,onClick:()=>s(`/mission-control/listings/${ae.listing.id}`)},ae.id))})}),e.jsx(fs,{value:"referrals",className:"space-y-6",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Ec,{className:"h-4 w-4"}),"Referrals Sent (",((K=N==null?void 0:N.sent)==null?void 0:K.length)||0,")"]}),((Z=N==null?void 0:N.sent)==null?void 0:Z.length)===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(Q=N==null?void 0:N.sent)==null?void 0:Q.map(ae=>{var ue,me;return e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ae.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((ue=ae.listing)==null?void 0:ue.property_address)||((me=ae.listing)==null?void 0:me.city)})]}),e.jsx(Xe,{variant:ae.status==="closed"?"default":"secondary",children:ae.status.replace("_"," ")})]})})},ae.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),"Referrals Received (",((W=N==null?void 0:N.received)==null?void 0:W.length)||0,")"]}),((te=N==null?void 0:N.received)==null?void 0:te.length)===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(ne=N==null?void 0:N.received)==null?void 0:ne.map(ae=>{var ue;return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ae.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(ue=ae.sender)==null?void 0:ue.name]})]}),e.jsx(Xe,{variant:ae.status==="closed"?"default":"secondary",children:ae.status.replace("_"," ")})]}),e.jsx(q,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${ae.listing_id}`),children:"View Listing"})]})},ae.id)})})]})]})}),t&&e.jsx(fs,{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((ae,ue)=>e.jsxs(ke,{children:[e.jsx(dr,{className:"h-48 w-full"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[e.jsx(dr,{className:"h-5 w-3/4"}),e.jsx(dr,{className:"h-4 w-1/2"})]})]},ue))}):(A==null?void 0:A.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(SE,{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(q,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Ys,{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(ae=>e.jsx(IV,{listing:ae,onClick:()=>s(`/mission-control/listings/${ae.id}`)},ae.id))})}),e.jsx(fs,{value:"map",children:e.jsx(fqs,{listings:f||[],isLoading:x})}),e.jsx(fs,{value:"leaderboard",children:e.jsx(hqs,{leaderboard:D})})]})]}),e.jsx(lqs,{})]}):e.jsx(ws,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(Pn,{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 k1t(s){return pt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:r}=await U.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function xqs(){const{user:s}=Cs(),t=is();return Mt({mutationFn:async({listingId:r,file:n})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=n.name.split(".").pop(),i=`${s.id}/${r}/${crypto.randomUUID()}.${a}`,{error:l}=await U.storage.from("listing-documents").upload(i,n,{contentType:n.type||void 0});if(l)throw l;const{data:o,error:c}=await U.from("listing_documents").insert({listing_id:r,owner_user_id:s.id,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["listing-documents",n.listingId]})}})}function gqs(){const s=is();return Mt({mutationFn:async({id:t,storage_path:r,listingId:n})=>{await U.storage.from("listing-documents").remove([r]);const{error:a}=await U.from("listing_documents").delete().eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function yqs(){const s=is();return Mt({mutationFn:async({id:t,visible:r,listingId:n})=>{const{error:a}=await U.from("listing_documents").update({visible_on_exchange:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function S1t(s){const{data:t,error:r}=await U.storage.from("listing-documents").createSignedUrl(s,3600);if(r)throw r;return t.signedUrl}const vqs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function bqs({listingId:s,ownerOnly:t=!1}){const{data:r=[]}=k1t(s),n=t?r:r.filter(i=>i.visible_on_exchange);if(n.length===0)return null;const a=async i=>{try{const l=await S1t(i);window.open(l,"_blank")}catch{he.error("Failed to open document")}};return e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(En,{className:"h-5 w-5"}),"Documents & Disclosures (",n.length,")"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-2",children:n.map(i=>e.jsxs("button",{onClick:()=>a(i.storage_path),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors text-left group",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 flex-shrink-0",children:e.jsx(En,{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:vqs(i.file_size)})]}),e.jsx(li,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}const _qs=s=>{if(!s)return"";const t=s.replace(/\D/g,""),r=t.length===11&&t.startsWith("1")?t.slice(1):t;return r.length!==10?s:`${r.slice(0,3)}-${r.slice(3,6)}-${r.slice(6)}`},wKe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),bC="#D4AF37",jKe="#0F172A",NKe=async s=>new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.referrerPolicy="no-referrer",n.onload=()=>t(n),n.onerror=r,n.src=s}),kKe=(s,t,r,n,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,r,n,a,i)},KO=(s,t,r)=>{if(s.measureText(t).width<=r)return t;let n=t;for(;n.length>3&&s.measureText(`${n}…`).width>r;)n=n.slice(0,-1);return`${n.trim()}…`},wqs=(s,t,r,n)=>{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<=r||!l)l=c;else if(i.push(l),l=o,i.length===n)break}return l&&i.length{let i=r;for(const l of t)s.fillText(l,i,n),i+=s.measureText(l).width+a},Nqs=s=>s instanceof DOMException||s instanceof Error?s.name:null;function C1t({listingId:s,open:t,onOpenChange:r}){var E,D;const{data:n}=wEe(s||""),[a,i]=k.useState(null),[l,o]=k.useState(!1),[c,d]=k.useState(null),[u,m]=k.useState(null),f=((n==null?void 0:n.photos)||[]).slice().sort((R,F)=>R.is_primary&&!F.is_primary?-1:!R.is_primary&&F.is_primary?1:(R.sort_order??0)-(F.sort_order??0));k.useEffect(()=>{var F;if(!t)return;const R=((F=f[0])==null?void 0:F.photo_url)||null;m(O=>O||R)},[t,n==null?void 0:n.id,f.length]),k.useEffect(()=>{let R=!1;if(!(!t||!(n!=null&&n.agent_id)))return(async()=>{var K,Z,Q,W;const{data:F}=await U.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",n.agent_id).maybeSingle();if(R)return;const O=F,B=((K=O==null?void 0:O.brokerage)==null?void 0:K.name)||((Q=(Z=n.agent)==null?void 0:Z.brokerage)==null?void 0:Q.name)||null;i({name:(O==null?void 0:O.name)||((W=n.agent)==null?void 0:W.name)||"Agent",phone:(O==null?void 0:O.phone)||(O==null?void 0:O.phone_e164)||null,avatar_url:(O==null?void 0:O.avatar_url)||null,brokerage:B})})(),()=>{R=!0}},[t,n==null?void 0:n.agent_id]),k.useEffect(()=>{if(!t){d(null),m(null);return}if(!n||!a)return;const R=setTimeout(()=>{x()},350);return()=>clearTimeout(R)},[t,n==null?void 0:n.id,a==null?void 0:a.name,u]);const x=async()=>{if(!(!n||!a)){o(!0);try{const R=document.createElement("canvas");R.width=1080,R.height=1080;const F=R.getContext("2d");if(!F)throw new Error("Canvas unavailable");if(F.fillStyle=jKe,F.fillRect(0,0,1080,1080),N){const W=await NKe(N);kKe(F,W,0,0,1080,1080)}const O=F.createLinearGradient(0,0,0,1080);O.addColorStop(0,"rgba(15,23,42,0.58)"),O.addColorStop(.34,"rgba(15,23,42,0.16)"),O.addColorStop(.62,"rgba(15,23,42,0.48)"),O.addColorStop(1,"rgba(15,23,42,0.98)"),F.fillStyle=O,F.fillRect(0,0,1080,1080),F.fillStyle=bC,F.fillRect(56,62,72,2),F.font="600 22px Arial, sans-serif",jqs(F,"JUST LISTED",146,72,8),F.save(),F.shadowColor="rgba(0,0,0,0.55)",F.shadowBlur=24,F.shadowOffsetY=4,F.fillStyle="#F8FAFC",F.font="600 64px Georgia, serif",F.textBaseline="top";const B=wqs(F,n.property_address||`${n.city||""}, ${n.state||""}`.trim(),952,2);let K=B.length>1?590:654;B.forEach(W=>{F.fillText(W,64,K),K+=70}),F.restore();const Z=[n.city,n.state].filter(Boolean).join(", ")+(n.neighborhood?` · ${n.neighborhood}`:"");F.fillStyle="rgba(248,250,252,0.9)",F.font="600 26px Arial, sans-serif",F.fillText(KO(F,Z.toUpperCase(),952),64,K+8),F.fillStyle=bC,F.font="700 56px Arial, sans-serif",F.fillText(wKe(n.price),64,K+58),A.length>0&&(F.fillStyle="rgba(248,250,252,0.86)",F.font="600 22px Arial, sans-serif",F.fillText(KO(F,A.join(" · "),430),360,K+78));const Q=F.createLinearGradient(0,880,0,1080);if(Q.addColorStop(0,"rgba(15,23,42,0.96)"),Q.addColorStop(1,"#0B1322"),F.fillStyle=Q,F.fillRect(0,880,1080,200),F.fillStyle=bC,F.fillRect(0,880,1080,2),F.save(),F.beginPath(),F.arc(124,980,60,0,Math.PI*2),F.closePath(),F.fillStyle="#1E293B",F.fill(),F.lineWidth=6,F.strokeStyle=bC,F.stroke(),F.clip(),a.avatar_url)try{const W=await NKe(a.avatar_url);kKe(F,W,64,920,120,120)}catch{F.fillStyle=bC,F.font="700 48px Arial, sans-serif",F.textAlign="center",F.textBaseline="middle",F.fillText(a.name.charAt(0).toUpperCase(),124,982)}else F.fillStyle=bC,F.font="700 48px Arial, sans-serif",F.textAlign="center",F.textBaseline="middle",F.fillText(a.name.charAt(0).toUpperCase(),124,982);F.restore(),F.textAlign="left",F.textBaseline="alphabetic",F.fillStyle="#F8FAFC",F.font="600 38px Georgia, serif",F.fillText(KO(F,a.name,C?430:820),212,970),a.brokerage&&(F.fillStyle=bC,F.font="600 20px Arial, sans-serif",F.fillText(KO(F,a.brokerage.toUpperCase(),C?430:820),212,1008)),C&&(F.textAlign="right",F.fillStyle="rgba(212,175,55,0.86)",F.font="600 16px Arial, sans-serif",F.fillText("CALL · TEXT",1016,958),F.fillStyle="#F8FAFC",F.font="600 38px Arial, sans-serif",F.fillText(C,1016,1008)),d(R.toDataURL("image/png"))}catch(R){console.error("Generate graphic error",R),he.error("Could not generate graphic")}finally{o(!1)}}},y=async R=>(await fetch(R)).blob(),_=async()=>{if(!c)return;const R=document.createElement("a");R.href=c,R.download=`just-listed-${(n==null?void 0:n.slug)||(n==null?void 0:n.id)||"graphic"}.png`,R.click(),he.success("Downloaded!")},b=async()=>{if(c)try{const R=await y(c);await navigator.clipboard.write([new ClipboardItem({"image/png":R})]),he.success("Copied to clipboard")}catch{he.error("Copy not supported in this browser")}},j=async()=>{if(c)try{const R=await y(c),F=new File([R],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[F]})?await navigator.share({files:[F],title:"Just Listed"}):_()}catch(R){Nqs(R)!=="AbortError"&&he.error("Share failed")}},N=u||((E=f[0])==null?void 0:E.photo_url)||null,C=_qs(a==null?void 0:a.phone),A=[n!=null&&n.bedrooms?`${n.bedrooms} BD`:null,n!=null&&n.bathrooms?`${n.bathrooms} BA`:null,n!=null&&n.square_footage?`${n.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(vs,{open:t,onOpenChange:r,children:e.jsx(ys,{className:"!max-w-[480px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex flex-col",style:{maxHeight:"calc(100vh - 2rem)"},children:[e.jsxs(_s,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(bs,{className:"flex items-center gap-2 pr-8",children:[e.jsx(Ir,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(an,{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:jKe},children:[N&&e.jsx("img",{src:N,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:(n==null?void 0:n.property_address)||`${(n==null?void 0:n.city)||""}, ${(n==null?void 0:n.state)||""}`}),e.jsxs("div",{className:"mt-1 truncate text-[9px] font-semibold uppercase tracking-[0.18em] text-white/85",children:[[n==null?void 0:n.city,n==null?void 0:n.state].filter(Boolean).join(", "),n!=null&&n.neighborhood?` · ${n.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:n?wKe(n.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"}):(D=a==null?void 0:a.name)==null?void 0:D.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})]}),C&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:C})]}),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(ls,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),f.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:f.map(R=>{const F=u===R.photo_url;return e.jsx("button",{type:"button",onClick:()=>m(R.photo_url),className:`relative shrink-0 h-14 w-14 rounded-md overflow-hidden border-2 transition ${F?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:R.photo_url,alt:"",className:"w-full h-full object-cover"})},R.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(q,{variant:"outline",size:"sm",onClick:()=>void x(),disabled:l||!n||!a,children:"Regenerate"}),e.jsxs(q,{variant:"outline",size:"sm",onClick:b,disabled:!c,className:"gap-1.5",children:[e.jsx(si,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:j,disabled:!c,className:"gap-1.5",children:[e.jsx(Ec,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(q,{size:"sm",onClick:_,disabled:!c,className:"gap-1.5",children:[e.jsx(li,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function kqs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const Sqs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function Cqs({open:s,onOpenChange:t,listing:r}){const{user:n}=Cs(),{data:a=[],isLoading:i}=Lp(),{data:l=[]}=H0(),[o,c]=k.useState(""),[d,u]=k.useState("all"),[m,f]=k.useState(new Set),[x,y]=k.useState(!1),[_,b]=k.useState(null);k.useEffect(()=>{s||(c(""),u("all"),f(new Set),y(!1))},[s]),k.useEffect(()=>{!s||!n||(async()=>{const{data:F}=await U.from("gmail_integrations").select("gmail_email").eq("user_id",n.id).maybeSingle();b((F==null?void 0:F.gmail_email)||null)})()},[s,n]);const j=k.useMemo(()=>a.filter(F=>F.email),[a]),N=k.useMemo(()=>{let F=j;if(d!=="all"&&(F=F.filter(O=>{var B;return(B=O.tags)==null?void 0:B.some(K=>K.relationship_type_id===d)})),o.trim()){const O=o.toLowerCase();F=F.filter(B=>`${B.first_name||""} ${B.last_name||""}`.toLowerCase().includes(O)||(B.email||"").toLowerCase().includes(O))}return F},[j,o,d]),C=()=>{m.size===N.length?f(new Set):f(new Set(N.map(F=>F.id)))},A=F=>{const O=new Set(m);O.has(F)?O.delete(F):O.add(F),f(O)},E=k.useMemo(()=>j.filter(F=>m.has(F.id)).map(F=>({id:F.id,first_name:F.first_name||"there",last_name:F.last_name,email:F.email})),[j,m]),{defaultSubject:D,defaultBody:R}=k.useMemo(()=>{var fe,je,xe,Ee;const F=r.property_address||`${r.city}, ${r.state}`,O=kqs(r.price),B=Sqs[r.property_type]||"home",K=r.bedrooms?`${r.bedrooms} bed`:"",Z=r.bathrooms?`${r.bathrooms} bath`:"",Q=r.square_footage?`${r.square_footage.toLocaleString()} sqft`:"",W=[K,Z,Q].filter(Boolean).join(" • "),te=`https://listings.relevelup.com/${r.slug||r.id}`,ne=((je=(fe=r.photos)==null?void 0:fe.find(Me=>Me.is_primary))==null?void 0:je.photo_url)||((Ee=(xe=r.photos)==null?void 0:xe[0])==null?void 0:Ee.photo_url)||"",ue={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[r.status]||"New Listing",me=`${ue}: ${F} — ${O}`,de=`

Hi {{first_name}},

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

${ne?` ${F} `:""}
${ue}

${O}

${F}

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

${W?`

${W} • ${B}

`:""} 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:me,defaultBody:de}},[r]);return x?e.jsx(uw,{open:x,onOpenChange:F=>{y(F),F||t(!1)},bulkContacts:E,defaultSubject:D,defaultBody:R,gmailEmail:_}):e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(an,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search contacts...",value:o,onChange:F=>c(F.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:d,onValueChange:u,children:[e.jsx(Ps,{className:"sm:w-[180px]",children:e.jsx(Fs,{placeholder:"Filter by tag"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All contacts"}),l.map(F=>e.jsx(lt,{value:F.id,children:F.name},F.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:C,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Ri,{checked:N.length>0&&m.size===N.length,className:"pointer-events-none"}),e.jsx("span",{children:m.size===N.length&&N.length>0?"Deselect all":`Select all (${N.length})`})]}),e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Dr,{className:"h-3 w-3"}),m.size," selected"]})]}),e.jsx(ui,{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(ls,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):N.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:N.map(F=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(Ri,{checked:m.has(F.id),onCheckedChange:()=>A(F.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[F.first_name," ",F.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:F.email})]}),F.tags&&F.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:F.tags.slice(0,2).map(O=>{var B;return e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(B=O.relationship_type)==null?void 0:B.name},O.id)})})]},F.id))})}),e.jsx(cl,{}),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(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:()=>y(!0),disabled:m.size===0,className:"gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"}),"Compose Email (",m.size,")"]})]})]})]})})}function Vy(s){const t=s.expected_commission;if(!t)return null;if((s.commission_calc_method||"standard")==="referral_first"){let a=t;s.referral_fee_pct&&(a-=t*(s.referral_fee_pct/100));let i=a;return s.brokerage_split_pct&&(i-=a*(s.brokerage_split_pct/100)),s.team_split_pct&&(i-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(i-=t*(s.franchise_fee_pct/100)),s.transaction_fee&&(i-=s.transaction_fee),Math.max(0,i)}let n=t;return s.brokerage_split_pct&&(n-=t*(s.brokerage_split_pct/100)),s.team_split_pct&&(n-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(n-=t*(s.franchise_fee_pct/100)),s.referral_fee_pct&&(n-=t*(s.referral_fee_pct/100)),s.transaction_fee&&(n-=s.transaction_fee),Math.max(0,n)}function Gye(){const s=xa();return pt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function T1t(){const s=xa(),t=is();return Mt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:r}=await U.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function Wye(){const s=xa();return pt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function E1t(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("deal_pipeline").insert({deal_name:r.deal_name,deal_type:r.deal_type,stage_id:r.stage_id||null,contact_id:r.contact_id||null,listing_id:r.listing_id||null,property_address:r.property_address||null,city:r.city||null,state:r.state||null,zip_code:r.zip_code||null,expected_price:r.expected_price||null,expected_commission:r.expected_commission||null,commission_percentage:r.commission_percentage||3,target_close_date:r.target_close_date||null,contract_date:r.contract_date||null,listing_date:r.listing_date||null,priority:r.priority||"medium",probability:r.probability||50,notes:r.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await U.from("deal_activities").insert([{deal_id:n.id,activity_type:"system",title:"Deal created",description:`Deal "${r.deal_name}" was created`}]),n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function A1t(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("deal_pipeline").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function Tqs(){const s=is();return Mt({mutationFn:async({dealId:t,stageId:r,stageName:n})=>{const{data:a,error:i}=await U.from("deal_pipeline").update({stage_id:r}).eq("id",t).select().single();if(i)throw i;return await U.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${n}`,metadata:{new_stage_id:r,new_stage_name:n}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function Eqs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("deal_pipeline").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function Aqs(s){return pt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:r}=await U.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Mqs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-activities",r.deal_id]})}})}function Iqs(s){return pt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:r}=await U.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function Pqs(){const s=is();return Mt({mutationFn:async({id:t,is_completed:r,deal_id:n})=>{const{data:a,error:i}=await U.from("deal_checklist_items").update({is_completed:r,completed_at:r?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function Lqs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function Dqs(){const s=xa();return pt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(r)throw r;const n=(t==null?void 0:t.filter(o=>{var c,d,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:n.length,wonDeals:a.length,pipelineValue:n.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:n.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:n.reduce((o,c)=>o+(Vy(c)||0),0),wonValue:a.reduce((o,c)=>o+(c.expected_price||0),0),weightedGCI:n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(c.expected_commission||0)*d},0),weightedNet:n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Vy(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(Vy(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(Vy(c)||0),0)+n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Vy(c)||0)*d},0)}},enabled:!!s})}function Rqs(s){const t=xa();return pt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:r,error:n}=await U.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(n)throw n;return r},enabled:!!t&&!!s})}function Oqs(){const s=is();return Mt({mutationFn:async({dealId:t,listingId:r})=>{const{data:n,error:a}=await U.from("deal_pipeline").update({listing_id:r}).eq("id",t).select().single();if(a)throw a;return await U.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:r}}),n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",r.listingId]})}})}function Fqs(){const s=is();return Mt({mutationFn:async({dealId:t,listingId:r})=>{const{data:n,error:a}=await U.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:n,listingId:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function zqs({listing:s}){const t=qr(),[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l,isLoading:o}=Rqs(s.id),{data:c,isLoading:d}=Gye(),{data:u,isLoading:m}=Wye(),f=T1t(),x=Oqs(),y=Fqs(),_=E1t(),b=(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(D=>D.name==="Active");case"under_contract":return c.find(D=>D.name==="Under Contract");case"sold":return c.find(D=>D.is_won_stage);default:return c.find(D=>D.name==="Active")}},N=async()=>{i(!0);try{c!=null&&c.length||await f.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}),he.success("Deal created and linked to listing!")}catch(E){console.error("Failed to create deal:",E),he.error("Failed to create deal")}finally{i(!1)}},C=async()=>{if(!r){he.error("Please select a deal");return}try{await x.mutateAsync({dealId:r,listingId:s.id}),he.success("Listing linked to deal!"),n("")}catch{he.error("Failed to link listing")}},A=async()=>{if(l)try{await y.mutateAsync({dealId:l.id,listingId:s.id}),he.success("Listing unlinked from deal")}catch{he.error("Failed to unlink listing")}};return o||d?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(i2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(ke,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ul,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Pe,{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.deal_name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:l.deal_pipeline_stages&&e.jsx(Xe,{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(q,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(ci,{className:"h-3 w-3 ml-1"})]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:A,disabled:y.isPending,children:y.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(WE,{className:"h-4 w-4"})})]})]})]}):e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(i2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link this listing to your pipeline to track the deal and sync status changes."}),e.jsxs(q,{onClick:N,disabled:a||_.isPending,className:"w-full",size:"sm",children:[a||_.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ds,{value:r,onValueChange:n,children:[e.jsx(Ps,{className:"flex-1 text-sm",children:e.jsx(Fs,{placeholder:"Link to existing deal..."})}),e.jsx(Ls,{children:b.map(E=>e.jsx(lt,{value:E.id,children:E.deal_name},E.id))})]}),e.jsx(q,{variant:"secondary",size:"icon",onClick:C,disabled:!r||x.isPending,children:x.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Ul,{className:"h-4 w-4"})})]})]})]})]})}const Bqs={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"},$qs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},SKe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function Uqs(){var ae,ue,me,de,fe,je,xe,Ee,Me;const{listingId:s}=xo(),t=qr(),{user:r}=Cs(),{data:n,isLoading:a}=wEe(s||""),{data:i}=Bct(s||""),{data:l}=qQt(s||""),o=zct(),c=UQt(),d=VQt(),u=Fct(),m=GQt(),[f,x]=k.useState(!1),[y,_]=k.useState(!1),[b,j]=k.useState(!1),[N,C]=k.useState(!1),[A,E]=k.useState(!1),[D,R]=k.useState(null),[F,O]=k.useState({buyerName:"",buyerType:"",notes:""}),B=(r==null?void 0:r.id)===(n==null?void 0:n.agent_id),K=Oe=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Oe),Z=async Oe=>{const Ie=`https://listings.relevelup.com/${(n==null?void 0:n.slug)||(n==null?void 0:n.id)}`,ze=`Check out this listing: ${(n==null?void 0:n.property_address)||(n==null?void 0:n.city)}`;d.mutate({listingId:n.id,shareType:Oe});try{switch(Oe){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Ie)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Ie),he.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${ze} ${Ie}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(ze)}&body=${encodeURIComponent(`Check out this listing: ${Ie}`)}`);break}}catch(Ve){console.error("Share error:",Ve),he.error("Failed to share")}},Q=async()=>{try{await u.mutateAsync(n.id),he.success("Listing deleted"),t("/mission-control/listings")}catch{he.error("Failed to delete listing")}},W=async()=>{if(!F.buyerName.trim()){he.error("Please enter buyer name");return}try{await m.mutateAsync({listingId:n.id,listingAgentId:n.agent_id,buyerName:F.buyerName,buyerType:F.buyerType||void 0,notes:F.notes||void 0}),he.success("Referral sent successfully!"),_(!1),O({buyerName:"",buyerType:"",notes:""})}catch{he.error("Failed to send referral")}},te=Oe=>{var Qe,we;const Ie=(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`,ze=K((n==null?void 0:n.price)||0),Ve=n!=null&&n.bedrooms?`${n.bedrooms}BD`:"",Le=n!=null&&n.bathrooms?`${n.bathrooms}BA`:"",$e=n!=null&&n.square_footage?`${n.square_footage.toLocaleString()}SF`:"",ve=[Ve,Le,$e].filter(Boolean).join(" | ");switch(Oe){case"just_listed":return`🏡 JUST LISTED! ${Ie} ${ze} ${ve} ${(n==null?void 0:n.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Qe=n==null?void 0:n.city)==null?void 0:Qe.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Ie} Now ${ze}! ${ve} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${SKe[(n==null?void 0:n.property_type)||"single_family"].toLowerCase()} in ${n==null?void 0:n.city}? 👀 I've got just the one for you! ${ve} DM me for details! 📩 #ComingSoon #RealEstate #${(we=n==null?void 0:n.city)==null?void 0:we.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(ws,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(dr,{className:"h-10 w-32"}),e.jsx(dr,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(dr,{className:"h-48"}),e.jsx(dr,{className:"h-48"}),e.jsx(dr,{className:"h-48"})]})]})});if(!n)return e.jsx(ws,{title:"Listing Not Found",description:"",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(q,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const ne=((ae=n.photos)==null?void 0:ae.find(Oe=>Oe.is_primary))||((ue=n.photos)==null?void 0:ue[0]);return e.jsxs(ws,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(q,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>ne&&R(ne.photo_url),children:ne?e.jsx("img",{src:ne.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(me=n.photos)==null?void 0:me.slice(1,5).map((Oe,Ie)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>R(Oe.photo_url),children:e.jsx("img",{src:Oe.photo_url,alt:`Photo ${Ie+2}`,className:"w-full h-full object-cover"})},Oe.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Xe,{className:`${Bqs[n.status]} text-white border-0`,children:$qs[n.status]}),n.is_featured&&e.jsxs(Xe,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(fa,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),n.open_to_referrals&&e.jsxs(Xe,{variant:"outline",children:[e.jsx(Dr,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:K(n.price)}),n.property_address&&e.jsx("p",{className:"text-xl font-medium",children:n.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Ma,{className:"h-4 w-4"}),n.city,", ",n.state,n.neighborhood&&` • ${n.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(q,{variant:"outline",size:"icon",onClick:()=>o.mutate(n.id),children:e.jsx(yi,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx(q,{variant:"outline",size:"icon",onClick:()=>c.mutate(n.id),children:l?e.jsx(b_,{className:"h-4 w-4"}):e.jsx(ym,{className:"h-4 w-4"})}),!B&&e.jsxs(q,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>j(!0),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{variant:"outline",children:[e.jsx(Ec,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Sd,{children:[e.jsxs(ti,{onClick:()=>Z("copy"),children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(ti,{onClick:()=>Z("facebook"),children:[e.jsx(mh,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(ti,{onClick:()=>Z("text"),children:[e.jsx(Ui,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(ti,{onClick:()=>Z("email"),children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),B&&e.jsxs(e.Fragment,{children:[e.jsxs(q,{variant:"outline",onClick:()=>{const Oe=(n.photos??[]).slice().sort((Ie,ze)=>(ze.is_primary?1:0)-(Ie.is_primary?1:0)||(Ie.sort_order??0)-(ze.sort_order??0)).map(Ie=>Ie.photo_url).filter(Boolean);if(Oe.length===0){he.error("Add photos to this listing first.");return}j1t({photos:Oe,details:{address:n.property_address||`${n.city??""} ${n.state??""}`.trim(),beds:n.bedrooms?String(n.bedrooms):"",baths:n.bathrooms?String(n.bathrooms):"",sqft:n.square_footage?String(n.square_footage):"",price:n.price?String(n.price):"",highlights:n.description||""},sourceLabel:"Listing Exchange",badge:N1t(n.status,n.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(rP,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs(q,{variant:"outline",onClick:()=>E(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(Ir,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(q,{variant:"outline",onClick:()=>C(!0),className:"gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(q,{onClick:()=>t(`/mission-control/listings/${n.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(Ir,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs(q,{variant:"outline",onClick:()=>t(`/mission-control/listings/${n.id}/edit`),children:[e.jsx(iu,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(q,{variant:"destructive",size:"icon",onClick:()=>x(!0),children:e.jsx(zr,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[n.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(k0,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),n.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(of,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),n.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(C0,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),n.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(vn,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Xe,{variant:"secondary",children:[e.jsx(Ga,{className:"h-3 w-3 mr-1"}),SKe[n.property_type]]}),n.lot_size&&e.jsxs(Xe,{variant:"secondary",children:["Lot: ",n.lot_size]}),n.has_hoa&&e.jsx(Xe,{variant:"secondary",children:"HOA"})]}),n.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})]}),n.agent_notes&&n.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.agent_notes})]}),n.mls_link&&e.jsx(q,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:n.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(un,{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(Nn,{className:"h-4 w-4"}),n.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ec,{className:"h-4 w-4"}),n.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yi,{className:"h-4 w-4"}),n.save_count," saves"]})]})]})}),n.allow_sharing&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Share Content"})}),e.jsx(Pe,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Oe=>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:[Oe.replace("_"," ")," Caption"]}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(te(Oe)),he.success("Caption copied!")},children:e.jsx(si,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:te(Oe)})]},Oe))})]}),e.jsx(bqs,{listingId:n.id,ownerOnly:B})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-semibold text-primary",children:((fe=(de=n.agent)==null?void 0:de.name)==null?void 0:fe.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((je=n.agent)==null?void 0:je.name)||"Unknown"}),((Ee=(xe=n.agent)==null?void 0:xe.brokerage)==null?void 0:Ee.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n.agent.brokerage.name})]})]}),!B&&e.jsx("div",{className:"space-y-2",children:((Me=n.agent)==null?void 0:Me.email)&&e.jsx(q,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${n.agent.email}`,children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),B&&e.jsx(zqs,{listing:n}),!B&&n.open_to_referrals&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Have a buyer interested in this property? Send a referral to the listing agent."}),e.jsx(q,{className:"w-full",onClick:()=>_(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(vs,{open:!!D,onOpenChange:()=>R(null),children:e.jsx(ys,{className:"max-w-4xl",children:e.jsx("img",{src:D||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(vs,{open:f,onOpenChange:x,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Delete Listing"}),e.jsx(an,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(q,{variant:"destructive",onClick:Q,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(vs,{open:y,onOpenChange:_,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Send Buyer Referral"}),e.jsx(an,{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(ce,{children:"Buyer Name *"}),e.jsx(Ne,{value:F.buyerName,onChange:Oe=>O({...F,buyerName:Oe.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Buyer Type"}),e.jsxs(Ds,{value:F.buyerType,onValueChange:Oe=>O({...F,buyerType:Oe}),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select type"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"first_time",children:"First-Time Buyer"}),e.jsx(lt,{value:"investor",children:"Investor"}),e.jsx(lt,{value:"relocating",children:"Relocating"}),e.jsx(lt,{value:"upgrade",children:"Upgrading"}),e.jsx(lt,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Notes"}),e.jsx(pr,{value:F.notes,onChange:Oe=>O({...F,notes:Oe.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx(q,{onClick:W,disabled:m.isPending,children:m.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(b1t,{open:b,onOpenChange:j,listingId:(n==null?void 0:n.id)||"",listingSlug:(n==null?void 0:n.slug)||null,listingTitle:(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`}),n&&e.jsx(Cqs,{open:N,onOpenChange:C,listing:n}),e.jsx(C1t,{listingId:(n==null?void 0:n.id)||null,open:A,onOpenChange:E})]})}function qqs({onImport:s}){const[t,r]=k.useState(""),[n,a]=k.useState([]),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(null),m=k.useRef(),f=k.useRef(null);k.useEffect(()=>{const N=C=>{f.current&&!f.current.contains(C.target)&&c(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[]);const x=async N=>{if(N.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:C,error:A}=await U.functions.invoke("mls-listing-search",{body:{query:N}});if(A)throw A;a((C==null?void 0:C.listings)||[]),c(!0)}catch(C){console.error("MLS search error:",C),a([])}finally{l(!1)}},y=N=>{r(N),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>x(N),400)},_=N=>{u(N.mlsNumber),s(N),c(!1),r(`${N.address}, ${N.city}`),he.success(`Imported: ${N.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},b=N=>N?`$${N.toLocaleString()}`:"",j=N=>{const C=(N||"").toLowerCase();return C.includes("single")||C.includes("detached")?"Single Family":C.includes("condo")?"Condo":C.includes("town")?"Townhouse":C.includes("land")||C.includes("lot")?"Land":C.includes("multi")?"Multi-Family":C.includes("commercial")?"Commercial":N||"Other"};return e.jsxs(ke,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Pt,{className:"pb-3",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(li,{className:"h-4 w-4 text-primary"}),"Import from MLS"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Search by address to auto-fill property details and photos from MLS"})]}),e.jsx(Pe,{children:e.jsxs("div",{ref:f,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:t,onChange:N=>y(N.target.value),onFocus:()=>n.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(ls,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground"}),t&&!i&&e.jsx("button",{type:"button",onClick:()=>{r(""),a([]),c(!1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx($r,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:n.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):n.map(N=>e.jsxs("button",{type:"button",onClick:()=>_(N),disabled:d===N.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:[N.photos[0]?e.jsx("img",{src:N.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(Ma,{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:N.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N.city,", ",N.state," ",N.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:b(N.price)}),N.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(k0,{className:"h-3 w-3"})," ",N.bedrooms]}),N.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(of,{className:"h-3 w-3"})," ",N.bathrooms]}),N.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(m2,{className:"h-3 w-3"})," ",N.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:j(N.propertyType)}),N.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[N.photos.length," photos"]})]})]},N.mlsNumber))})]})})]})}function Vqs({photo:s,onRemove:t,onSetPrimary:r}){const{attributes:n,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=w0e({id:s.id}),d={transform:zS.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:zt("relative aspect-square rounded-lg overflow-hidden bg-muted group",c&&"opacity-50 ring-2 ring-primary z-50"),children:[e.jsx("img",{src:s.photo_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...n,...a,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Vu,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>t(s.id),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx($r,{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(fa,{className:"h-2.5 w-2.5 fill-current"})," Primary"]}):e.jsx("button",{type:"button",onClick:()=>r(s.id),className:"absolute bottom-1 left-1 text-[10px] bg-black/60 text-white px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80",children:"Set as Primary"})]})}function Hqs({photos:s,uploading:t,onUpload:r,onRemove:n,onReorder:a,onSetPrimary:i}){const l=m0e(NL(B8,{activationConstraint:{distance:5}})),o=[...s].sort((d,u)=>(d.sort_order??0)-(u.sort_order??0)),c=d=>{const{active:u,over:m}=d;if(!m||u.id===m.id)return;const f=o.findIndex(j=>j.id===u.id),x=o.findIndex(j=>j.id===m.id),y=[...o],[_]=y.splice(f,1);y.splice(x,0,_);const b=y.map((j,N)=>({...j,sort_order:N}));a(b)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. Hover to set primary."}),e.jsx(v0e,{sensors:l,collisionDetection:f0e,onDragEnd:c,children:e.jsx(_0e,{items:o.map(d=>d.id),strategy:VB,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(Vqs,{photo:d,onRemove:n,onSetPrimary:i},d.id)),e.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[t?e.jsx(ls,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:"Upload"})]}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:d=>r(d.target.files),disabled:t})]})]})})})]})}function Gqs({selectedVideoId:s,onVideoSelect:t,listingId:r}){const n=qr(),{user:a}=Cs(),[i,l]=k.useState(!1),[o,c]=k.useState([]),[d,u]=k.useState(!1),[m,f]=k.useState(null),[x,y]=k.useState({});k.useEffect(()=>{s&&a?_():f(null)},[s,a]);const _=async()=>{if(!s)return;const{data:O,error:B}=await U.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!B&&O&&(f(O),b(O))},b=async O=>{try{const{data:B,error:K}=await U.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:O.bunny_video_id,isAgentVideo:!0}});!K&&(B!=null&&B.thumbnailUrl)&&y(Z=>({...Z,[O.id]:{thumbnailUrl:B.thumbnailUrl}}))}catch(B){console.warn("Failed to get signed URL",B)}},j=async()=>{if(a){u(!0);try{const{data:O,error:B}=await U.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(B)throw B;c(O||[]),O!=null&&O.length&&N(O)}catch(O){console.error("Error fetching videos:",O),he.error("Failed to load videos")}finally{u(!1)}}},N=async O=>{var B;try{const K=O.map(ne=>ne.bunny_video_id),{data:Z,error:Q}=await U.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:K,isAgentVideo:!0}});if(Q)throw Q;const W=(Z==null?void 0:Z.assets)||{},te={};for(const ne of O)(B=W[ne.bunny_video_id])!=null&&B.thumbnailUrl&&(te[ne.id]={thumbnailUrl:W[ne.bunny_video_id].thumbnailUrl});y(ne=>({...ne,...te}))}catch(K){console.warn("Failed to bulk-fetch signed URLs",K)}},C=()=>{l(!0),j()},A=O=>{t(O.id),f(O),l(!1),he.success("Video selected")},E=()=>{t(null),f(null)},D=()=>{const O=r?`/mission-control/listings/${r}/edit`:"/mission-control/listings/new";n(`/mission-control/video?returnUrl=${encodeURIComponent(O)}`)},R=O=>{if(!O)return"0:00";const B=Math.floor(O/60),K=O%60;return`${B}:${K.toString().padStart(2,"0")}`},F=O=>{var B;return((B=x[O.id])==null?void 0:B.thumbnailUrl)||O.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[m?e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Pe,{className:"p-0",children:e.jsxs("div",{className:"flex items-start gap-4 p-4",children:[e.jsxs("div",{className:"relative w-32 h-20 bg-muted rounded-lg overflow-hidden flex-shrink-0",children:[F(m)?e.jsx("img",{src:F(m),alt:m.title||"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(bn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/30 flex items-center justify-center",children:e.jsx(Al,{className:"h-6 w-6 text-white fill-white"})}),m.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:R(m.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:m.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{type:"button",variant:"outline",size:"sm",onClick:C,children:"Change"}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:E,className:"text-destructive hover:text-destructive",children:e.jsx($r,{className:"h-4 w-4"})})]})]})})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Pe,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(bn,{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(q,{type:"button",variant:"outline",onClick:C,className:"gap-2",children:[e.jsx(nS,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(q,{type:"button",variant:"outline",onClick:D,className:"gap-2",children:[e.jsx(Tp,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(nS,{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(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(bn,{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(q,{onClick:D,className:"gap-2",children:[e.jsx(Tp,{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(O=>e.jsxs("button",{type:"button",onClick:()=>A(O),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===O.id?"border-primary ring-2 ring-primary/20":"border-transparent hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[F(O)?e.jsx("img",{src:F(O),alt:O.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(bn,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center",children:e.jsx(Al,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),O.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:R(O.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:O.title||"Untitled Video"})})]},O.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(q,{type:"button",variant:"ghost",onClick:D,className:"gap-2",children:[e.jsx(Tp,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(q,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const Wqs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function Kqs({listingId:s}){const t=k.useRef(null),{data:r=[],isLoading:n}=k1t(s),a=xqs(),i=gqs(),l=yqs(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){he.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(m){he.error(`Failed to upload ${u.name}: ${m.message}`)}}t.current&&(t.current.value=""),he.success("Documents uploaded")}},c=async d=>{try{const u=await S1t(d);window.open(u,"_blank")}catch{he.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(q,{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(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Upload PDFs (disclosures, etc.)"]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No documents yet. Upload PDFs that other agents can download from your listing."}):e.jsx("div",{className:"space-y-2",children:r.map(d=>e.jsxs(ke,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(En,{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:Wqs(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(Nn,{className:"h-3 w-3"}):e.jsx(Wf,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(Rr,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx(q,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(li,{className:"h-4 w-4"})}),e.jsx(q,{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($r,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const Yqs=[{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"}],Zqs=[{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 Xqs({id:s,url:t,index:r,onRemove:n}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=w0e({id:s}),u={transform:zS.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(Vu,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>n(r),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx($r,{className:"h-3 w-3"})}),r===0&&e.jsxs("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded flex items-center gap-0.5",children:[e.jsx(fa,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function Qqs({photoUrls:s,pendingPhotos:t,onRemove:r,onReorder:n,uploading:a,onUpload:i}){const l=m0e(NL(B8,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:m}=d;if(!m||u.id===m.id)return;const f=o.indexOf(u.id),x=o.indexOf(m.id),y=[...s],_=[...t],[b]=y.splice(f,1),[j]=_.splice(f,1);y.splice(x,0,b),_.splice(x,0,j),n(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(v0e,{sensors:l,collisionDetection:f0e,onDragEnd:c,children:e.jsx(_0e,{items:o,strategy:VB,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(Xqs,{id:o[u],url:d,index:u,onRemove:r},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(ls,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{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 CKe(){const{listingId:s}=xo(),[t]=ic(),r=t.get("brokerage"),n=qr(),{user:a}=Cs(),{hasLeadSite:i}=hf(),l=!!s&&s!=="new",o=!!r&&!l,[c,d]=k.useState([]),[u,m]=k.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:f,isLoading:x}=wEe(l?s:""),y=LQt(),_=DQt(),b=RQt(),j=OQt(),N=FQt(),C=zQt(),A=BQt(),{data:E=[]}=pt({queryKey:["brokerage-agents",r],queryFn:async()=>{if(!r)return[];const{data:xe,error:Ee}=await U.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name");if(Ee)throw Ee;return xe||[]},enabled:o}),[D,R]=k.useState(""),[F,O]=k.useState(!1),[B,K]=k.useState([]),[Z,Q]=k.useState([]),[W,te]=k.useState({property_address:"",city:"",state:"",neighborhood:"",price:"",property_type:"single_family",status:"active",bedrooms:"",bathrooms:"",square_footage:"",lot_size:"",year_built:"",has_hoa:!1,description:"",agent_notes:"",agent_notes_public:!1,mls_link:"",video_link:"",video_id:null,allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0});k.useEffect(()=>{var xe,Ee,Me,Oe,Ie;f&&l&&te({property_address:f.property_address||"",city:f.city||"",state:f.state||"",neighborhood:f.neighborhood||"",price:((xe=f.price)==null?void 0:xe.toString())||"",property_type:f.property_type,status:f.status,bedrooms:((Ee=f.bedrooms)==null?void 0:Ee.toString())||"",bathrooms:((Me=f.bathrooms)==null?void 0:Me.toString())||"",square_footage:((Oe=f.square_footage)==null?void 0:Oe.toString())||"",lot_size:f.lot_size||"",year_built:((Ie=f.year_built)==null?void 0:Ie.toString())||"",has_hoa:f.has_hoa,description:f.description||"",agent_notes:f.agent_notes||"",agent_notes_public:f.agent_notes_public,mls_link:f.mls_link||"",video_link:f.video_link||"",video_id:f.video_id||null,allow_sharing:f.allow_sharing,open_to_referrals:f.open_to_referrals,open_to_social_promotion:f.open_to_social_promotion,share_with_brokerage:f.share_with_brokerage??!1,is_public:f.is_public})},[f,l]);const ne=xe=>{var Ie,ze;const Ee={"single family":"single_family",detached:"single_family",residential:"single_family",condo:"condo",condominium:"condo",apartment:"condo",townhouse:"townhouse",townhome:"townhouse",land:"land",lot:"land","lots and land":"land","multi-family":"multi_family","multi family":"multi_family",duplex:"multi_family",commercial:"commercial"},Me=(xe.propertyType||"").toLowerCase(),Oe=((Ie=Object.entries(Ee).find(([Ve])=>Me.includes(Ve)))==null?void 0:Ie[1])||"other";te(Ve=>({...Ve,property_address:xe.address||Ve.property_address,city:xe.city||Ve.city,state:xe.state||Ve.state,price:xe.price?String(xe.price):Ve.price,property_type:Oe,bedrooms:xe.bedrooms?String(xe.bedrooms):Ve.bedrooms,bathrooms:xe.bathrooms?String(xe.bathrooms):Ve.bathrooms,square_footage:xe.sqft?String(xe.sqft):Ve.square_footage,lot_size:xe.lotSize?String(xe.lotSize):Ve.lot_size,year_built:xe.yearBuilt?String(xe.yearBuilt):Ve.year_built,description:xe.description||Ve.description})),((ze=xe.photos)==null?void 0:ze.length)>0&&(d(xe.photos),Z.forEach(Ve=>URL.revokeObjectURL(Ve)),K([]),Q([]))},ae=xe=>{if(!xe)return;const Ee=Array.from(xe);K(Oe=>[...Oe,...Ee]);const Me=Ee.map(Oe=>URL.createObjectURL(Oe));Q(Oe=>[...Oe,...Me])},ue=xe=>{URL.revokeObjectURL(Z[xe]),K(Ee=>Ee.filter((Me,Oe)=>Oe!==xe)),Q(Ee=>Ee.filter((Me,Oe)=>Oe!==xe))},me=async xe=>{var Ee;if(!(!xe||!f)){O(!0);try{for(const Me of Array.from(xe)){const Oe=Me.name.split(".").pop(),Ie=`${a==null?void 0:a.id}/${f.id}/${Date.now()}.${Oe}`,{error:ze}=await U.storage.from("listing-photos").upload(Ie,Me);if(ze)throw ze;const{data:{publicUrl:Ve}}=U.storage.from("listing-photos").getPublicUrl(Ie);await j.mutateAsync({listingId:f.id,photoUrl:Ve,isPrimary:!((Ee=f.photos)!=null&&Ee.length)})}he.success("Photos uploaded!")}catch(Me){console.error("Upload error:",Me),he.error("Failed to upload photos")}finally{O(!1)}}},de=async xe=>{for(let Ee=0;Ee{if(f)try{await N.mutateAsync({photoId:xe,listingId:f.id}),he.success("Photo removed")}catch{he.error("Failed to remove photo")}},je=async xe=>{if(xe.preventDefault(),!W.city.trim()||!W.state.trim()||!W.price){he.error("Please fill in required fields (City, State, Price)");return}if(o&&!D){he.error("Please select an agent to assign this listing to");return}try{const Ee={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 b.mutateAsync({id:s,...Ee}),he.success("Listing updated!"),n(`/mission-control/listings/${s}`);else{O(!0);let Me;if(o&&D?Me=await _.mutateAsync({agentId:D,...Ee}):Me=await y.mutateAsync(Ee),B.length>0)try{await de(Me.id),Z.forEach(Ie=>URL.revokeObjectURL(Ie)),K([]),Q([])}catch(Ie){console.error("Photo upload error:",Ie),he.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Ie=0;Ien(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),o?"Back to Brokerage":"Back to Listings"]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[o&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Assign to Agent *"})}),e.jsxs(Pe,{children:[e.jsxs(Ds,{value:D,onValueChange:R,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select an agent..."})}),e.jsx(Ls,{children:E.map(xe=>e.jsx(lt,{value:xe.id,children:xe.name||xe.email},xe.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"This listing will appear on the selected agent's Listing Exchange."})]})]}),!l&&i&&!o&&e.jsx(qqs,{onImport:ne}),c.length>0&&e.jsxs(ke,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Pt,{className:"pb-3",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(li,{className:"h-4 w-4 text-primary"}),"MLS Photos (",c.length,")"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These photos will be imported when you save the listing."})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((xe,Ee)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:xe,alt:"",className:"w-full h-full object-cover"})},Ee)),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(q,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx($r,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Property Details"})}),e.jsx(Pe,{className:"space-y-4",children:e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[e.jsx(ce,{children:"Property Address"}),e.jsx(Ne,{value:W.property_address,onChange:xe=>te({...W,property_address:xe.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"City *"}),e.jsx(Ne,{value:W.city,onChange:xe=>te({...W,city:xe.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"State *"}),e.jsx(Ne,{value:W.state,onChange:xe=>te({...W,state:xe.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Neighborhood"}),e.jsx(Ne,{value:W.neighborhood,onChange:xe=>te({...W,neighborhood:xe.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Price *"}),e.jsx(Ne,{type:"number",value:W.price,onChange:xe=>te({...W,price:xe.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Property Type"}),e.jsxs(Ds,{value:W.property_type,onValueChange:xe=>te({...W,property_type:xe}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:Zqs.map(xe=>e.jsx(lt,{value:xe.value,children:xe.label},xe.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Status"}),e.jsxs(Ds,{value:W.status,onValueChange:xe=>te({...W,status:xe}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:Yqs.map(xe=>e.jsx(lt,{value:xe.value,children:xe.label},xe.value))})]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Property Specs (Optional)"})}),e.jsx(Pe,{children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Bedrooms"}),e.jsx(Ne,{type:"number",value:W.bedrooms,onChange:xe=>te({...W,bedrooms:xe.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Bathrooms"}),e.jsx(Ne,{type:"number",step:"0.5",value:W.bathrooms,onChange:xe=>te({...W,bathrooms:xe.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Sq Ft"}),e.jsx(Ne,{type:"number",value:W.square_footage,onChange:xe=>te({...W,square_footage:xe.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Lot Size"}),e.jsx(Ne,{value:W.lot_size,onChange:xe=>te({...W,lot_size:xe.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Year Built"}),e.jsx(Ne,{type:"number",value:W.year_built,onChange:xe=>te({...W,year_built:xe.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Rr,{checked:W.has_hoa,onCheckedChange:xe=>te({...W,has_hoa:xe})}),e.jsx(ce,{children:"Has HOA"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Description & Links"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{value:W.description,onChange:xe=>te({...W,description:xe.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Agent Notes"}),e.jsx(pr,{value:W.agent_notes,onChange:xe=>te({...W,agent_notes:xe.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{checked:W.agent_notes_public,onCheckedChange:xe=>te({...W,agent_notes_public:xe})}),e.jsx(ce,{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(ce,{children:"MLS Link"}),e.jsx(Ne,{value:W.mls_link,onChange:xe=>te({...W,mls_link:xe.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Video Link"}),e.jsx(Ne,{value:W.video_link,onChange:xe=>te({...W,video_link:xe.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(bn,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Pe,{children:e.jsx(Gqs,{selectedVideoId:W.video_id,onVideoSelect:xe=>te({...W,video_id:xe}),listingId:l?s:void 0})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Photos"})}),e.jsx(Pe,{children:l&&(f!=null&&f.photos)?e.jsx(Hqs,{photos:f.photos,uploading:F,onUpload:xe=>me(xe),onRemove:xe=>fe(xe),onReorder:xe=>{C.mutate({photos:xe.map(Ee=>({id:Ee.id,sort_order:Ee.sort_order,is_primary:Ee.is_primary}))})},onSetPrimary:xe=>{f&&A.mutate({photoId:xe,listingId:f.id})}}):e.jsx(Qqs,{photoUrls:Z,onRemove:ue,onReorder:(xe,Ee)=>{Q(xe),K(Ee)},pendingPhotos:B,uploading:F,onUpload:ae})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(li,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Pe,{children:l&&s?e.jsx(Kqs,{listingId:s}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save the listing first, then you can upload PDFs (disclosures, floor plans, HOA docs, etc.) for other agents to download."})})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Sharing & Collaboration"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(Rr,{checked:W.allow_sharing,onCheckedChange:xe=>te({...W,allow_sharing:xe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(Rr,{checked:W.open_to_referrals,onCheckedChange:xe=>te({...W,open_to_referrals:xe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(Rr,{checked:W.open_to_social_promotion,onCheckedChange:xe=>te({...W,open_to_social_promotion:xe})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(Rr,{checked:W.share_with_brokerage,onCheckedChange:xe=>te({...W,share_with_brokerage:xe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(Rr,{checked:W.is_public,onCheckedChange:xe=>te({...W,is_public:xe})})]})]})]}),e.jsx(q,{type:"submit",className:"w-full",size:"lg",disabled:y.isPending||b.isPending,children:y.isPending||b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(C1t,{listingId:u.listingId,open:u.open,onOpenChange:xe=>{if(!xe){const{nextPath:Ee}=u;m({open:!1,listingId:null,nextPath:Ee}),n(Ee)}}})]})}const DCe=[{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"}],M1t=[{type:"extra_video",label:"Extra Video / Reel",icon:bn,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:fF,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:zo,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:u2,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:jn,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:tl,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],Jqs=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],fje={sections:Object.fromEntries(DCe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},eVs=()=>Math.random().toString(36).slice(2,10);function tVs(){const{listingId:s}=xo(),t=qr(),{user:r}=Cs(),n=is(),[a,i]=k.useState("desktop"),[l,o]=k.useState(fje),[c,d]=k.useState(!1),[u,m]=k.useState(0),{data:f,isLoading:x}=pt({queryKey:["listing-customize",s],queryFn:async()=>{const{data:B,error:K}=await U.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(K)throw K;return B},enabled:!!s});k.useEffect(()=>{var B,K;f!=null&&f.page_config&&o({...fje,...f.page_config||{},sections:{...fje.sections,...((B=f.page_config)==null?void 0:B.sections)||{}},addons:((K=f.page_config)==null?void 0:K.addons)||[]})},[f==null?void 0:f.id]);const y=!!r&&!!f&&r.id===f.agent_id,_=k.useMemo(()=>f?`/public/listing/${f.slug||f.id}?preview=1&t=${u}`:"",[f,u]),b=k.useMemo(()=>f?`https://listings.relevelup.com/${f.slug||f.id}`:"",[f]),j=Mt({mutationFn:async()=>{const{error:B}=await U.from("listings").update({page_config:l}).eq("id",s);if(B)throw B},onSuccess:()=>{he.success("Saved. Your public page is live."),d(!1),n.invalidateQueries({queryKey:["listing-customize",s]}),n.invalidateQueries({queryKey:["public-listing"]}),m(B=>B+1)},onError:B=>he.error(`Save failed: ${B.message||"Try again"}`)}),N=B=>{o(K=>({...K,...B})),d(!0)},C=(B,K)=>N({sections:{...l.sections||{},[B]:K}}),A=B=>N({addons:[...l.addons||[],{id:eVs(),type:B,data:{}}]}),E=(B,K)=>N({addons:(l.addons||[]).map(Z=>Z.id===B?{...Z,data:{...Z.data,...K}}:Z)}),D=B=>N({addons:(l.addons||[]).filter(K=>K.id!==B)}),R=(B,K)=>{const Z=[...l.addons||[]],Q=Z.findIndex(te=>te.id===B);if(Q<0)return;const W=Q+K;W<0||W>=Z.length||([Z[Q],Z[W]]=[Z[W],Z[Q]],N({addons:Z}))};if(x)return e.jsx(ws,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!f)return e.jsx(ws,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!y)return e.jsx(ws,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx(q,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${f.id}`),children:"Back"})]})});const F=(l.addons||[]).length,O=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(ws,{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(q,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${f.id}`),children:[e.jsx(Aa,{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:f.property_address||`${f.city}, ${f.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(k_,{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(yg,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>m(B=>B+1),children:[e.jsx(lo,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx(q,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:b,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx(q,{size:"sm",onClick:()=>j.mutate(),disabled:!c||j.isPending,children:j.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ml,{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(ui,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(pO,{icon:e.jsx(Ir,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(B=>e.jsx("button",{onClick:()=>N({hero_style:B}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===B?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:B},B))})]})}),e.jsx(pO,{icon:e.jsx(dl,{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:()=>N({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"}),Jqs.map(B=>e.jsx("button",{onClick:()=>N({accent_color:B}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===B?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:B},"aria-label":B},B))]})}),e.jsx(pO,{icon:e.jsx(p0,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(pr,{value:l.custom_note||"",onChange:B=>N({custom_note:B.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(pO,{icon:e.jsx(Fj,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${O} of ${DCe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:DCe.map(B=>{var Z;const K=((Z=l.sections)==null?void 0:Z[B.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:B.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:B.hint})]}),e.jsx(Rr,{checked:K,onCheckedChange:Q=>C(B.key,Q)})]},B.key)})})}),e.jsxs(pO,{icon:e.jsx(Ys,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:F?`${F} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:M1t.map(B=>e.jsxs("button",{onClick:()=>A(B.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${B.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(B.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:B.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:B.desc})]},B.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((B,K)=>e.jsx(sVs,{addon:B,onChange:Z=>E(B.id,Z),onRemove:()=>D(B.id),onMoveUp:K>0?()=>R(B.id,-1):void 0,onMoveDown:KR(B.id,1):void 0},B.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(q,{className:"w-full",onClick:()=>j.mutate(),disabled:!c||j.isPending,children:j.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ml,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(ke,{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(Nn,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(Xe,{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(la,{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(k_,{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(yg,{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 pO({icon:s,title:t,desc:r,rightLabel:n,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}),r&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:r})]})]}),n&&e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:n})]}),e.jsx("div",{className:"space-y-3",children:a})]})}function sVs({addon:s,onChange:t,onRemove:r,onMoveUp:n,onMoveDown:a}){const i=M1t.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:n,disabled:!n,className:"text-muted-foreground/50 hover:text-foreground disabled:opacity-30 leading-none",children:e.jsx(Vu,{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(q,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(Vu,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:r,"aria-label":"Remove",children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs",children:"Video URL"}),e.jsx(Ne,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(ce,{className:"text-xs",children:"Title (optional)"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(pr,{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(ce,{className:"text-xs",children:"Quote"}),e.jsx(pr,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(ce,{className:"text-xs",children:"Attribution"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"Headline"}),e.jsx(Ne,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(ce,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"Button label"}),e.jsx(Ne,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(ce,{className:"text-xs",children:"Link URL"}),e.jsx(Ne,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const I1t="teleprompter_settings",pje={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function rVs(){try{const s=localStorage.getItem(I1t);return s?{...pje,...JSON.parse(s)}:pje}catch{return pje}}function nVs(s){try{localStorage.setItem(I1t,JSON.stringify(s))}catch{}}function cIe({text:s,isVisible:t,onToggleVisibility:r,isRecording:n=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=k.useRef(null),c=k.useRef(null),d=k.useRef(0),u=k.useRef(0),[m,f]=k.useState(rVs),{scrollSpeed:x,fontSize:y,lineHeight:_,opacity:b,position:j,isMirrored:N}=m,C=k.useCallback((Z,Q)=>{f(W=>{const te={...W,[Z]:Q};return nVs(te),te})},[]),[A,E]=k.useState(!1),[D,R]=k.useState(null),F=k.useCallback(Z=>{if(!o.current)return;d.current===0&&(d.current=Z);const Q=Z-d.current;d.current=Z,u.current+=x*Q/1e3;const W=Math.floor(u.current);W>0&&(o.current.scrollTop+=W,u.current-=W);const{scrollTop:te,scrollHeight:ne,clientHeight:ae}=o.current;if(te+ae>=ne){E(!1);return}c.current=requestAnimationFrame(F)},[x]);k.useEffect(()=>(A?(d.current=0,u.current=0,c.current=requestAnimationFrame(F)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[A,F]),k.useEffect(()=>{if(n&&t)if(o.current&&(o.current.scrollTop=0),a){R(3);let Z=3;const Q=setInterval(()=>{Z-=1,Z<=0?(clearInterval(Q),R(null),i==null||i(),E(!0)):R(Z)},1e3);return()=>clearInterval(Q)}else setTimeout(()=>E(!0),100);else n||(E(!1),R(null))},[n,t,a,i]);const O=k.useCallback(()=>{o.current&&(o.current.scrollTop=0),E(!1)},[]),B=k.useCallback(()=>{E(Z=>!Z)},[]);if(!t)return e.jsx("div",{className:zt("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(q,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const K={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:zt("absolute inset-0 pointer-events-none",l),children:[D!==null&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:D},D),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:zt("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",K[j],D!==null&&"opacity-30"),style:{opacity:D!==null?.3:b},children:e.jsxs("div",{ref:o,className:zt("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",N&&"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(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsx(q,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Bo,{className:"h-4 w-4"})})}),e.jsx(Ko,{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(ce,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x})]}),e.jsx(nf,{value:[x],onValueChange:([Z])=>C("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(ce,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[y,"px"]})]}),e.jsx(nf,{value:[y],onValueChange:([Z])=>C("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(ce,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_.toFixed(1)})]}),e.jsx(nf,{value:[_*10],onValueChange:([Z])=>C("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(ce,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(b*100),"%"]})]}),e.jsx(nf,{value:[b*100],onValueChange:([Z])=>C("opacity",Z/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:j==="top"?"default":"outline",size:"sm",onClick:()=>C("position","top"),children:e.jsx(pg,{className:"h-4 w-4"})}),e.jsx(q,{variant:j==="center"?"default":"outline",size:"sm",onClick:()=>C("position","center"),children:e.jsx(N_,{className:"h-4 w-4"})}),e.jsx(q,{variant:j==="bottom"?"default":"outline",size:"sm",onClick:()=>C("position","bottom"),children:e.jsx(Co,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{className:"text-xs",children:"Mirror Mode"}),e.jsx(Rr,{checked:N,onCheckedChange:Z=>C("isMirrored",Z)})]})]})})]}),e.jsx(q,{variant:"secondary",size:"icon",onClick:B,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:A?e.jsx(Xf,{className:"h-4 w-4"}):e.jsx(Al,{className:"h-4 w-4"})}),e.jsx(q,{variant:"secondary",size:"icon",onClick:O,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(ev,{className:"h-4 w-4"})}),e.jsxs(q,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Wf,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function aVs({onSelectScript:s,onCreateNew:t,selectedScriptId:r,className:n}){const{toast:a}=Ba(),[i,l]=k.useState(""),[o,c]=k.useState(null),[d,u]=k.useState("levelup"),{data:m,isLoading:f}=bzs(),{data:x,isLoading:y}=_zs(),{data:_,isLoading:b}=wzs(),j=jzs(),N=k.useMemo(()=>x?x.filter(R=>{const F=!i||R.title.toLowerCase().includes(i.toLowerCase())||R.script_text.toLowerCase().includes(i.toLowerCase())||R.tags.some(B=>B.toLowerCase().includes(i.toLowerCase())),O=!o||R.category_id===o;return F&&O}):[],[x,i,o]),C=k.useMemo(()=>_?_.filter(R=>!i||R.title.toLowerCase().includes(i.toLowerCase())||R.script_text.toLowerCase().includes(i.toLowerCase())):[],[_,i]),A=R=>{s({title:R.title,text:R.script_text})},E=async R=>{try{await j.mutateAsync(R),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},D=f||y||b;return e.jsxs("div",{className:zt("flex flex-col h-full",n),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search scripts...",value:i,onChange:R=>l(R.target.value),className:"pl-9"})]})}),e.jsxs(ta,{value:d,onValueChange:R=>u(R),className:"flex-1 flex flex-col",children:[e.jsxs(ea,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(rs,{value:"levelup",children:[e.jsx(En,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(rs,{value:"my-scripts",children:[e.jsx(Zy,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(fs,{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(Xe,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),m==null?void 0:m.map(R=>e.jsx(Xe,{variant:o===R.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(R.id),children:R.name},R.id))]}),e.jsx(ui,{className:"flex-1 max-h-[50vh]",children:D?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):N.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(En,{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:N.map(R=>e.jsxs(ke,{className:zt("cursor-pointer hover:bg-accent/50 transition-colors",r===R.id&&"ring-2 ring-primary"),onClick:()=>A(R),children:[e.jsx(Pt,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Dt,{className:"text-sm font-medium truncate",children:R.title}),R.category&&e.jsx(Xe,{variant:"secondary",className:"mt-1 text-xs",children:R.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:F=>{F.stopPropagation(),E(R)},children:e.jsx(Zy,{className:"h-4 w-4"})}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Pe,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:R.script_text})})]},R.id))})})]}),e.jsxs(fs,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(q,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(ui,{className:"flex-1 max-h-[50vh]",children:b?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):C.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Zy,{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:C.map(R=>e.jsxs(ke,{className:zt("cursor-pointer hover:bg-accent/50 transition-colors",r===R.id&&"ring-2 ring-primary"),onClick:()=>A(R),children:[e.jsx(Pt,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Dt,{className:"text-sm font-medium truncate",children:R.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:R.is_custom?e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Pe,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:R.script_text})})]},R.id))})})]})]})]})}function iVs({selectedTemplate:s,onSelect:t,contactName:r,saving:n=!1}){const[a,i]=k.useState(()=>{const o=bP(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(ce,{className:"text-sm font-medium",children:"Share Page Template"}),n&&e.jsx(ls,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:FXt.map(o=>{const c=zXt(o.id),d=a.has(o.id),u=c.some(m=>m.id===s);return e.jsxs(E0,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(A0,{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(Co,{className:zt("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(M0,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(m=>{const f=s===m.id;return e.jsxs("button",{type:"button",onClick:()=>t(m.id),disabled:n,className:zt("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",f?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[f&&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(la,{className:"h-2.5 w-2.5 text-primary-foreground"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"opacity-70 shrink-0",children:m.icon}),e.jsx("span",{className:"text-sm font-medium truncate",children:m.name})]})]},m.id)})})})]},o.id)})}),r&&s!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Will show: "',bP(s).headerText(r),'"']})]})}function P1t({open:s,onOpenChange:t,video:r,contactName:n,onTemplateUpdated:a}){const[i,l]=k.useState(r.page_template||"default"),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[m,f]=k.useState(r.page_template||"default"),[x,y]=k.useState([]),[_,b]=k.useState(r.contact_id&&n?{id:r.contact_id,name:n,email:null}:null),[j,N]=k.useState(!1),[C,A]=k.useState(!1),E=r.share_token?`https://video.relevelup.com/${r.share_token}`:"";k.useEffect(()=>{s&&x.length===0&&D()},[s]);const D=async()=>{A(!0);try{const{data:te,error:ne}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ne)throw ne;const ae=(te||[]).map(ue=>({id:ue.id,name:[ue.first_name,ue.last_name].filter(Boolean).join(" ")||"Unnamed",email:ue.email||null}));y(ae)}catch(te){console.error("Failed to fetch contacts:",te)}finally{A(!1)}},R=async te=>{b(te),N(!1),c(!0);try{const{error:ne}=await U.from("agent_videos").update({contact_id:(te==null?void 0:te.id)||null,recipient_name:(te==null?void 0:te.name)||null}).eq("id",r.id);if(ne)throw ne;he.success(te?`Assigned to ${te.name}`:"Contact removed"),a==null||a()}catch(ne){console.error("Failed to update contact:",ne),he.error("Failed to update contact")}finally{c(!1)}},F=async te=>{l(te),c(!0);try{const{error:ne}=await U.from("agent_videos").update({page_template:te}).eq("id",r.id);if(ne)throw ne;f(te),he.success("Template saved!"),a==null||a()}catch(ne){console.error("Failed to save template:",ne),he.error("Failed to save template"),l(m)}finally{c(!1)}},O=(_==null?void 0:_.name)||null,B=()=>{const te=r.title||"Video Message",ne=r.share_token?`https://video.relevelup.com/thumb/${r.share_token}`:r.thumbnail_url||"";return``},K=async()=>{if(!r.thumbnail_url){he.error("Video thumbnail not available yet");return}const te=B(),ne=`Watch: ${r.title||"Video Message"} ${E}`;try{const ae=new Blob([te],{type:"text/html"}),ue=new Blob([ne],{type:"text/plain"}),me=new ClipboardItem({"text/html":ae,"text/plain":ue});await navigator.clipboard.write([me]),he.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(ne+` `+te),he.success("Copied! Paste into your email.")}},Z=async()=>{await navigator.clipboard.writeText(E),u(!0),he.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},Q=()=>{const ne=bP(i).headerText(O),ae=i==="default"?`Check out this video: ${E}`:`${ne} Check out this special video: ${E}`;window.open(`sms:?body=${encodeURIComponent(ae)}`,"_self")},W=()=>{const te=bP(i),ne=te.headerText(O),ae=i==="default"?r.title||"Video Message":ne,ue=`${te.subText} Watch the video: ${E}`,me=_!=null&&_.email?encodeURIComponent(_.email):"";window.open(`mailto:${me}?subject=${encodeURIComponent(ae)}&body=${encodeURIComponent(ue)}`,"_self")};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(an,{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(ce,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(sl,{open:j,onOpenChange:N,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{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(qi,{className:"h-4 w-4 text-muted-foreground"}),_.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(xg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-[300px] p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search contacts..."}),e.jsxs(kg,{children:[e.jsx(Sg,{children:C?"Loading...":"No contacts found."}),e.jsx(Cg,{children:x.map(te=>e.jsxs(Sp,{value:te.name,onSelect:()=>R(te),children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",(_==null?void 0:_.id)===te.id?"opacity-100":"opacity-0")}),te.name]},te.id))})]})]})})]}),_&&e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>R(null),disabled:o,className:"shrink-0",children:e.jsx($r,{className:"h-4 w-4"})})]}),_&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',bP(i).headerText(_.name),'"']})]}),e.jsx(iVs,{selectedTemplate:i,onSelect:F,contactName:O,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:E,readOnly:!0,className:"font-mono text-sm"}),e.jsx(q,{onClick:Z,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(la,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-4 w-4"}),"Copy"]})})]})]}),r.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Share for Email"}),e.jsxs(q,{variant:"outline",className:"w-full gap-2",onClick:K,children:[e.jsx(zo,{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(ce,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{variant:"outline",className:"flex-1 gap-2",onClick:Q,children:[e.jsx(Ui,{className:"h-4 w-4"}),"Text"]}),e.jsxs(q,{variant:"outline",className:"flex-1 gap-2",onClick:W,children:[e.jsx(Ks,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(fn,{children:e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function oVs(){var We;const s=qr(),[t]=ic(),{toast:r}=Ba(),n=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=Q0t(),{data:u}=Lp(),m=V2(),f=Tzs(),[x,y]=k.useState("record"),[_,b]=k.useState(""),[j,N]=k.useState(!1),[C,A]=k.useState(!1),[E,D]=k.useState(!1),[R,F]=k.useState(null),[O,B]=k.useState(0),[K,Z]=k.useState(0),[Q,W]=k.useState(null),[te,ne]=k.useState(null),[ae,ue]=k.useState(n||""),[me,de]=k.useState(""),[fe,je]=k.useState(""),[xe,Ee]=k.useState(null),[Me,Oe]=k.useState(null),[Ie,ze]=k.useState(null),[Ve,Le]=k.useState(!1),$e=k.useCallback(async(Ce,qe)=>{F(Ce),y("uploading");try{const{videoId:et,uploadUrl:Ze}=await dM(me||"Quick Video Touch");W(et);const{apiKey:rt}=await uM(et),ct=new XMLHttpRequest;ct.upload.onprogress=Yt=>{Yt.lengthComputable&&B(Yt.loaded/Yt.total*100)},await new Promise((Yt,es)=>{ct.onload=()=>{ct.status>=200&&ct.status<300?Yt():es(new Error(`Upload failed: ${ct.status}`))},ct.onerror=()=>es(new Error("Upload failed")),ct.open("PUT",Ze),ct.setRequestHeader("AccessKey",rt),ct.send(Ce)}),y("processing");let vt=0;const kt=Date.now(),St=90*1e3;for(;vt<4;){if(await new Promise(es=>setTimeout(es,3e3)),Date.now()-kt>St){const es=Ce.size/1048576,zs=`https://iframe.mediadelivery.net/play/${et}/${et}`;await m.mutateAsync({bunny_video_id:et,playback_url:zs,file_size_mb:es,title:me||"Quick Video Touch",notes:fe||void 0,contact_id:ae&&ae!=="none"?ae:void 0,status:"processing",touch_type:"video_touch"}),r({title:"Video saved — still processing",description:'Your video has been saved and will appear in your library with a "processing" badge. It will be ready to share once encoding completes (usually within a few minutes).',duration:8e3}),s("/mission-control/video-library");return}const Yt=await W_(et);if(vt=Yt.status,Z(Yt.encodeProgress||0),vt===4)ne({playbackUrl:Yt.directPlayUrl,thumbnailUrl:Yt.thumbnailUrl,previewUrl:Yt.previewUrl||null,duration:Yt.length||qe,fileSizeMb:(Yt.storageSize||Ce.size)/(1024*1024)});else if(vt===5||vt===6)throw new Error("Video processing failed")}y("details")}catch(et){console.error("Upload error:",et),r({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),y("record")}},[me,r]),ve=async()=>{if(!(!Q||!te))try{const Ce=ae&&ae!=="none"?ae:null,qe=await m.mutateAsync({bunny_video_id:Q,contact_id:Ce,playback_url:te.playbackUrl,thumbnail_url:te.thumbnailUrl,preview_url:te.previewUrl,duration_seconds:te.duration,file_size_mb:te.fileSizeMb,title:me||"Quick Video Touch",notes:fe,task_id:a||null,status:"ready"});Ee(qe.id),Oe(qe.share_token||null),Ce&&await f.mutateAsync({contactId:Ce,videoId:qe.id,notes:fe}),r({title:"Video saved successfully!"}),y("share")}catch(Ce){console.error("Save video error:",Ce),r({title:"Failed to save video",description:(Ce==null?void 0:Ce.message)||"Please try again.",variant:"destructive"})}},Qe=(Ce,qe)=>{navigator.clipboard.writeText(qe),ze(Ce),setTimeout(()=>ze(null),2e3),r({title:"Copied to clipboard!"})},we=()=>Me?`https://video.relevelup.com/${Me}`:(te==null?void 0:te.playbackUrl)||"",nt=()=>{const Ce=u==null?void 0:u.find(ct=>ct.id===ae),qe=Ce?`${Ce.first_name}`:"",et=(Ce==null?void 0:Ce.phone)||"",Ze=(Ce==null?void 0:Ce.email)||"",rt=we();return{text:`Hey${qe?` ${qe}`:""}! I recorded a quick video for you: ${rt}`,link:rt,contactPhone:et,contactEmail:Ze}},Se=()=>{const{text:Ce,contactPhone:qe}=nt(),et=qe?`sms:${qe}?body=${encodeURIComponent(Ce)}`:`sms:?body=${encodeURIComponent(Ce)}`;window.open(et,"_self")},Ge=()=>{const{link:Ce,contactEmail:qe}=nt(),et="Check out this video",Ze=`I recorded a quick video for you: ${Ce}`,rt=qe?`mailto:${qe}?subject=${encodeURIComponent(et)}&body=${encodeURIComponent(Ze)}`:`mailto:?subject=${encodeURIComponent(et)}&body=${encodeURIComponent(Ze)}`;window.open(rt,"_self")};return i?e.jsx(ws,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(Aa,{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(q,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(En,{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"]})]})]})]}),x==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(pM,{maxDurationSeconds:600,onRecordingComplete:$e,onRecordingStateChange:D,className:"w-full",teleprompterContent:j&&_&&e.jsx(cIe,{text:_,isVisible:j,onToggleVisibility:()=>N(!1),isRecording:E,startCountdown:!1})}),!j&&_&&e.jsxs(q,{variant:"outline",className:"mt-4",onClick:()=>N(!0),children:[e.jsx(En,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(ke,{className:"lg:col-span-1",children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx(pr,{placeholder:"Type or paste your script here...",value:_,onChange:Ce=>b(Ce.target.value),rows:6}),e.jsxs(sw,{open:C,onOpenChange:A,children:[e.jsx(mge,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:"w-full",children:[e.jsx(En,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(U1,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(rw,{className:"p-4 border-b",children:e.jsx(nw,{children:"Select a Script"})}),e.jsx(aVs,{onSelectScript:Ce=>{b(Ce.text),A(!1),N(!0)},className:"h-[calc(100vh-80px)]"})]})]}),_&&e.jsx(q,{className:"w-full",onClick:()=>N(!0),children:"Use Script"})]})]})]}),x==="uploading"&&e.jsx(ke,{className:"max-w-md mx-auto",children:e.jsxs(Pe,{className:"pt-6 text-center",children:[e.jsx(ka,{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(ki,{value:O,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[O.toFixed(0),"%"]})]})}),x==="processing"&&e.jsx(ke,{className:"max-w-md mx-auto",children:e.jsxs(Pe,{className:"pt-6 text-center space-y-4",children:[e.jsx(ls,{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(ki,{value:K,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[K.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.`})]})}),x==="details"&&e.jsxs(ke,{className:"max-w-lg mx-auto",children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Video Details"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Title"}),e.jsx(Ne,{value:me,onChange:Ce=>de(Ce.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Attach to Contact (Optional)"}),e.jsxs(Ds,{value:ae,onValueChange:ue,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"No contact - use anywhere"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(tl,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(Ce=>e.jsx(lt,{value:Ce.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qi,{className:"h-4 w-4"}),Ce.first_name," ",Ce.last_name]})},Ce.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Notes"}),e.jsx(pr,{value:fe,onChange:Ce=>je(Ce.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(q,{className:"w-full",onClick:ve,disabled:m.isPending,children:[m.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),x==="share"&&e.jsxs(ke,{className:"max-w-lg mx-auto",children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Share your video with one click:"}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs(q,{variant:"outline",className:"justify-start",onClick:Se,children:[e.jsx(Ui,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(q,{variant:"outline",className:"justify-start",onClick:Ge,children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(q,{variant:"outline",className:"justify-start",onClick:()=>Qe("link",nt().link),children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Ie==="link"&&e.jsx(la,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(q,{variant:"outline",className:"justify-start",onClick:()=>Le(!0),children:[e.jsx(dl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(q,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(q,{onClick:()=>{y("record"),F(null),W(null),ne(null)},children:"Record Another"})]})]})]}),xe&&Me&&e.jsx(P1t,{open:Ve,onOpenChange:Le,video:{id:xe,share_token:Me,title:me||null,contact_id:ae||null,thumbnail_url:(te==null?void 0:te.thumbnailUrl)||null},contactName:((We=u==null?void 0:u.find(Ce=>Ce.id===ae))==null?void 0:We.first_name)||null})]})}):e.jsx(ws,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(du,{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(q,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function lVs({open:s,onOpenChange:t,video:r,gmailEmail:n,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=k.useState([]),[c,d]=k.useState(null),[u,m]=k.useState(!1),[f,x]=k.useState(!1),[y,_]=k.useState(""),[b,j]=k.useState(""),[N,C]=k.useState(""),[A,E]=k.useState(!1),D=G0t(),R=r.share_token?`https://video.relevelup.com/share/video/${r.share_token}`:"",F=r.share_token?`https://video.relevelup.com/thumb/${r.share_token}`:a||r.thumbnail_url||"",O=r.title||"Video Message";k.useEffect(()=>{s&&l.length===0&&B()},[s]),k.useEffect(()=>{if(s&&(j(`I recorded a video for you — ${O}`),C("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),_(""),r.contact_id)){const ne=l.find(ae=>ae.id===r.contact_id);ne&&(d(ne),_(ne.email||""))}},[s,r.contact_id,l]);const B=async()=>{x(!0);try{const{data:ne,error:ae}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ae)throw ae;o(ne||[])}catch{console.error("Failed to fetch contacts")}finally{x(!1)}},K=ne=>{d(ne),m(!1),_(ne.email||""),C(`Hey ${ne.first_name}! I recorded a quick video just for you. Click below to watch it:`),j(`I recorded a video for you — ${O}`)},Z=()=>{d(null),_(""),C("Hey! I recorded a quick video just for you. Click below to watch it:")},Q=ne=>`${ne.first_name} ${ne.last_name||""}`.trim(),W=ne=>{const ae=N.split(/\n\n+/).map(de=>`

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

`).join(""),ue=ne?K0t(ne):R,me=ne?``:"";return`
${ae}

▶ Watch Video

${me}
`},te=async()=>{var ne;if(!y){he.error("Please enter a recipient email");return}if(!R){he.error("Video does not have a share link");return}E(!0);try{let ae;try{const je=c?Q(c):y.split("@")[0];ae=(await D.mutateAsync({video_id:r.id,recipient_email:y,recipient_name:je,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(je){console.warn("Failed to create tracking record, sending without tracking:",je)}const ue=W(ae),{data:me,error:de}=await U.functions.invoke("gmail-send",{body:{to:y,subject:b,body:ue,contactId:(c==null?void 0:c.id)||null}});let fe=null;if(de&&((ne=de.context)!=null&&ne.json))try{fe=await de.context.json()}catch{}if((fe==null?void 0:fe.error)==="insufficient_scope"||(me==null?void 0:me.error)==="insufficient_scope"){he.error((fe==null?void 0:fe.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(de)throw new Error((fe==null?void 0:fe.message)||de.message);if(!(me!=null&&me.success))throw new Error((me==null?void 0:me.error)||"Failed to send");he.success("Video email sent!"),t(!1),i==null||i()}catch(ae){console.error("Gmail send error:",ae),he.error("Failed to send: "+(ae instanceof Error?ae.message:"Unknown error"))}finally{E(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),n&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:n})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(sl,{open:u,onOpenChange:m,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qi,{className:"h-4 w-4 text-muted-foreground"}),Q(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(xg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-[350px] p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search contacts..."}),e.jsxs(kg,{children:[e.jsx(Sg,{children:f?"Loading...":"No contacts found."}),e.jsx(Cg,{children:l.filter(ne=>ne.email).map(ne=>e.jsxs(Sp,{value:`${ne.first_name} ${ne.last_name||""} ${ne.email||""}`,onSelect:()=>K(ne),children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",(c==null?void 0:c.id)===ne.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Q(ne)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ne.email})]})]},ne.id))})]})]})})]}),c&&e.jsx(q,{variant:"ghost",size:"icon",onClick:Z,className:"shrink-0",children:e.jsx($r,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(Ne,{id:"video-to",value:y,onChange:ne=>_(ne.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"video-subject",children:"Subject"}),e.jsx(Ne,{id:"video-subject",value:b,onChange:ne=>j(ne.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(pr,{id:"video-message",value:N,onChange:ne=>C(ne.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(ce,{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:[F?e.jsx("img",{src:F,alt:O,className:"w-full aspect-video object-cover"}):e.jsx("div",{className:"w-full aspect-video flex items-center justify-center bg-muted",children:e.jsx(Al,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/80 flex items-center justify-center shadow",children:e.jsx(Al,{className:"h-5 w-5 text-primary ml-0.5"})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will see the thumbnail with a play button. Clicking opens the video page."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),e.jsxs(q,{onClick:te,disabled:A||!y||!b,className:"gap-2",children:[A?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"}),A?"Sending...":"Send Video Email"]})]})]})]})})}const cVs=()=>{const{user:s}=Cs();return pt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.rpc("get_team_videos",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})};function dVs({recipient:s}){return s.watched_at?e.jsxs(Xe,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Al,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(Xe,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(dm,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(Xe,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(Nn,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(Xe,{variant:"outline",className:"text-[10px]",children:[e.jsx(hn,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function uVs({open:s,onOpenChange:t,videoId:r,videoTitle:n}){const{data:a=[],isLoading:i}=rzs(r);return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Mo,{className:"h-5 w-5"}),"Send Analytics: ",n]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(dr,{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(ui,{className:"h-[400px]",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Recipient"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Sent"}),e.jsx(At,{children:"Last Activity"})]})}),e.jsx(ha,{children:a.map(l=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.recipient_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.recipient_email})]})}),e.jsx(xt,{children:e.jsx(dVs,{recipient:l})}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:As(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?Nl(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function hVs(){const{data:s,isLoading:t}=nzs(),{data:r=[],isLoading:n}=azs(),[a,i]=k.useState(null),l=t||n,o=r.reduce((c,d)=>{const u=d.agent_videos,m=(u==null?void 0:u.id)||d.video_id;return c[m]||(c[m]={videoId:m,title:(u==null?void 0:u.title)||"Untitled",thumbnailUrl:u==null?void 0:u.thumbnail_url,recipients:[]}),c[m].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(dr,{className:"h-4 w-20"})}),e.jsx(Pe,{children:e.jsx(dr,{className:"h-8 w-16"})})]},d))})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(hn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(Nn,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.openRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalOpened)||0," opened"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(dm,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.clickRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalClicked)||0," clicked"]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Ur,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Pe,{children:Object.keys(o).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No tracked sends yet. Send a video via Gmail to start tracking."}):e.jsx("div",{className:"space-y-2",children:Object.values(o).map(c=>{const d=c.recipients.filter(m=>m.opened_at).length,u=c.recipients.filter(m=>m.clicked_at).length;return e.jsxs("button",{onClick:()=>i({id:c.videoId,title:c.title}),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-left",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:c.thumbnailUrl?e.jsx("img",{src:c.thumbnailUrl,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer",onError:m=>{const f=m.currentTarget;f.style.display="none",f.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(bn,{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(hn,{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(Nn,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(dm,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(Wo,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(uVs,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function mVs({previewSrc:s,thumbnailSrc:t,alt:r,isHovered:n}){const[a,i]=k.useState(!1),[l,o]=k.useState(!1),c=n&&s&&!a,d=t&&!l;return!d&&!c?e.jsx("div",{className:"w-full h-full flex items-center justify-center absolute inset-0 bg-muted",children:e.jsx(bn,{className:"h-12 w-12 text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[d&&e.jsx("img",{src:t,alt:r,loading:"lazy",className:`w-full h-full object-cover absolute inset-0 transition-opacity duration-200 ${c?"opacity-0":"opacity-100"}`,onError:()=>o(!0)}),c&&e.jsx("img",{src:s,alt:r,className:"w-full h-full object-cover absolute inset-0",onError:()=>i(!0)})]})}function fVs({video:s,previewSrc:t,thumbnailSrc:r,onOpen:n,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:m,isGmailConnected:f,getContactName:x,getShareUrl:y,copyToClipboard:_,formatDuration:b}){const[j,N]=k.useState(!1);return e.jsxs(ke,{className:"overflow-hidden group cursor-pointer",onClick:n,onMouseEnter:()=>N(!0),onMouseLeave:()=>N(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(mVs,{previewSrc:t,thumbnailSrc:r,alt:s.title||"Video preview",isHovered:j}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(Al,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:b(s.duration_seconds)}),s.status!=="ready"&&e.jsx(Xe,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Pe,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(qi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:x(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(jn,{className:"h-3 w-3"}),e.jsx("span",{children:As(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(Nn,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),f&&s.share_token&&e.jsxs(q,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:C=>{C.stopPropagation(),m==null||m()},children:[e.jsx(Ks,{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(qi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:x(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(jn,{className:"h-3 w-3"}),e.jsx("span",{children:As(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(Nn,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:C=>C.stopPropagation(),children:e.jsx(Fy,{className:"h-4 w-4"})})}),e.jsxs(Sd,{align:"end",className:"bg-popover",children:[e.jsxs(ti,{onClick:C=>{C.stopPropagation(),n()},children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(z_,{}),e.jsxs(ti,{onClick:C=>{C.stopPropagation(),u()},children:[e.jsx(dl,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(ti,{onClick:C=>{C.stopPropagation(),_(y(s),"Share link")},children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(ti,{onClick:C=>{C.stopPropagation(),o()},children:[e.jsx(TE,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(ti,{onClick:C=>{C.stopPropagation(),c()},children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(ti,{onClick:C=>{C.stopPropagation(),d()},children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),f&&s.share_token&&e.jsxs(ti,{onClick:C=>{C.stopPropagation(),m==null||m()},children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(ti,{onClick:C=>{C.stopPropagation(),i()},children:[e.jsx(Ua,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(z_,{}),s.contact_id&&e.jsxs(ti,{onClick:C=>{C.stopPropagation(),l()},children:[e.jsx(qi,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(ti,{onClick:C=>{C.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function pVs(){var zs,sr;const s=qr(),{data:t,isLoading:r,refetch:n}=Nzs(),{data:a}=wye(),{data:i}=Lp(),l=Czs(),o=Szs(),{isGmailConnected:c,gmailEmail:d}=Cm(),{data:u}=uv(),{data:m=[],isLoading:f}=cVs(),[x,y]=k.useState("my"),[_,b]=k.useState(""),[j,N]=k.useState(null),[C,A]=k.useState(!1),[E,D]=k.useState(!1),[R,F]=k.useState(!1),[O,B]=k.useState(!1),[K,Z]=k.useState(!1),[Q,W]=k.useState(""),[te,ne]=k.useState(!1),[ae,ue]=k.useState(!1),[me,de]=k.useState(!1),[fe,je]=k.useState(!1),[xe,Ee]=k.useState(""),[Me,Oe]=k.useState({}),Ie=ms=>{if(!ms)return"Unassigned";const gt=i==null?void 0:i.find(Ut=>Ut.id===ms);return gt?`${gt.first_name} ${gt.last_name||""}`.trim():"Unknown"},ze=ms=>{if(!ms)return"0:00";const gt=Math.floor(ms/60),Ut=ms%60;return`${gt}:${Ut.toString().padStart(2,"0")}`},[Ve,Le]=k.useState("all"),$e=t==null?void 0:t.filter(ms=>{const gt=ms.category||"general";if(Ve==="general"&>!=="general"||Ve==="open_house"&>!=="open_house")return!1;if(!_)return!0;const Ut=Ie(ms.contact_id).toLowerCase(),ht=(ms.title||"").toLowerCase(),Jt=(ms.notes||"").toLowerCase();return Ut.includes(_.toLowerCase())||ht.includes(_.toLowerCase())||Jt.includes(_.toLowerCase())}),ve=(t==null?void 0:t.filter(ms=>(ms.category||"general")==="open_house").length)||0,Qe=(t==null?void 0:t.filter(ms=>(ms.category||"general")==="general").length)||0,we=(t||[]).filter(ms=>ms.status==="processing"&&ms.bunny_video_id).map(ms=>ms.id).join(",");k.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const gt=t.filter(ht=>ht.status==="processing"&&ht.bunny_video_id);if(!gt.length)return;let Ut=!1;for(const ht of gt)try{const{data:Jt,error:Ms}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:ht.bunny_video_id,isAgentVideo:!0}});if(Ms||!Jt)continue;Jt.status===4&&(await U.from("agent_videos").update({status:"ready",playback_url:Jt.directPlayUrl,thumbnail_url:Jt.thumbnailUrl,preview_url:Jt.previewUrl,duration_seconds:Jt.length||ht.duration_seconds,updated_at:new Date().toISOString()}).eq("id",ht.id),Ut=!0)}catch(Jt){console.warn("Reconcile check failed for video",ht.id,Jt)}Ut&&n()})()},[we,n]),k.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const gt=t.filter(ts=>(ts==null?void 0:ts.bunny_video_id)&&!Me[ts.id]);if(!gt.length)return;const Ut=gt.map(ts=>ts.bunny_video_id),{data:ht,error:Jt}=await U.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Ut,isAgentVideo:!0}});if(Jt)throw Jt;const Ms=(ht==null?void 0:ht.assets)||{};Oe(ts=>{const Xs={...ts};for(const js of gt)Ms[js.bunny_video_id]&&(Xs[js.id]={previewUrl:Ms[js.bunny_video_id].previewUrl,thumbnailUrl:Ms[js.bunny_video_id].thumbnailUrl});return Xs})})().catch(gt=>console.warn("Failed to load signed Bunny asset URLs",gt))},[t,Me]);const nt=(a==null?void 0:a.total_storage_mb)||0,Se=(a==null?void 0:a.max_storage_mb)||1024,Ge=nt/Se*100,We=Ge>=80,Ce=Ge>=100,qe=async(ms,gt)=>{await navigator.clipboard.writeText(ms),he.success(`${gt} copied to clipboard`)},et=ms=>ms.share_token?`https://video.relevelup.com/${ms.share_token}`:ms.playback_url||"",Ze=ms=>{const gt=et(ms),Ut=i==null?void 0:i.find(js=>js.id===ms.contact_id),ht=Ie(ms.contact_id),Jt=ht!=="Unassigned"?ht.split(" ")[0]:"",Ms=(Ut==null?void 0:Ut.phone)||"",ts=`Hey${Jt?` ${Jt}`:""}! I recorded a quick video message for you. Check it out: ${gt}`,Xs=Ms?`sms:${Ms}?body=${encodeURIComponent(ts)}`:`sms:?body=${encodeURIComponent(ts)}`;window.open(Xs,"_self")},rt=ms=>{const gt=i==null?void 0:i.find(Xs=>Xs.id===ms.contact_id),Ut=(gt==null?void 0:gt.email)||"",ht=et(ms),Jt="Check out this video",Ms=`I recorded a quick video for you: ${ht}`,ts=Ut?`mailto:${Ut}?subject=${encodeURIComponent(Jt)}&body=${encodeURIComponent(Ms)}`:`mailto:?subject=${encodeURIComponent(Jt)}&body=${encodeURIComponent(Ms)}`;window.open(ts,"_self")},ct=ms=>{var Jt;const gt=et(ms),Ut=ms.title||"Video Message",ht=ms.share_token?`https://video.relevelup.com/thumb/${ms.share_token}`:((Jt=Me[ms.id])==null?void 0:Jt.thumbnailUrl)||ms.thumbnail_url||"";return``},vt=async ms=>{if(!ms.thumbnail_url&&!ms.share_token){he.error("Video thumbnail not available yet");return}const gt=ct(ms),Ut=et(ms),ht=`Watch: ${ms.title||"Video Message"} ${Ut}`;try{const Jt=new Blob([gt],{type:"text/html"}),Ms=new Blob([ht],{type:"text/plain"}),ts=new ClipboardItem({"text/html":Jt,"text/plain":Ms});await navigator.clipboard.write([ts]),he.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(ht+` `+gt),he.success("Copied! Paste into your email.")}},kt=async ms=>{try{he.loading("Preparing download...",{id:"download"});const{data:gt,error:Ut}=await U.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:ms.bunny_video_id,isAgentVideo:!0}});if(Ut||!(gt!=null&>.downloadUrl))throw new Error((Ut==null?void 0:Ut.message)||"Failed to get download URL");const Jt=`${((ms.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Ms=await fetch(gt.downloadUrl);if(!Ms.ok)throw new Error("Failed to fetch video file");const ts=await Ms.blob(),Xs=URL.createObjectURL(ts),js=document.createElement("a");js.href=Xs,js.download=Jt,js.rel="noreferrer",document.body.appendChild(js),js.click(),js.remove(),URL.revokeObjectURL(Xs),he.success("Download started",{id:"download"})}catch(gt){console.error("Download error:",gt),he.error("Could not force download (your browser may block it).",{id:"download"})}},St=async ms=>{N(ms),ne(!0),W(""),Z(!0);try{const{data:gt,error:Ut}=await U.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:ms.bunny_video_id,title:ms.title,isAgentVideo:!0,shareToken:ms.share_token}});if(Ut||!(gt!=null&>.html))throw new Error("Failed to generate CRM embed code");W(gt.html)}catch(gt){console.error("CRM embed error:",gt),he.error("Failed to generate CRM embed code"),Z(!1)}finally{ne(!1)}},Yt=ms=>{N(ms),A(!0)},es=async()=>{if(j)try{await l.mutateAsync({id:j.id,bunnyVideoId:j.bunny_video_id,hardDelete:!0}),D(!1),N(null),he.success("Video deleted successfully")}catch{he.error("Failed to delete video")}};return e.jsx(ws,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>y("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${x==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((zs=u.team)==null?void 0:zs.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 ${x==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Dr,{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 ${x==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Mo,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),x==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(q,{variant:"outline",onClick:()=>F(!0),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(q,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),x==="team"?e.jsx(xVs,{videos:m,isLoading:f,searchTerm:_,setSearchTerm:b}):x==="analytics"?e.jsx(hVs,{}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:We?"border-amber-500":Ce?"border-destructive":"",children:e.jsxs(Pe,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(TF,{className:`h-5 w-5 ${Ce?"text-destructive":We?"text-amber-500":"text-muted-foreground"}`}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Storage Used"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[nt.toFixed(1)," MB / ",Se>=1024?`${(Se/1024).toFixed(0)} GB`:`${Se} MB`]})]}),e.jsx(ki,{value:Math.min(Ge,100),className:`h-2 ${Ce?"[&>div]:bg-destructive":We?"[&>div]:bg-amber-500":""}`})]}),We&&!Ce&&e.jsxs(Xe,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(go,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ce&&e.jsxs(Xe,{variant:"destructive",children:[e.jsx(go,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ce&&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:Qe},{id:"open_house",label:"Open House Tours",count:ve}].map(ms=>e.jsxs("button",{onClick:()=>Le(ms.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ve===ms.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[ms.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:ms.count})]},ms.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search videos by contact, title, or notes...",value:_,onChange:ms=>b(ms.target.value),className:"pl-10"})]}),r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):($e==null?void 0:$e.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(bn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No videos yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Record your first video touch to get started"}),e.jsxs(q,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Ys,{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:$e==null?void 0:$e.map(ms=>{var gt,Ut;return e.jsx(fVs,{video:ms,previewSrc:(gt=Me[ms.id])==null?void 0:gt.previewUrl,thumbnailSrc:(Ut=Me[ms.id])==null?void 0:Ut.thumbnailUrl,onOpen:()=>Yt(ms),onDelete:()=>{N(ms),D(!0)},onRename:()=>{N(ms),Ee(ms.title||""),je(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${ms.contact_id}`),onGetEmbedCode:()=>{N(ms),B(!0)},onCopyEmailHtml:()=>vt(ms),onEmbedToCrm:()=>St(ms),onShareWithTemplate:()=>{N(ms),ue(!0)},onSendViaGmail:()=>{N(ms),de(!0)},isGmailConnected:c,getContactName:Ie,getShareUrl:et,copyToClipboard:qe,formatDuration:ze},ms.id)})}),e.jsx(vs,{open:C,onOpenChange:A,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:(j==null?void 0:j.title)||"Video Preview"}),e.jsx(an,{children:(j==null?void 0:j.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qi,{className:"h-3 w-3"}),Ie(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(ls,{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(q,{variant:"outline",size:"sm",onClick:()=>{A(!1),n()},children:[e.jsx(lo,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:j.playback_url?(()=>{let ms=j.playback_url;return ms.includes("iframe.mediadelivery.net/play/")&&(ms=ms.replace("/play/","/embed/"),ms+=(ms.includes("?")?"&":"?")+"autoplay=false&responsive=true"),ms.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:ms,title:j.title||"Video preview",className:"absolute top-0 left-0 w-full h-full rounded-lg",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):e.jsx("video",{src:j.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:j.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>he.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(bn,{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(q,{variant:"outline",onClick:()=>Ze(j),children:[e.jsx(Ui,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(q,{variant:"outline",onClick:()=>rt(j),children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(q,{variant:"outline",onClick:()=>qe(et(j),"Share link"),children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(q,{variant:"outline",onClick:()=>vt(j),children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(q,{variant:"outline",onClick:()=>kt(j),children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(q,{variant:"outline",onClick:()=>{A(!1),St(j)},children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(q,{variant:"outline",onClick:()=>{A(!1),ue(!0)},children:[e.jsx(dl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(j==null?void 0:j.share_token)&&e.jsxs(q,{variant:"outline",onClick:()=>{A(!1),de(!0)},children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(q,{variant:"destructive",onClick:()=>{A(!1),D(!0)},children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(vs,{open:E,onOpenChange:D,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Delete Video"}),e.jsx(an,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(q,{variant:"destructive",onClick:es,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(J0t,{open:R,onOpenChange:F}),e.jsx(vs,{open:O,onOpenChange:B,children:e.jsxs(ys,{className:"sm:max-w-lg",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Embed Video"}),e.jsx(an,{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(ce,{children:"Embed Code"}),e.jsx(pr,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(q,{className:"flex-1",onClick:()=>{const ms=``;qe(ms,"Embed code")},children:[e.jsx(si,{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(P1t,{open:ae,onOpenChange:ue,video:j,contactName:Ie(j.contact_id)}),j&&e.jsx(lVs,{open:me,onOpenChange:de,video:j,gmailEmail:d,signedThumbnailUrl:(sr=Me[j.id])==null?void 0:sr.thumbnailUrl}),e.jsx(vs,{open:fe,onOpenChange:je,children:e.jsxs(ys,{className:"max-w-sm",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Rename Video"}),e.jsx(an,{children:"Enter a new title for this video."})]}),e.jsx(Ne,{value:xe,onChange:ms=>Ee(ms.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:ms=>{ms.key==="Enter"&&xe.trim()&&o.mutate({id:j.id,title:xe.trim()},{onSuccess:()=>{he.success("Video renamed"),je(!1)}})}}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>je(!1),children:"Cancel"}),e.jsx(q,{disabled:!xe.trim()||o.isPending,onClick:()=>{o.mutate({id:j.id,title:xe.trim()},{onSuccess:()=>{he.success("Video renamed"),je(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(vs,{open:K,onOpenChange:Z,children:e.jsxs(ys,{className:"sm:max-w-lg",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(an,{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."})]}),te?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):Q?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"CRM Email HTML"}),e.jsx(pr,{readOnly:!0,rows:12,value:Q,className:"font-mono text-xs"})]}),e.jsxs(q,{className:"w-full",onClick:()=>{qe(Q,"CRM embed code")},children:[e.jsx(si,{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 xVs({videos:s,isLoading:t,searchTerm:r,setSearchTerm:n}){const a=k.useMemo(()=>{if(!r)return s;const o=r.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,r]),i=k.useMemo(()=>{const o=new Map;return a.forEach(c=>{const d=o.get(c.owner_user_id);d?d.videos.push(c):o.set(c.owner_user_id,{name:c.owner_name,avatar:c.owner_avatar_url,videos:[c]})}),Array.from(o.entries())},[a]),l=o=>{if(!o)return"0:00";const c=Math.floor(o/60),d=o%60;return`${c}:${d.toString().padStart(2,"0")}`};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search team videos by title, owner, or recipient...",value:r,onChange:o=>n(o.target.value),className:"pl-10"})]}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):a.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(Dr,{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(Wn,{className:"h-7 w-7",children:[e.jsx(Xa,{src:c.avatar||""}),e.jsx(Kn,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(Xe,{variant:"secondary",className:"text-xs",children:c.videos.length})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:c.videos.map(d=>e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs("div",{className:"relative aspect-video bg-muted flex items-center justify-center",children:[d.thumbnail_url?e.jsx("img",{src:d.thumbnail_url,alt:d.title||"Video",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:u=>{u.target.style.display="none"}}):e.jsx(bn,{className:"h-10 w-10 text-muted-foreground"}),d.duration_seconds&&e.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:l(d.duration_seconds)})]}),e.jsxs(Pe,{className:"p-3",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:d.title||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[d.recipient_name&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qi,{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(Nn,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),As(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const gVs=()=>{const{user:s}=Cs();return pt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.rpc("get_team_deals",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})},TKe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function yVs({open:s,onOpenChange:t}){const{data:r,isLoading:n}=gVs(),[a,i]=k.useState(""),[l,o]=k.useState("all"),c=k.useMemo(()=>{if(!r)return new Map;const y=new Map;let _=0;return r.forEach(b=>{y.has(b.owner_user_id)||(y.set(b.owner_user_id,{name:b.owner_name||"Unknown",avatar:b.owner_avatar_url,color:TKe[_%TKe.length]}),_++)}),y},[r]),d=k.useMemo(()=>Array.from(c.entries()).map(([y,_])=>({id:y,..._})),[c]),u=k.useMemo(()=>{if(!r)return[];let y=r;if(l!=="all"&&(y=y.filter(_=>_.owner_user_id===l)),a.trim()){const _=a.toLowerCase();y=y.filter(b=>{var j,N,C,A;return b.deal_name.toLowerCase().includes(_)||((j=b.contact_name)==null?void 0:j.toLowerCase().includes(_))||((N=b.property_address)==null?void 0:N.toLowerCase().includes(_))||((C=b.city)==null?void 0:C.toLowerCase().includes(_))||((A=b.owner_name)==null?void 0:A.toLowerCase().includes(_))})}return y},[r,a,l]),m=k.useMemo(()=>{const y=new Map;return u.forEach(_=>{const b=_.stage_name||"Unknown";y.has(b)||y.set(b,{name:b,color:_.stage_color,icon:_.stage_icon,deals:[],totalValue:0});const j=y.get(b);j.deals.push(_),j.totalValue+=_.sale_price||0}),Array.from(y.values())},[u]),f=y=>y>=1e6?`$${(y/1e6).toFixed(1)}M`:y>=1e3?`$${(y/1e3).toFixed(0)}K`:`$${y.toFixed(0)}`,x=y=>y?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(y):null;return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Dr,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search deals...",value:a,onChange:y=>i(y.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:l,onValueChange:o,children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{placeholder:"All Members"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Members"}),d.map(y=>e.jsx(lt,{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:n?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(dr,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(dr,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(dr,{className:"h-24 w-full rounded-lg"})]},y))}):m.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Dr,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:m.map(y=>{const _=y.icon&&_xe[y.icon]||Rh;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(Xe,{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:f(y.totalValue)})]}),e.jsx(ui,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:y.deals.map(b=>{const j=c.get(b.owner_user_id);return e.jsx(vVs,{deal:b,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:x},b.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 ",m.length," stage",m.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function vVs({deal:s,ownerColor:t,ownerName:r,ownerAvatar:n,formatPrice:a}){const i={buyer:{label:"Buyer",className:"bg-blue-500/10 text-blue-600 border-blue-200"},seller:{label:"Seller",className:"bg-emerald-500/10 text-emerald-600 border-emerald-200"},dual:{label:"Dual",className:"bg-purple-500/10 text-purple-600 border-purple-200"},referral:{label:"Referral",className:"bg-orange-500/10 text-orange-600 border-orange-200"},lease:{label:"Lease",className:"bg-cyan-500/10 text-cyan-600 border-cyan-200"}},l=s.deal_type?i[s.deal_type]:null;return e.jsxs("div",{className:"rounded-lg border bg-card p-3 space-y-2 transition-all hover:shadow-sm",style:{borderLeftWidth:4,borderLeftColor:t},children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(Wn,{className:"h-4 w-4",children:[e.jsx(Xa,{src:n||""}),e.jsx(Kn,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:t},children:r.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium truncate",style:{color:t},children:r})]}),e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2",children:s.deal_name}),l&&e.jsx(Xe,{variant:"outline",className:zt("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(Pn,{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(Xl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function bVs({members:s,enabledMembers:t,onToggleMember:r,isOpen:n,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:zt("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",n?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(Dr,{className:"h-4 w-4 shrink-0 text-primary"}),n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-semibold flex-1 text-left",children:"Team"}),i>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:i}),e.jsx(jl,{className:"h-3 w-3 text-muted-foreground"})]}),!n&&i>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[9px] bg-primary text-primary-foreground rounded-full w-4 h-4 flex items-center justify-center",children:i})]})}),n?e.jsxs(ui,{className:"flex-1 p-2",children:[e.jsx("div",{className:"space-y-1",children:s.map(l=>{const o=t.has(l.id);return e.jsxs("button",{onClick:()=>r(l.id),className:zt("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(Wn,{className:"h-7 w-7",children:[e.jsx(Xa,{src:l.avatar_url||""}),e.jsx(Kn,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:l.color},children:l.name.charAt(0).toUpperCase()})]}),o&&e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background",style:{backgroundColor:l.color}})]}),e.jsx("span",{className:zt("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(Rr,{checked:o,onCheckedChange:()=>r(l.id),className:"scale-75",onClick:c=>c.stopPropagation()})]},l.id)})}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No team members"})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center pt-2 gap-2",children:[s.slice(0,5).map(l=>{const o=t.has(l.id);return e.jsx("button",{onClick:()=>r(l.id),className:"relative",title:l.name,children:e.jsxs(Wn,{className:zt("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(Xa,{src:l.avatar_url||""}),e.jsx(Kn,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:l.color},children:l.name.charAt(0).toUpperCase()})]})},l.id)}),s.length>5&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",s.length-5]})]})]})}const EKe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function _Vs(){const s=xa(),{data:t}=uv(),r=(t==null?void 0:t.role)==="team_leader",n=t==null?void 0:t.teamId,a=pt({queryKey:["team-pipeline-members",n,s],queryFn:async()=>{const{data:i,error:l}=await U.from("team_members").select("user_id, role").eq("team_id",n).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(u=>u.user_id),{data:c,error:d}=await U.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((u,m)=>({id:u.id,name:u.name||"Unknown",avatar_url:u.avatar_url,color:EKe[m%EKe.length]}))},enabled:!!n&&!!s&&r,staleTime:5*60*1e3});return{isTeamLeader:r,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function wVs(s){return pt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:r}=await U.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(r)throw r;return(t||[]).map(n=>{var a;return{...n,_stage_name:((a=n.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function jVs(){const s=xa();return pt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:r}=await U.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(r)throw r;const n=t||[],a={},i=new Set;n.forEach(o=>{a[o.deal_id]||(a[o.deal_id]=[]),a[o.deal_id].push(o.tag),i.add(o.tag)});const l=Array.from(i).sort((o,c)=>o.localeCompare(c));return{tags:n,byDeal:a,unique:l}},enabled:!!s})}function L1t({stages:s,currentStageId:t,onStageSelect:r,disabled:n}){const[a,i]=k.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&r(c.id,c.name),i(!1)};return e.jsxs(Gd,{open:a,onOpenChange:i,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:n,onClick:c=>c.stopPropagation(),children:[l&&e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l.color}}),e.jsx("span",{className:"max-w-[80px] truncate",children:(l==null?void 0:l.name)||"Move"}),e.jsx(Ia,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Sd,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&_xe[c.icon]||Rh,u=c.id===t;return e.jsxs(ti,{onClick:()=>o(c),className:zt("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(la,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const NVs={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"}},kVs={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 D1t({deal:s,onClick:t,isDragging:r,stages:n,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var N,C;const c=rD(),d=NVs[s.deal_type],u=kVs[s.priority],m=k.useMemo(()=>s.target_close_date?lv(El(s.target_close_date),new Date):null,[s.target_close_date]),f=m!==null&&m<0,x=m!==null&&m<=7&&m>=0,y=k.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const A=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!A)return null;const E=s.contract_date?El(s.contract_date):new Date;return lv(E,El(A))},[s]),_=l&&!s.scorecard_transaction_id,b=!!s.scorecard_transaction_id,j=A=>A?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(A):null;return e.jsx(ke,{className:zt("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",r&&"opacity-50 rotate-2 shadow-xl",f&&"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(Pe,{className:"p-3 space-y-2.5",children:[o&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(Wn,{className:"h-4 w-4",children:[e.jsx(Xa,{src:o.avatar_url||""}),e.jsx(Kn,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:o.color},children:o.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium",style:{color:o.color},children:o.name})]}),e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2 group-hover:text-primary transition-colors",children:s.deal_name})}),e.jsx(Xe,{variant:"outline",className:zt("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(Wn,{className:"h-5 w-5",children:e.jsxs(Kn,{className:"text-[10px] bg-primary/10 text-primary",children:[(N=s.contact.first_name)==null?void 0:N[0],(C=s.contact.last_name)==null?void 0:C[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(Ul,{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(wo,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),b&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(qn,{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(Xy,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:zt("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(Pn,{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(Xl,{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=Vy(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:zt("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",u.color),children:[e.jsx("div",{className:zt("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&&n&&a?e.jsx(L1t,{stages:n,currentStageId:s.stage_id||"",onStageSelect:(A,E)=>a(s.id,A,E)}):s.target_close_date?e.jsxs("div",{className:zt("flex items-center gap-1 text-[10px]",f&&"text-red-600",x&&!f&&"text-amber-600",!f&&!x&&"text-muted-foreground"),children:[f?e.jsx(go,{className:"h-3 w-3"}):e.jsx(vn,{className:"h-3 w-3"}),e.jsx("span",{children:f?`${Math.abs(m)}d overdue`:x?`${m}d left`:As(El(s.target_close_date),"MMM d")})]}):null]})]})})}function SVs({stage:s,deals:t,onDealClick:r,onAddDeal:n,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const u=k.useRef(null),m=t.reduce((b,j)=>b+(j.expected_price||0),0),f=t.reduce((b,j)=>b+(j.expected_commission||0),0),x=t.reduce((b,j)=>b+(Vy(j)||0),0),y=b=>b>=1e6?`$${(b/1e6).toFixed(1)}M`:b>=1e3?`$${(b/1e3).toFixed(0)}K`:`$${b.toFixed(0)}`,_=s.icon&&_xe[s.icon]||Rh;return e.jsxs("div",{ref:u,className:zt("flex flex-col h-full min-w-[280px] max-w-[320px] bg-muted/30 rounded-xl border border-border/50 transition-all duration-200",o&&"border-primary/50 bg-primary/5 ring-2 ring-primary/20"),onDragOver:b=>i(b,s.id),onDrop:b=>l(b,s.id),children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center",style:{backgroundColor:`${s.color}20`},children:e.jsx(_,{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(Xe,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length})]}),m>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:y(m)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[y(f)," GCI"]}),x>0&&x!==f&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[y(x)," Net"]})]})]})]}),e.jsx(ui,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(b=>e.jsx("div",{draggable:!0,onDragStart:j=>{j.dataTransfer.effectAllowed="move",a(b.id,s.id)},children:e.jsx(D1t,{deal:b,onClick:()=>r(b),isWonStage:c,ownerInfo:(d==null?void 0:d(b))||null})},b.id)),t.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground text-sm",children:[e.jsx("p",{className:"mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-xs",children:"Drag deals here or add new"})]})]})}),e.jsx("div",{className:"p-2 border-t border-border/50 shrink-0",children:e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>n(s.id),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function CVs({stats:s,isLoading:t}){const r=a=>a>=1e6?`$${(a/1e6).toFixed(1)}M`:a>=1e3?`$${(a/1e3).toFixed(0)}K`:`$${a.toLocaleString()}`,n=[{label:"Active Deals",value:(s==null?void 0:s.activeDeals)||0,icon:Hu,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:r((s==null?void 0:s.weightedGCI)||0),icon:HF,color:"text-indigo-500",bgColor:"bg-indigo-500/10",tooltip:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:r((s==null?void 0:s.weightedNet)||0),icon:uP,color:"text-teal-500",bgColor:"bg-teal-500/10",tooltip:"Net to Agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:r((s==null?void 0:s.ytdWonNet)||0),icon:xF,color:"text-green-500",bgColor:"bg-green-500/10",subtitle:`${(s==null?void 0:s.ytdWonDeals)||0} deals`,tooltip:"Net commission from deals closed this year"},{label:"Projected Annual",value:r((s==null?void 0:s.projectedAnnualNet)||0),icon:Wo,color:"text-amber-500",bgColor:"bg-amber-500/10",tooltip:"YTD Closed Net + Weighted Active Net"}];return t?e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[1,2,3,4,5].map(a=>e.jsx(ke,{className:"animate-pulse",children:e.jsx(Pe,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(J_,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:n.map(a=>{const i=e.jsx(ke,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:zt("p-2 rounded-lg",a.bgColor),children:e.jsx(a.icon,{className:zt("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(Oc,{children:[e.jsx(Fc,{asChild:!0,children:i}),e.jsx(Sc,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function TVs({formData:s,onChange:t,isEditing:r}){const{isAdmin:n}=Cs(),[a,i]=k.useState(s.portal_enabled);if(!n)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Xe,{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(E0,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(A0,{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(Ir,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(Xe,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(Co,{className:zt("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(M0,{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(ce,{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(Rr,{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(ce,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(u_,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:zt("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(Du,{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:zt("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(Du,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Public"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Shareable link"})]})]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/30",children:[e.jsx(Ri,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(ce,{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(Ri,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(ce,{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(ce,{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(ce,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(Ne,{value:s.client_name,onChange:o=>l({client_name:o.target.value}),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(Ne,{type:"email",value:s.client_email,onChange:o=>l({client_email:o.target.value}),placeholder:"jane@example.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(Ne,{type:"tel",value:s.client_phone,onChange:o=>l({client_phone:o.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(Ds,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"email",children:"Email"}),e.jsxs(lt,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const EVs=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],AVs=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function MVs({open:s,onOpenChange:t,deal:r,defaultStageId:n}){const{data:a}=Gye(),{data:i}=Lp(),{data:l}=Oct(),o=Dge(),c=E1t(),d=A1t(),u=c6e(),[m,f]=k.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[x,y]=k.useState(""),[_,b]=k.useState(!1),[j,N]=k.useState(!1),[C,A]=k.useState({first_name:"",last_name:"",email:"",phone:""}),E=(l==null?void 0:l.filter(Q=>((r==null?void 0:r.listing_id)===Q.id,!0)))||[],[D,R]=k.useState({deal_name:"",deal_type:"buyer",stage_id:"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});k.useEffect(()=>{var Q,W,te,ne,ae,ue,me,de;s&&(r?(R({deal_name:r.deal_name,deal_type:r.deal_type,stage_id:r.stage_id||"",contact_id:r.contact_id||"",listing_id:r.listing_id||"",property_address:r.property_address||"",city:r.city||"",state:r.state||"",zip_code:r.zip_code||"",expected_price:((Q=r.expected_price)==null?void 0:Q.toString())||"",commission_percentage:((W=r.commission_percentage)==null?void 0:W.toString())||"3",brokerage_split_pct:((te=r.brokerage_split_pct)==null?void 0:te.toString())||"",team_split_pct:((ne=r.team_split_pct)==null?void 0:ne.toString())||"",referral_fee_pct:((ae=r.referral_fee_pct)==null?void 0:ae.toString())||"",franchise_fee_pct:((ue=r.franchise_fee_pct)==null?void 0:ue.toString())||"",transaction_fee:((me=r.transaction_fee)==null?void 0:me.toString())||"",commission_calc_method:r.commission_calc_method||"standard",target_close_date:r.target_close_date?El(r.target_close_date):void 0,contract_date:r.contract_date?El(r.contract_date):void 0,listing_date:r.listing_date?El(r.listing_date):void 0,priority:r.priority,probability:r.probability.toString(),notes:r.notes||""}),r.contact&&y(`${r.contact.first_name} ${r.contact.last_name}`)):(R({deal_name:"",deal_type:"buyer",stage_id:n||((de=a==null?void 0:a[0])==null?void 0:de.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(""),f({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,r,n,a]);const F=i==null?void 0:i.filter(Q=>{var je,xe,Ee,Me,Oe;const W=x.toLowerCase().trim();if(!W)return!0;const te=((je=Q.first_name)==null?void 0:je.toLowerCase())||"",ne=((xe=Q.last_name)==null?void 0:xe.toLowerCase())||"",ae=((Ee=Q.email)==null?void 0:Ee.toLowerCase())||"",ue=((Oe=(Me=Q.phone)==null?void 0:Me.toLowerCase)==null?void 0:Oe.call(Me))||"",me=`${te} ${ne}`.trim(),de=`${ne} ${te}`.trim();if(me.includes(W)||de.includes(W)||te.includes(W)||ne.includes(W)||ae.includes(W)||ue.includes(W))return!0;const fe=W.split(/\s+/).filter(Boolean);return fe.length>1?fe.every(Ie=>te.includes(Ie)||ne.includes(Ie)||ae.includes(Ie)||ue.includes(Ie)):!1}).slice(0,8),O=()=>{const Q=parseFloat(D.expected_price)||0,W=parseFloat(D.commission_percentage)||0;return Q*(W/100)},B=()=>{const Q=O();if(!Q)return null;const W=parseFloat(D.brokerage_split_pct)||0,te=parseFloat(D.team_split_pct)||0,ne=parseFloat(D.referral_fee_pct)||0,ae=parseFloat(D.franchise_fee_pct)||0,ue=parseFloat(D.transaction_fee)||0;if(D.commission_calc_method==="referral_first"){let de=Q;ne&&(de-=Q*ne/100);let fe=de;return W&&(fe-=de*W/100),te&&(fe-=Q*te/100),ae&&(fe-=Q*ae/100),ue&&(fe-=ue),Math.max(0,fe)}let me=Q;return W&&(me=me*((100-W)/100)),te&&(me=me*((100-te)/100)),ne&&(me=me-Q*ne/100),ae&&(me=me-Q*ae/100),ue&&(me=me-ue),Math.max(0,me)},K=async Q=>{var W,te,ne;if(Q.preventDefault(),!D.deal_name.trim()){he.error("Please enter a deal name");return}try{const ae={deal_name:D.deal_name,deal_type:D.deal_type,stage_id:D.stage_id||null,contact_id:D.contact_id||null,listing_id:D.listing_id||null,property_address:D.property_address||null,city:D.city||null,state:D.state||null,zip_code:D.zip_code||null,expected_price:D.expected_price?parseFloat(D.expected_price):null,expected_commission:O()||null,commission_percentage:D.commission_percentage?parseFloat(D.commission_percentage):3,brokerage_split_pct:D.brokerage_split_pct?parseFloat(D.brokerage_split_pct):null,team_split_pct:D.team_split_pct?parseFloat(D.team_split_pct):null,referral_fee_pct:D.referral_fee_pct?parseFloat(D.referral_fee_pct):null,franchise_fee_pct:D.franchise_fee_pct?parseFloat(D.franchise_fee_pct):null,transaction_fee:D.transaction_fee?parseFloat(D.transaction_fee):null,commission_calc_method:D.commission_calc_method,target_close_date:((W=D.target_close_date)==null?void 0:W.toISOString().split("T")[0])||null,contract_date:((te=D.contract_date)==null?void 0:te.toISOString().split("T")[0])||null,listing_date:((ne=D.listing_date)==null?void 0:ne.toISOString().split("T")[0])||null,priority:D.priority,probability:parseInt(D.probability)||50,notes:D.notes||null};if(r)await d.mutateAsync({id:r.id,...ae}),he.success("Deal updated successfully");else{const ue=await c.mutateAsync(ae);if(he.success("Deal created successfully"),m.portal_enabled&&(ue!=null&&ue.id))try{await u.mutateAsync({deal_id:ue.id,visibility:m.visibility,require_onboarding:m.require_onboarding,allow_spouse:m.allow_spouse,client_name:m.client_name||null,client_email:m.client_email||null,client_phone:m.client_phone||null,invite_method:m.invite_method}),he.success("Client portal created!")}catch{he.error("Deal created, but portal setup failed")}}t(!1)}catch{he.error("Failed to save deal")}},Z=c.isPending||d.isPending;return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:r?"Edit Deal":"Add New Deal"}),e.jsx(an,{children:r?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:K,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(ce,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(Ne,{id:"deal_name",value:D.deal_name,onChange:Q=>R(W=>({...W,deal_name:Q.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Deal Type"}),e.jsxs(Ds,{value:D.deal_type,onValueChange:Q=>R(W=>({...W,deal_type:Q})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:EVs.map(Q=>e.jsx(lt,{value:Q.value,children:Q.label},Q.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Stage"}),e.jsxs(Ds,{value:D.stage_id||"none",onValueChange:Q=>R(W=>({...W,stage_id:Q==="none"?"":Q})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select stage"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No Stage"}),a==null?void 0:a.map(Q=>e.jsx(lt,{value:Q.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:Q.color}}),Q.name]})},Q.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:x,onChange:Q=>{y(Q.target.value),b(!0),N(!1),Q.target.value||R(W=>({...W,contact_id:""}))},onFocus:()=>b(!0),placeholder:"Search contacts...",className:"pl-9"}),_&&x&&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:[F&&F.length>0?F.map(Q=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{R(W=>({...W,contact_id:Q.id})),y(`${Q.first_name} ${Q.last_name}`),b(!1)},children:[e.jsx(qi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[Q.first_name," ",Q.last_name]}),Q.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:Q.email})]},Q.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 Q=x.trim().split(/\s+/);A({first_name:Q[0]||"",last_name:Q.slice(1).join(" ")||"",email:"",phone:""}),N(!0),b(!1)},children:[e.jsx(xl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',x.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(xl,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(q,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>N(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ne,{placeholder:"First name *",value:C.first_name,onChange:Q=>A(W=>({...W,first_name:Q.target.value})),className:"h-8 text-sm"}),e.jsx(Ne,{placeholder:"Last name",value:C.last_name,onChange:Q=>A(W=>({...W,last_name:Q.target.value})),className:"h-8 text-sm"}),e.jsx(Ne,{placeholder:"Email",type:"email",value:C.email,onChange:Q=>A(W=>({...W,email:Q.target.value})),className:"h-8 text-sm"}),e.jsx(Ne,{placeholder:"Phone",type:"tel",value:C.phone,onChange:Q=>A(W=>({...W,phone:Q.target.value})),className:"h-8 text-sm"})]}),e.jsx(q,{type:"button",size:"sm",className:"w-full h-8",disabled:!C.first_name.trim()||o.isPending,onClick:async()=>{try{const Q=await o.mutateAsync({first_name:C.first_name.trim(),last_name:C.last_name.trim()||null,email:C.email.trim()||null,phone:C.phone.trim()||null});Q&&(R(W=>({...W,contact_id:Q.id})),y(`${Q.first_name} ${Q.last_name||""}`.trim()),N(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(xl,{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(ce,{className:"flex items-center gap-2",children:[e.jsx(Ul,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(Ds,{value:D.listing_id||"none",onValueChange:Q=>{const W=Q==="none"?"":Q,te=E.find(ne=>ne.id===W);R(te?ne=>{var ae;return{...ne,listing_id:W,deal_type:"seller",property_address:te.property_address||ne.property_address,city:te.city||ne.city,state:te.state||ne.state,expected_price:((ae=te.price)==null?void 0:ae.toString())||ne.expected_price}}:ne=>({...ne,listing_id:W}))},children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a listing to sync status..."})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"None"}),E.map(Q=>e.jsx(lt,{value:Q.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:Q.property_address||`${Q.city}, ${Q.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(Q.price/1e3).toFixed(0),"K"]})]})},Q.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(ce,{htmlFor:"property_address",children:"Address"}),e.jsx(Ne,{id:"property_address",value:D.property_address,onChange:Q=>R(W=>({...W,property_address:Q.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:D.city,onChange:Q=>R(W=>({...W,city:Q.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:D.state,onChange:Q=>R(W=>({...W,state:Q.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(Ne,{id:"zip_code",value:D.zip_code,onChange:Q=>R(W=>({...W,zip_code:Q.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(ce,{htmlFor:"expected_price",children:"Expected Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(Ne,{id:"expected_price",type:"number",value:D.expected_price,onChange:Q=>R(W=>({...W,expected_price:Q.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:Q=>R(W=>({...W,commission_percentage:Q.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(ce,{children:"Expected GCI"}),e.jsx(Ne,{value:O()?`$${O().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(ce,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(Ds,{value:D.commission_calc_method,onValueChange:Q=>R(W=>({...W,commission_calc_method:Q})),children:[e.jsx(Ps,{className:"h-7 text-xs",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(lt,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),D.commission_calc_method==="referral_first"&&e.jsx("p",{className:"text-[10px] text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-2 rounded",children:"💡 Referral fee is deducted from GCI first, then the brokerage split is applied to the remaining amount."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:Q=>R(W=>({...W,brokerage_split_pct:Q.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(ce,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:Q=>R(W=>({...W,team_split_pct:Q.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(ce,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:Q=>R(W=>({...W,referral_fee_pct:Q.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(ce,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:Q=>R(W=>({...W,franchise_fee_pct:Q.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(ce,{className:"text-xs",children:"Transaction Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(Ne,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:Q=>R(W=>({...W,transaction_fee:Q.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(ce,{className:"text-xs",children:"Net to Agent"}),e.jsx(Ne,{value:B()?`$${Math.round(B()).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(ce,{children:"Target Close Date"}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("w-full justify-start text-left font-normal",!D.target_close_date&&"text-muted-foreground"),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),D.target_close_date?As(D.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:D.target_close_date,onSelect:Q=>R(W=>({...W,target_close_date:Q})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Contract Date"}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("w-full justify-start text-left font-normal",!D.contract_date&&"text-muted-foreground"),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),D.contract_date?As(D.contract_date,"PPP"):"Pick a date"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:D.contract_date,onSelect:Q=>R(W=>({...W,contract_date:Q})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(D.deal_type==="seller"||D.deal_type==="dual")&&!D.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(ce,{children:"Listing Date (for Days on Market)"}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("w-full justify-start text-left font-normal",!D.listing_date&&"text-muted-foreground"),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),D.listing_date?As(D.listing_date,"PPP"):"Pick a date"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:D.listing_date,onSelect:Q=>R(W=>({...W,listing_date:Q})),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(ce,{children:"Priority"}),e.jsxs(Ds,{value:D.priority,onValueChange:Q=>R(W=>({...W,priority:Q})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:AVs.map(Q=>e.jsx(lt,{value:Q.value,children:Q.label},Q.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",min:"0",max:"100",value:D.probability,onChange:Q=>R(W=>({...W,probability:Q.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(ce,{htmlFor:"notes",children:"Notes"}),e.jsx(pr,{id:"notes",value:D.notes,onChange:Q=>R(W=>({...W,notes:Q.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!r&&e.jsx(TVs,{formData:m,onChange:f}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{type:"submit",disabled:Z,children:[Z&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Update Deal":"Create Deal"]})]})]})]})})}function IVs({dealId:s}){const t=xa(),r=is(),[n,a]=k.useState(""),[i,l]=k.useState(!1),{data:o=[]}=pt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:y,error:_}=await U.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(_)throw _;return y},enabled:!!s}),{data:c=[]}=pt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:y,error:_}=await U.from("deal_tags").select("tag").eq("owner_user_id",t);if(_)throw _;return[...new Set(y.map(j=>j.tag))].sort()},enabled:!!t}),d=Mt({mutationFn:async y=>{if(!t)throw new Error("Not authenticated");const{error:_}=await U.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:y.trim()});if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["deal-tags",s]}),r.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=Mt({mutationFn:async y=>{const{error:_}=await U.from("deal_tags").delete().eq("id",y);if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["deal-tags",s]})}}),m=()=>{const y=n.trim();y&&(o.some(_=>_.tag.toLowerCase()===y.toLowerCase())||d.mutate(y))},f=o.map(y=>y.tag.toLowerCase()),x=c.filter(y=>y.toLowerCase().includes(n.toLowerCase())&&!f.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(Xe,{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($r,{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(Ys,{className:"h-3 w-3"})," Add tag"]})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(Ne,{value:n,onChange:y=>a(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),m()),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:m,disabled:!n.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),n&&x.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:x.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 PVs(s){return pt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:r}=await U.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function LVs(){const s=xa(),t=is();return Mt({mutationFn:async({dealId:r,file:n})=>{if(!s)throw new Error("Not authenticated");const a=n.name.split(".").pop(),i=`${s}/${r}/${crypto.randomUUID()}.${a}`,{error:l}=await U.storage.from("deal-files").upload(i,n);if(l)throw l;const{data:o,error:c}=await U.from("deal_files").insert({deal_id:r,owner_user_id:s,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["deal-files",n.dealId]})}})}function DVs(){const s=is();return Mt({mutationFn:async({fileId:t,storagePath:r,dealId:n})=>{await U.storage.from("deal-files").remove([r]);const{error:a}=await U.from("deal_files").delete().eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function RVs(){const s=is();return Mt({mutationFn:async({fileId:t,visible:r,dealId:n})=>{const{error:a}=await U.from("deal_files").update({visible_on_portal:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function OVs(s){const{data:t,error:r}=await U.storage.from("deal-files").createSignedUrl(s,3600);if(r)throw r;return t.signedUrl}const AKe={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function R1t({open:s,onOpenChange:t}){const{data:r,isLoading:n}=cBs(),a=dBs(),i=uBs(),l=hBs(),[o,c]=k.useState(!1),[d,u]=k.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[m,f]=k.useState(""),x=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((r==null?void 0:r.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),f(""),c(!1),he.success("Question added")}catch{he.error("Failed to add question")}},y=async N=>{try{await l.mutateAsync(N),he.success("Question removed")}catch{he.error("Failed to remove question")}},_=async(N,C)=>{try{await i.mutateAsync({id:N,is_required:C})}catch{he.error("Failed to update question")}},b=()=>{m.trim()&&(u(N=>({...N,options:[...N.options,m.trim()]})),f(""))},j=N=>{u(C=>({...C,options:C.options.filter((A,E)=>E!==N)}))};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(_s,{children:[e.jsx(bs,{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(ui,{className:"flex-1",children:e.jsxs("div",{className:"space-y-3 pr-2",children:[n&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),r==null?void 0:r.map(N=>{var C;return e.jsx("div",{className:"border rounded-lg p-3 space-y-2",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Vu,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:N.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"secondary",className:"text-xs",children:AKe[N.field_type]||N.field_type}),N.is_required&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Required"})]}),N.field_type==="dropdown"&&((C=N.options)==null?void 0:C.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",N.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(Rr,{checked:N.is_required,onCheckedChange:A=>_(N.id,A),className:"scale-75"}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>y(N.id),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})},N.id)}),!n&&(r==null?void 0:r.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Question"}),e.jsx(Ne,{value:d.question_text,onChange:N=>u(C=>({...C,question_text:N.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(AKe).map(([N,C])=>e.jsx("button",{type:"button",onClick:()=>u(A=>({...A,field_type:N,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===N?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:C},N))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((N,C)=>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:N}),e.jsx("button",{onClick:()=>j(C),className:"text-muted-foreground hover:text-destructive",children:e.jsx($r,{className:"h-3.5 w-3.5"})})]},C)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:m,onChange:N=>f(N.target.value),onKeyDown:N=>N.key==="Enter"&&(N.preventDefault(),b()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(q,{variant:"outline",size:"sm",onClick:b,disabled:!m.trim(),className:"h-8",children:e.jsx(Ys,{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(Rr,{checked:d.is_required,onCheckedChange:N=>u(C=>({...C,is_required:N}))}),e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(q,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(q,{size:"sm",onClick:x,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(ls,{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(q,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function FVs({override:s,onChange:t}){const r=xa(),{data:n}=glt(),[a,i]=k.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(r){if(d.size>5*1024*1024){he.error("Image must be under 5MB");return}i(u);try{const m=await ylt(r,d,`${u}`);l(u==="logo"?{logo_url:m}:{cover_photo_url:m})}catch(m){he.error(`Upload failed: ${m.message||m}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(Ir,{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(MKe,{label:"Logo",value:s.logo_url??null,globalValue:(n==null?void 0:n.logo_url)??null,uploading:a==="logo",onUpload:d=>o(d,"logo"),onClear:()=>l({logo_url:null}),aspect:"square"}),e.jsx(MKe,{label:"Cover Photo",value:s.cover_photo_url??null,globalValue:(n==null?void 0:n.cover_photo_url)??null,uploading:a==="cover",onUpload:d=>o(d,"cover"),onClear:()=>l({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(IKe,{label:"Brand Color",value:s.brand_color??null,globalValue:(n==null?void 0:n.brand_color)??null,onChange:d=>l({brand_color:d})}),e.jsx(IKe,{label:"Accent Color",value:s.accent_color??null,globalValue:(n==null?void 0:n.accent_color)??null,onChange:d=>l({accent_color:d})})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(Ne,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(n==null?void 0:n.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(zr,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function MKe({label:s,value:t,globalValue:r,uploading:n,onUpload:a,onClear:i,aspect:l}){const o=t||r,c=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ce,{className:"text-sm font-medium",children:s}),c?e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"}):r?e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Using global"}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:zt("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(zo,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:d=>{var m;const u=(m=d.target.files)==null?void 0:m[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:[n?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ka,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(q,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})]})}function IKe({label:s,value:t,globalValue:r,onChange:n}){const a=t||r||"#000000",i=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{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:zt("mt-1 flex items-center gap-2 h-9 rounded-md border bg-background px-2",i?"border-primary":"border-input"),children:[e.jsx("input",{type:"color",value:a,onChange:l=>n(l.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(Ne,{value:t||"",onChange:l=>n(l.target.value||null),placeholder:r||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>n(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(zr,{className:"h-3 w-3"})})]})]})}function zVs({portalId:s,agentUserId:t}){const r=is(),{data:n,isLoading:a}=pt({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:m}=await U.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),f=m==null?void 0:m.brokerage_id,x=U.from("vendors").select("*").eq("is_active",!0),y=f?x.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${f})`):x.eq("owner_type","agent").eq("owner_user_id",t),[{data:_,error:b},{data:j},{data:N}]=await Promise.all([y.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),U.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),U.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(b)throw b;const C=new Map;(j||[]).forEach(E=>C.set(E.vendor_id,E.is_visible));const A=new Map;return(N||[]).forEach(E=>A.set(E.vendor_id,E.is_visible)),{vendors:_||[],selMap:C,overrideMap:A}}}),i=Mt({mutationFn:async({vendorId:m,isVisible:f})=>{const{data:x}=await U.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",m).maybeSingle();if(x){const{error:y}=await U.from("portal_vendor_overrides").update({is_visible:f}).eq("id",x.id);if(y)throw y}else{const{error:y}=await U.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:m,is_visible:f});if(y)throw y}},onSuccess:()=>{r.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),r.invalidateQueries({queryKey:["portal-vendors",s]})},onError:m=>he.error(m.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"w-5 h-5 animate-spin text-muted-foreground"})});const l=(n==null?void 0:n.vendors)||[],o=(n==null?void 0:n.selMap)||new Map,c=(n==null?void 0:n.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(j_,{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=m=>{const f=c.get(m.id);if(f!==void 0)return f;if(m.is_required)return!0;const x=o.get(m.id);return x===void 0?!0:x!==!1},u=m=>{var f;return((f=A8.find(x=>x.value===m))==null?void 0:f.label)||m};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(ui,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(m=>{const f=d(m);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:m.logo_url?e.jsx("img",{src:m.logo_url,alt:m.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:m.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:m.company||m.name}),e.jsx(Xe,{variant:"outline",className:"text-[10px] shrink-0",children:u(m.category)}),m.owner_type==="brokerage"&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),m.is_required&&e.jsx(Xe,{className:"text-[10px] shrink-0",children:"Required"})]}),m.company&&m.name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:m.name})]}),e.jsx(Rr,{checked:f,disabled:m.is_required||i.isPending,onCheckedChange:x=>i.mutate({vendorId:m.id,isVisible:x})})]},m.id)})})})]})}function BVs({portalId:s,ownerId:t,clientEmail:r,linkedPortalId:n,onLink:a}){const[i,l]=k.useState(""),[o,c]=k.useState(!1),{data:d,isLoading:u}=pt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:y,error:_}=await U.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(_)throw _;return y},enabled:o||!!n}),m=k.useMemo(()=>!n||!d?null:d.find(y=>y.id===n),[n,d]),f=k.useMemo(()=>!d||!r?[]:d.filter(y=>{var _;return((_=y.client_email)==null?void 0:_.toLowerCase())===r.toLowerCase()&&y.id!==s}),[d,r,s]),x=k.useMemo(()=>{if(!d||!i.trim())return[];const y=i.toLowerCase();return d.filter(_=>{var j,N,C,A;const b=_.deal_pipeline;return((j=_.client_name)==null?void 0:j.toLowerCase().includes(y))||((N=_.client_email)==null?void 0:N.toLowerCase().includes(y))||((C=b==null?void 0:b.deal_name)==null?void 0:C.toLowerCase().includes(y))||((A=b==null?void 0:b.property_address)==null?void 0:A.toLowerCase().includes(y))})},[d,i]);if(n){const y=m==null?void 0:m.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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(Ul,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:(m==null?void 0:m.client_name)||(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(q,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(WE,{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(ce,{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(q,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(Ul,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&f.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)"}),f.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(Xe,{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(Ul,{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(_n,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{value:i,onChange: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(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),x.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:x.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(Xe,{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&&x.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function dIe({contactId:s,onVideoReady:t}){const[r,n]=k.useState(!1),[a,i]=k.useState("record"),[l,o]=k.useState(0),[c,d]=k.useState(0),u=V2(),m=()=>{i("record"),o(0),d(0)},f=y=>{!y&&(a==="uploading"||a==="processing")||(n(y),y||m())},x=k.useCallback(async(y,_)=>{i("uploading");try{const b="Card Video",{videoId:j,libraryId:N}=await dM(b),{uploadUrl:C,apiKey:A}=await uM(j),E=new XMLHttpRequest;E.upload.onprogress=Z=>{Z.lengthComputable&&o(Z.loaded/Z.total*100)},await new Promise((Z,Q)=>{E.onload=()=>E.status>=200&&E.status<300?Z():Q(new Error("Upload failed")),E.onerror=()=>Q(new Error("Upload failed")),E.open("PUT",C),E.setRequestHeader("AccessKey",A),E.send(y)}),i("processing");let D=0;const R=Date.now(),F=9e4,O=`https://iframe.mediadelivery.net/embed/${N}/${j}`;for(;D<4;){if(await new Promise(Q=>setTimeout(Q,3e3)),Date.now()-R>F){const Q=y.size/1048576;await u.mutateAsync({bunny_video_id:j,playback_url:`https://iframe.mediadelivery.net/play/${N}/${j}`,file_size_mb:Q,title:b,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(O),he.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{n(!1),m()},1500);return}const Z=await W_(j);if(D=Z.status,d(Z.encodeProgress||0),D===5||D===6)throw new Error("Video processing failed")}const B=await W_(j),K=(B.storageSize||y.size)/(1024*1024);await u.mutateAsync({bunny_video_id:j,contact_id:s||void 0,playback_url:B.directPlayUrl||O,thumbnail_url:B.thumbnailUrl,preview_url:B.previewUrl||null,duration_seconds:B.length||_,file_size_mb:K,title:b,status:"ready",touch_type:"video"}),t(O),he.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{n(!1),m()},1500)}catch(b){console.error("Recording upload error:",b),he.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(vs,{open:r,onOpenChange:f,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(ys,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(pM,{maxDurationSeconds:600,onRecordingComplete:x,onError:y=>he.error(y)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(ls,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ki,{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(ls,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ki,{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(Ti,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const $Vs=s=>`portal-settings-draft:${s}`;function uIe({open:s,onOpenChange:t,portal:r,dealOwnerId:n}){const a=nD(),[i,l]=k.useState(!1),o=k.useMemo(()=>$Vs(r.id),[r.id]),[c,d]=k.useState(!1),[u,m]=k.useState(r.next_step_text||""),[f,x]=k.useState(r.next_step_video_url||""),[y,_]=k.useState(r.inspection_date||""),[b,j]=k.useState(r.appraisal_date||""),[N,C]=k.useState(r.welcome_message||""),[A,E]=k.useState(r.review_url||""),[D,R]=k.useState(r.show_post_close_tips),[F,O]=k.useState(r.notify_client),[B,K]=k.useState(r.require_onboarding),[Z,Q]=k.useState(r.allow_spouse),[W,te]=k.useState(r.visibility),[ne,ae]=k.useState(r.stage_mapping||[]),[ue,me]=k.useState(null),[de,fe]=k.useState(r.linked_portal_id||null),[je,xe]=k.useState(r.referral_enabled??!0),[Ee,Me]=k.useState(r.referral_reward_text||""),[Oe,Ie]=k.useState(r.referral_cta_headline||""),[ze,Ve]=k.useState(r.homeowner_hub_video_url||""),[Le,$e]=k.useState(r.branding_override||{}),ve=()=>{m(r.next_step_text||""),x(r.next_step_video_url||""),_(r.inspection_date||""),j(r.appraisal_date||""),C(r.welcome_message||""),E(r.review_url||""),R(r.show_post_close_tips),O(r.notify_client),K(r.require_onboarding),Q(r.allow_spouse),te(r.visibility),ae(r.stage_mapping||[]),fe(r.linked_portal_id||null),xe(r.referral_enabled??!0),Me(r.referral_reward_text||""),Ie(r.referral_cta_headline||""),Ve(r.homeowner_hub_video_url||""),$e(r.branding_override||{})};k.useEffect(()=>{d(!1);const Ce=localStorage.getItem(o);if(Ce)try{const qe=JSON.parse(Ce);m(qe.nextStepText||""),x(qe.nextStepVideo||""),_(qe.inspectionDate||""),j(qe.appraisalDate||""),C(qe.welcomeMessage||""),E(qe.reviewUrl||""),R(!!qe.showPostClose),O(!!qe.notifyClient),K(!!qe.requireOnboarding),Q(!!qe.allowSpouse),te(qe.visibility||r.visibility),ae(qe.stageMapping||[]),fe(qe.linkedPortalId??null),xe(qe.referralEnabled??!0),Me(qe.referralRewardText||""),Ie(qe.referralCtaHeadline||""),Ve(qe.homeownerHubVideoUrl||""),$e(qe.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}ve(),d(!0)},[o,r]),k.useEffect(()=>{if(!c)return;const Ce={nextStepText:u,nextStepVideo:f,inspectionDate:y,appraisalDate:b,welcomeMessage:N,reviewUrl:A,showPostClose:D,notifyClient:F,requireOnboarding:B,allowSpouse:Z,visibility:W,stageMapping:ne,linkedPortalId:de,referralEnabled:je,referralRewardText:Ee,referralCtaHeadline:Oe,homeownerHubVideoUrl:ze,brandingOverride:Le};u!==(r.next_step_text||"")||f!==(r.next_step_video_url||"")||y!==(r.inspection_date||"")||b!==(r.appraisal_date||"")||N!==(r.welcome_message||"")||A!==(r.review_url||"")||D!==r.show_post_close_tips||F!==r.notify_client||B!==r.require_onboarding||Z!==r.allow_spouse||W!==r.visibility||JSON.stringify(ne)!==JSON.stringify(r.stage_mapping||[])||de!==(r.linked_portal_id||null)||je!==(r.referral_enabled??!0)||Ee!==(r.referral_reward_text||"")||Oe!==(r.referral_cta_headline||"")||ze!==(r.homeowner_hub_video_url||"")||JSON.stringify(Le)!==JSON.stringify(r.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ce)):localStorage.removeItem(o)},[u,f,y,b,N,A,D,F,B,Z,W,ne,de,je,Ee,Oe,ze,Le,o,c,r]);const Qe=()=>{localStorage.removeItem(o),ve()},we=async()=>{try{await a.mutateAsync({id:r.id,next_step_text:u||null,next_step_video_url:f||null,inspection_date:y||null,appraisal_date:b||null,welcome_message:N||null,review_url:A||null,show_post_close_tips:D,notify_client:F,require_onboarding:B,allow_spouse:Z,visibility:W,stage_mapping:ne.length>0?ne:null,linked_portal_id:de,referral_enabled:je,referral_reward_text:Ee||null,referral_cta_headline:Oe||null,homeowner_hub_video_url:ze||null,branding_override:Object.values(Le).some(qe=>qe!=null&&qe!=="")?Le:null});const Ce=r.linked_portal_id;de&&de!==Ce&&await U.from("client_portals").update({linked_portal_id:r.id}).eq("id",de),!de&&Ce&&await U.from("client_portals").update({linked_portal_id:null}).eq("id",Ce),localStorage.removeItem(o),he.success("Portal settings saved"),t(!1)}catch{he.error("Failed to save settings")}},nt=()=>{ae([...ne,{label:""}])},Se=Ce=>{ae(ne.filter((qe,et)=>et!==Ce)),ue===Ce&&me(null)},Ge=(Ce,qe,et)=>{const Ze=[...ne];Ze[Ce]={...Ze[Ce],[qe]:et},ae(Ze)},We=()=>{const qe=Nge(null).map(et=>({label:et.label,description:et.description,stageId:void 0}));ae(qe)};return e.jsxs(e.Fragment,{children:[e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Portal Settings"})}),e.jsxs(ta,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ea,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(rs,{value:"general",children:"General"}),e.jsx(rs,{value:"timeline",children:"Timeline"}),e.jsx(rs,{value:"content",children:"Content"}),e.jsx(rs,{value:"vendors",children:"Vendors"}),e.jsx(rs,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(fs,{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(ce,{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(Ce=>e.jsx("button",{onClick:()=>te(Ce),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${W===Ce?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ce.charAt(0).toUpperCase()+Ce.slice(1)},Ce))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{checked:B,onCheckedChange:K})]}),B&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(q,{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(ce,{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(Rr,{checked:Z,onCheckedChange:Q})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{checked:D,onCheckedChange:R})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{checked:F,onCheckedChange:O})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(BVs,{portalId:r.id,ownerId:n,clientEmail:r.client_email,linkedPortalId:de,onLink:fe})}),e.jsx("div",{children:e.jsx(Ne,{type:"date",value:y,onChange:Ce=>_(Ce.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(Ne,{type:"date",value:b,onChange:Ce=>j(Ce.target.value),className:"mt-1"})]})]}),e.jsx(fs,{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(ce,{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(q,{variant:"outline",size:"sm",onClick:We,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),ne.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx(q,{variant:"outline",size:"sm",onClick:We,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:ne.map((Ce,qe)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vu,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(Ne,{value:Ce.label,onChange:et=>Ge(qe,"label",et.target.value),placeholder:`Stage ${qe+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>me(ue===qe?null:qe),children:ue===qe?"Less":"More"}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Se(qe),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]}),ue===qe&&e.jsxs("div",{className:"ml-6 space-y-2 pl-2 border-l-2 border-primary/15 pb-2",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ce.description||"",onChange:et=>Ge(qe,"description",et.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(ce,{className:"text-xs text-muted-foreground",children:"Video"}),Ce.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:Ce.video_url.length>40?Ce.video_url.slice(0,40)+"...":Ce.video_url}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Ge(qe,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(dIe,{onVideoReady:et=>Ge(qe,"video_url",et)}),e.jsx(cM,{userId:n,onSelect:et=>Ge(qe,"video_url",et),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(q,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const et=prompt("Paste a YouTube or Loom URL:");et&&Ge(qe,"video_url",et)},children:[e.jsx(tl,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},qe))}),ne.length>0&&e.jsxs(q,{variant:"outline",size:"sm",onClick:nt,className:"mt-2 text-xs w-full",children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(fs,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:N,onChange:Ce=>C(Ce.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(ce,{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:Ce=>m(Ce.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(ce,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(Ne,{value:f,onChange:Ce=>x(Ce.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Review URL"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown after deal closes"}),e.jsx(Ne,{value:A,onChange:Ce=>E(Ce.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(ce,{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(ce,{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(Rr,{checked:je,onCheckedChange:xe})]}),je&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Headline"}),e.jsx(Ne,{value:Oe,onChange:Ce=>Ie(Ce.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Reward (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"What the client gets for a successful referral"}),e.jsx(Ne,{value:Ee,onChange:Ce=>Me(Ce.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Personal Welcome Video URL (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:'A "welcome home" video shown above the referral card'}),e.jsx(Ne,{value:ze,onChange:Ce=>Ve(Ce.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(fs,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(zVs,{portalId:r.id,agentUserId:n})}),e.jsx(fs,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(FVs,{override:Le,onChange:$e})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(q,{variant:"ghost",onClick:Qe,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(q,{onClick:we,disabled:a.isPending,children:[a.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(R1t,{open:i,onOpenChange:l})]})}const UVs=s=>`portal-update-draft:${s}`;function hIe({open:s,onOpenChange:t,portalId:r,portalSlug:n,notifyClient:a}){const i=k.useMemo(()=>UVs(r),[r]),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,m]=k.useState(""),[f,x]=k.useState(!1),[y,_]=k.useState(a??!1),[b,j]=k.useState(!1),N=oyt();k.useEffect(()=>{j(!1);const E=localStorage.getItem(i);if(E)try{const D=JSON.parse(E);o(D.title||""),d(D.content||""),m(D.videoUrl||""),x(!!D.isStageChange),_(typeof D.sendNotification=="boolean"?D.sendNotification:a??!1),j(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),m(""),x(!1),_(a??!1),j(!0)},[i,a]),k.useEffect(()=>{if(!b)return;const E={title:l,content:c,videoUrl:u,isStageChange:f,sendNotification:y};l.trim()||c.trim()||u.trim()||f||y!==(a??!1)?localStorage.setItem(i,JSON.stringify(E)):localStorage.removeItem(i)},[l,c,u,f,y,b,i,a]);const C=()=>{localStorage.removeItem(i),o(""),d(""),m(""),x(!1),_(a??!1)},A=async()=>{if(l.trim())try{if(await N.mutateAsync({portal_id:r,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:f}),y&&n)try{const E=R_(n);await U.functions.invoke("send-portal-notification",{body:{portal_id:r,update_title:l.trim(),update_content:c.trim()||null,portal_url:E}}),he.success("Update posted & client notified")}catch(E){console.error("Notification failed:",E),he.success("Update posted (notification failed to send)")}else he.success("Update posted to portal");C(),t(!1)}catch{he.error("Failed to post update")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Title *"}),e.jsx(Ne,{value:l,onChange:E=>o(E.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(ce,{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(ce,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Ne,{value:u,onChange:E=>m(E.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(bn,{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:()=>x(!f),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${f?"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(ym,{className:"h-3 w-3"}):e.jsx(b_,{className:"h-3 w-3"}),y?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(q,{variant:"ghost",onClick:C,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(q,{onClick:A,disabled:!l.trim()||N.isPending,children:[N.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function mIe({open:s,onOpenChange:t,portal:r,dealName:n}){const a=nD(),{isGmailConnected:i,gmailEmail:l}=Cm(),[o,c]=k.useState(r.client_name||""),[d,u]=k.useState(r.client_email||""),[m,f]=k.useState(!1),[x,y]=k.useState(!1),_=R_(r.slug),b=o.split(" ")[0]||"there",j=`Your Transaction Portal – ${n}`,N=`Hi ${b}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${_} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,C=()=>{navigator.clipboard.writeText(_),y(!0),setTimeout(()=>y(!1),2e3),he.success("Portal link copied!")},A=async()=>{if(!d.trim()){he.error("Please enter the client email");return}f(!0);try{await a.mutateAsync({id:r.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:D}=await U.functions.invoke("gmail-send",{body:{to:d,subject:j,body:N.replace(/\n/g,"
")}});if(D){let R="";try{const F=D==null?void 0:D.context;if(F&&typeof F.json=="function"){const O=await F.json();R=(O==null?void 0:O.message)||(O==null?void 0:O.error)||""}}catch{}throw new Error(R||D.message||"Failed to send invite")}he.success(`Invite sent to ${d}`),t(!1)}catch(D){he.error(D.message||"Failed to send invite")}finally{f(!1)}},E=()=>{const D=encodeURIComponent(j),R=encodeURIComponent(N);window.open(`mailto:${d}?subject=${D}&body=${R}`,"_blank"),a.mutateAsync({id:r.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(Ne,{value:o,onChange:D=>c(D.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(Ne,{type:"email",value:d,onChange:D=>u(D.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ce,{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(q,{variant:"outline",size:"icon",onClick:C,className:"shrink-0",children:x?e.jsx(la,{className:"h-4 w-4 text-emerald-600"}):e.jsx(si,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(q,{onClick:A,disabled:m||!d.trim(),className:"w-full",children:[m?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(q,{onClick:E,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(q,{variant:"ghost",onClick:C,className:"w-full text-muted-foreground",children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function qVs({deal:s}){const{isAdmin:t,user:r}=Cs(),{data:n,isLoading:a}=oBs(s.id),i=c6e(),l=nD(),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[m,f]=k.useState(!1),[x,y]=k.useState(!1),_=`portal-management-ui:${s.id}`;if(k.useEffect(()=>{const D=sessionStorage.getItem(_);if(D)try{const R=JSON.parse(D);u(!!R.settingsOpen),f(!!R.composerOpen),y(!!R.inviteOpen)}catch{sessionStorage.removeItem(_)}},[_]),k.useEffect(()=>{d||m||x?sessionStorage.setItem(_,JSON.stringify({settingsOpen:d,composerOpen:m,inviteOpen:x})):sessionStorage.removeItem(_)},[d,m,x,_]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(ls,{className:"h-3 w-3 animate-spin ml-auto"})]})});const b=async()=>{var D,R;c(!0);try{await i.mutateAsync({deal_id:s.id,visibility:"private",require_onboarding:!0,client_name:s.contact?`${s.contact.first_name} ${s.contact.last_name}`:void 0,client_email:((D=s.contact)==null?void 0:D.email)||void 0,client_phone:((R=s.contact)==null?void 0:R.phone)||void 0}),he.success("Client portal enabled!")}catch{he.error("Failed to create portal")}finally{c(!1)}},j=async D=>{if(n)try{await l.mutateAsync({id:n.id,is_enabled:D}),he.success(D?"Portal enabled":"Portal disabled")}catch{he.error("Failed to update portal")}},N=()=>{if(!n)return;const D=R_(n.slug);navigator.clipboard.writeText(D),he.success("Portal link copied!")},C=()=>{if(!n)return;const D=R_(n.slug);window.open(D,"_blank")};if(!n)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ir,{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(q,{onClick:b,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const A=R_(n.slug),E=(r==null?void 0:r.id)||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Xe,{variant:"outline",className:n.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:n.is_enabled?"Active":"Disabled"})]}),e.jsx(Rr,{checked:n.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(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:n.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:n.require_onboarding?"Required":"Disabled"})]}),n.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:n.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:A})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:N,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(si,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:C,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(un,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>y(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(hn,{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(q,{variant:"ghost",size:"sm",onClick:()=>f(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(c_,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(Bo,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(Vn,{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(Di,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(uIe,{open:d,onOpenChange:u,portal:n,dealOwnerId:E}),e.jsx(hIe,{open:m,onOpenChange:f,portalId:n.id,portalSlug:n.slug,notifyClient:n.notify_client}),e.jsx(mIe,{open:x,onOpenChange:y,portal:n,dealName:s.deal_name})]})}const VVs=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function HVs(s){return pt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:r}=await U.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(r)throw r;return t||[]},enabled:!!s})}function GVs(){const s=is();return Mt({mutationFn:async({dealId:t,contactId:r,role:n})=>{const{data:a,error:i}=await U.from("deal_contacts").insert({deal_id:t,contact_id:r,role:n}).select().single();if(i)throw i;return a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-contacts",r.dealId]}),he.success("Contact linked to deal")},onError:t=>{var r;(r=t.message)!=null&&r.includes("duplicate")?he.error("This contact is already linked to this deal"):he.error("Failed to link contact")}})}function WVs(){const s=is();return Mt({mutationFn:async({id:t,dealId:r})=>{const{error:n}=await U.from("deal_contacts").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-contacts",r.dealId]}),he.success("Contact removed from deal")},onError:()=>{he.error("Failed to remove contact")}})}function KVs({dealId:s,primaryContactId:t}){const r=qr(),{data:n,isLoading:a}=HVs(s),{data:i}=Lp(),l=GVs(),o=WVs(),[c,d]=k.useState(!1),[u,m]=k.useState(""),[f,x]=k.useState("Client"),y=new Set((n==null?void 0:n.map(C=>C.contact_id))||[]);t&&y.add(t);const _=i==null?void 0:i.filter(C=>{var E,D,R;if(y.has(C.id))return!1;if(!u.trim())return!0;const A=u.toLowerCase();return((E=C.first_name)==null?void 0:E.toLowerCase().includes(A))||((D=C.last_name)==null?void 0:D.toLowerCase().includes(A))||((R=C.email)==null?void 0:R.toLowerCase().includes(A))}).slice(0,8),b=C=>{l.mutate({dealId:s,contactId:C,role:f}),d(!1),m("")},j=C=>{o.mutate({id:C,dealId:s})},N={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(n!=null&&n.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(sl,{open:c,onOpenChange:d,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Ko,{className:"w-80 p-3",align:"start",children:e.jsx(PKe,{search:u,setSearch:m,selectedRole:f,setSelectedRole:x,filteredContacts:_,onAdd:b})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),"Linked Contacts",n&&n.length>0&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] px-1.5",children:n.length})]}),e.jsxs(sl,{open:c,onOpenChange:d,children:[e.jsx(rl,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(Ko,{className:"w-80 p-3",align:"end",children:e.jsx(PKe,{search:u,setSearch:m,selectedRole:f,setSelectedRole:x,filteredContacts:_,onAdd:b})})]})]}),e.jsx("div",{className:"space-y-1.5",children:n==null?void 0:n.map(C=>{var A,E,D,R,F,O,B,K;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Wn,{className:"h-7 w-7",children:e.jsxs(Kn,{className:"text-[10px] bg-primary/10 text-primary",children:[(E=(A=C.contact)==null?void 0:A.first_name)==null?void 0:E[0],(R=(D=C.contact)==null?void 0:D.last_name)==null?void 0:R[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>r(`/mission-control/contacts/${C.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(F=C.contact)==null?void 0:F.first_name," ",(O=C.contact)==null?void 0:O.last_name]})}),e.jsx(Xe,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${N[C.role]||N.Other}`,children:C.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((B=C.contact)==null?void 0:B.phone)&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${C.contact.phone}`,children:e.jsx(Mn,{className:"h-3 w-3"})})}),((K=C.contact)==null?void 0:K.email)&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${C.contact.email}`,children:e.jsx(Ks,{className:"h-3 w-3"})})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>j(C.id),children:e.jsx(zr,{className:"h-3 w-3"})})]})]},C.id)})})]})}function PKe({search:s,setSearch:t,selectedRole:r,setSelectedRole:n,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Ds,{value:r,onValueChange:n,children:[e.jsx(Ps,{className:"h-8 text-sm",children:e.jsx(Fs,{placeholder:"Role"})}),e.jsx(Ls,{children:VVs.map(l=>e.jsx(lt,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(ui,{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 YVs={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"}},ZVs={note:Ui,call:Mn,email:Ks,meeting:vn,stage_change:un,task_completed:qn,document:Pn,system:jn};function XVs({deal:s,open:t,onOpenChange:r,onEdit:n,onAddToScorecard:a,isWonStage:i}){var ze,Ve;const l=qr(),{data:o,isLoading:c}=Aqs((s==null?void 0:s.id)||""),{data:d,isLoading:u}=Iqs((s==null?void 0:s.id)||""),m=Mqs(),f=Lqs(),x=Pqs(),y=Eqs(),{data:_,isLoading:b}=PVs((s==null?void 0:s.id)||""),j=LVs(),N=DVs(),C=RVs(),A=k.useRef(null),[E,D]=k.useState(""),[R,F]=k.useState(""),[O,B]=k.useState(!1),[K,Z]=k.useState(!1);if(!s)return null;const Q=YVs[s.deal_type],W=(()=>{var ve;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Le=((ve=s.listing)==null?void 0:ve.created_at)||s.listing_date;if(!Le)return null;const $e=s.contract_date?El(s.contract_date):new Date;return lv($e,El(Le))})(),te=Le=>Le?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Le):"-",ne=async()=>{if(E.trim())try{await m.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:E}),D(""),he.success("Note added")}catch{he.error("Failed to add note")}},ae=async()=>{if(R.trim())try{await f.mutateAsync({deal_id:s.id,title:R,sort_order:((d==null?void 0:d.length)||0)+1}),F(""),he.success("Task added")}catch{he.error("Failed to add task")}},ue=async(Le,$e)=>{try{await x.mutateAsync({id:Le,is_completed:$e,deal_id:s.id})}catch{he.error("Failed to update task")}},me=async()=>{try{await y.mutateAsync(s.id),he.success("Deal deleted"),r(!1)}catch{he.error("Failed to delete deal")}},de=(d==null?void 0:d.filter(Le=>Le.is_completed).length)||0,fe=(d==null?void 0:d.length)||0,je=(_==null?void 0:_.length)||0,xe=Le=>Le<1024?`${Le} B`:Le<1024*1024?`${(Le/1024).toFixed(1)} KB`:`${(Le/(1024*1024)).toFixed(1)} MB`,Ee=Le=>Le?Le.startsWith("image/")?zo:Le.includes("pdf")?En:WI:WI,Me=async Le=>{const $e=Le.target.files;if(!(!$e||!s)){Z(!0);try{for(const ve of Array.from($e)){if(ve.size>20*1024*1024){he.error(`${ve.name} exceeds 20MB limit`);continue}await j.mutateAsync({dealId:s.id,file:ve})}he.success("File(s) uploaded")}catch{he.error("Failed to upload file")}finally{Z(!1),A.current&&(A.current.value="")}}},Oe=async(Le,$e)=>{if(s)try{await N.mutateAsync({fileId:Le,storagePath:$e,dealId:s.id}),he.success("File deleted")}catch{he.error("Failed to delete file")}},Ie=async(Le,$e)=>{try{const ve=await OVs(Le),Qe=document.createElement("a");Qe.href=ve,Qe.download=$e,Qe.target="_blank",document.body.appendChild(Qe),Qe.click(),document.body.removeChild(Qe)}catch{he.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(sw,{open:t,onOpenChange:r,children:e.jsxs(U1,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(rw,{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(Xe,{variant:"outline",className:zt("text-xs",Q.color),children:Q.label}),e.jsxs(Xe,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(nw,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(IVs,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",size:"icon",onClick:()=>n(s),children:e.jsx(iu,{className:"h-4 w-4"})}),e.jsx(q,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>B(!0),children:e.jsx(zr,{className:"h-4 w-4"})})]})]})}),e.jsx(ui,{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:()=>{r(!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(Wn,{className:"h-10 w-10",children:e.jsxs(Kn,{className:"bg-primary/10 text-primary",children:[(ze=s.contact.first_name)==null?void 0:ze[0],(Ve=s.contact.last_name)==null?void 0:Ve[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(q,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(Mn,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(q,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(Ks,{className:"h-4 w-4"})})}),e.jsx(q,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{r(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(un,{className:"h-4 w-4"})})]})]}),e.jsx(KVs,{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(Pn,{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:te(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:te(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?` (${te(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:te(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:te(s.net_commission)})]})})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(q,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(wo,{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(qn,{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:zt("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(vn,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",As(El(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Xl,{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(qVs,{deal:s}),e.jsxs(ta,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(ea,{className:"w-full grid grid-cols-3",children:[e.jsxs(rs,{value:"tasks",className:"gap-1",children:[e.jsx(qn,{className:"h-4 w-4"}),"Tasks ",fe>0&&`(${de}/${fe})`]}),e.jsxs(rs,{value:"files",className:"gap-1",children:[e.jsx(iS,{className:"h-4 w-4"}),"Files ",je>0&&`(${je})`]}),e.jsxs(rs,{value:"activity",className:"gap-1",children:[e.jsx(jn,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(fs,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Add a new task...",value:R,onChange:Le=>F(Le.target.value),onKeyDown:Le=>Le.key==="Enter"&&ae()}),e.jsx(q,{onClick:ae,disabled:!R.trim(),children:e.jsx(Ys,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(Le=>e.jsxs("div",{className:zt("flex items-center gap-3 p-3 rounded-lg border transition-colors",Le.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(Ri,{checked:Le.is_completed,onCheckedChange:$e=>ue(Le.id,!!$e)}),e.jsx("span",{className:zt("flex-1 text-sm",Le.is_completed&&"line-through text-muted-foreground"),children:Le.title}),Le.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:As(new Date(Le.due_date),"MMM d")})]},Le.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(fs,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:A,className:"hidden",multiple:!0,onChange:Me,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(q,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var Le;return(Le=A.current)==null?void 0:Le.click()},disabled:K,children:[K?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ka,{className:"h-4 w-4 mr-2"}),K?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[_==null?void 0:_.map(Le=>{const $e=Ee(Le.file_type);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-background",children:[e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center shrink-0",children:e.jsx($e,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Le.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[xe(Le.file_size)," · ",As(new Date(Le.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(J_,{children:e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${Le.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>C.mutate({fileId:Le.id,visible:!Le.visible_on_portal,dealId:s.id}),children:Le.visible_on_portal?e.jsx(Nn,{className:"h-4 w-4"}):e.jsx(Wf,{className:"h-4 w-4"})})}),e.jsx(Sc,{side:"top",children:Le.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Ie(Le.storage_path,Le.file_name),children:e.jsx(li,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Oe(Le.id,Le.storage_path),children:e.jsx($r,{className:"h-4 w-4"})})]})]},Le.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(fs,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(pr,{placeholder:"Add a note...",value:E,onChange:Le=>D(Le.target.value),rows:2}),e.jsxs(q,{onClick:ne,disabled:!E.trim(),size:"sm",className:"w-full",children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(Le=>{const $e=ZVs[Le.activity_type]||jn;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($e,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:Le.title}),Le.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:Le.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Nl(new Date(Le.created_at),{addSuffix:!0})})]})]},Le.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(el,{open:O,onOpenChange:B,children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete Deal?"}),e.jsxs(Ho,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:me,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function QVs({open:s,onOpenChange:t,deal:r,onComplete:n}){const a=Oge(),i=A1t(),{data:l}=I8(),{data:o}=H0(),[c,d]=k.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:As(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});k.useEffect(()=>{if(r&&s){const f=r.deal_type==="seller"?"seller":"buyer",x=r.expected_price||0,y=r.commission_percentage||3,_=r.expected_commission||x*y/100;d({property_address:r.property_address||r.deal_name||"",city:r.city||"",state:r.state||"",zip:r.zip_code||"",transaction_type:f,close_date:r.actual_close_date||r.target_close_date||As(new Date,"yyyy-MM-dd"),sale_price:x,commission_amount:_,lead_source_id:"",client_type_id:"",notes:r.notes||""})}},[r,s]);const u=async f=>{if(f.preventDefault(),!!r)try{const x=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:r.brokerage_split_pct||null,team_split_pct:r.team_split_pct||null,franchise_fee_pct:r.franchise_fee_pct||null,referral_fee_pct:r.referral_fee_pct||null,transaction_fee:r.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:r.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:r.id,scorecard_transaction_id:x.id,actual_close_date:c.close_date}),he.success("Deal added to Scorecard! 🎉"),t(!1),n==null||n()}catch(x){console.error("Error syncing to scorecard:",x),he.error("Failed to add to scorecard")}},m=f=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(f);return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{className:"space-y-3",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/20",children:e.jsx(wo,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(bs,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(an,{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(ce,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(Pn,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(Ne,{id:"property_address",value:c.property_address,onChange:f=>d(x=>({...x,property_address:f.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(ce,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:c.city,onChange:f=>d(x=>({...x,city:f.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:c.state,onChange:f=>d(x=>({...x,state:f.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"zip",children:"Zip"}),e.jsx(Ne,{id:"zip",value:c.zip,onChange:f=>d(x=>({...x,zip:f.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(ce,{children:"Transaction Type *"}),e.jsxs(Ds,{value:c.transaction_type,onValueChange:f=>d(x=>({...x,transaction_type:f})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"buyer",children:"Buyer"}),e.jsx(lt,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(Ne,{id:"close_date",type:"date",value:c.close_date,onChange:f=>d(x=>({...x,close_date:f.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(ce,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(Xl,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(Ne,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:f=>d(x=>({...x,sale_price:Number(f.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(UE,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(Ne,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:f=>d(x=>({...x,commission_amount:Number(f.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Lead Source"}),e.jsxs(Ds,{value:c.lead_source_id,onValueChange:f=>d(x=>({...x,lead_source_id:f})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select source"})}),e.jsx(Ls,{children:l==null?void 0:l.map(f=>e.jsx(lt,{value:f.id,children:f.name},f.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Client Type"}),e.jsxs(Ds,{value:c.client_type_id,onValueChange:f=>d(x=>({...x,client_type_id:f})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select type"})}),e.jsx(Ls,{children:o==null?void 0:o.map(f=>e.jsx(lt,{value:f.id,children:f.name},f.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"notes",children:"Notes"}),e.jsx(pr,{id:"notes",value:c.notes,onChange:f=>d(x=>({...x,notes:f.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(fn,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(q,{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(ci,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const JVs={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"}},LKe={urgent:0,high:1,medium:2,low:3};function eHs({deals:s,stages:t,onDealClick:r,onStageChange:n}){const[a,i]=k.useState("target_close_date"),[l,o]=k.useState("asc"),c=x=>{a===x?o(y=>y==="asc"?"desc":"asc"):(i(x),o("asc"))},d=k.useMemo(()=>[...s].sort((x,y)=>{var b,j;let _=0;switch(a){case"deal_name":_=x.deal_name.localeCompare(y.deal_name);break;case"stage":{const N=((b=t.find(A=>A.id===x.stage_id))==null?void 0:b.sort_order)||0,C=((j=t.find(A=>A.id===y.stage_id))==null?void 0:j.sort_order)||0;_=N-C;break}case"expected_price":_=(x.expected_price||0)-(y.expected_price||0);break;case"expected_commission":_=(x.expected_commission||0)-(y.expected_commission||0);break;case"target_close_date":{const N=x.target_close_date?El(x.target_close_date).getTime():1/0,C=y.target_close_date?El(y.target_close_date).getTime():1/0;_=N-C;break}case"priority":_=LKe[x.priority]-LKe[y.priority];break}return l==="asc"?_:-_}),[s,t,a,l]),u=x=>x?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(x):"—",m=x=>x?t.find(y=>y.id===x):null,f=({field:x,children:y})=>e.jsxs(q,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(x),children:[y,a===x?l==="asc"?e.jsx(qu,{className:"ml-2 h-4 w-4"}):e.jsx(gm,{className:"ml-2 h-4 w-4"}):e.jsx(Uu,{className:"ml-2 h-4 w-4 opacity-50"})]});return s.length===0?e.jsx("div",{className:"text-center py-16",children:e.jsx("p",{className:"text-muted-foreground",children:"No deals to display"})}):e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{className:"bg-muted/50",children:[e.jsx(At,{className:"w-[250px]",children:e.jsx(f,{field:"deal_name",children:"Deal Name"})}),e.jsx(At,{className:"w-[150px]",children:e.jsx(f,{field:"stage",children:"Stage"})}),e.jsx(At,{className:"w-[100px]",children:"Type"}),e.jsx(At,{className:"w-[120px]",children:e.jsx(f,{field:"expected_price",children:"Price"})}),e.jsx(At,{className:"w-[120px]",children:e.jsx(f,{field:"expected_commission",children:"GCI"})}),e.jsx(At,{className:"w-[130px]",children:e.jsx(f,{field:"target_close_date",children:"Close Date"})}),e.jsx(At,{className:"w-[100px]",children:e.jsx(f,{field:"priority",children:"Priority"})})]})}),e.jsx(ha,{children:d.map(x=>{m(x.stage_id);const y=JVs[x.deal_type],_=x.target_close_date?lv(El(x.target_close_date),new Date):null,b=_!==null&&_<0,j=_!==null&&_<=7&&_>=0;return e.jsxs(Ws,{className:zt("cursor-pointer hover:bg-muted/50 transition-colors",b&&"bg-red-50/50"),onClick:()=>r(x),children:[e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:x.deal_name}),x.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[x.contact.first_name," ",x.contact.last_name]})]})}),e.jsx(xt,{onClick:N=>N.stopPropagation(),children:e.jsx(L1t,{stages:t,currentStageId:x.stage_id||"",onStageSelect:(N,C)=>n(x.id,N,C)})}),e.jsx(xt,{children:e.jsx(Xe,{variant:"outline",className:zt("text-xs",y.color),children:y.label})}),e.jsx(xt,{children:e.jsx("span",{className:"font-medium",children:u(x.expected_price)})}),e.jsx(xt,{children:e.jsx("span",{className:"text-emerald-600",children:u(x.expected_commission)})}),e.jsx(xt,{children:x.target_close_date?e.jsxs("div",{className:zt("flex items-center gap-1 text-sm",b&&"text-red-600",j&&!b&&"text-amber-600"),children:[b&&e.jsx(go,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:As(El(x.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(xt,{children:e.jsx(Xe,{variant:"outline",className:zt("text-xs capitalize",x.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",x.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",x.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",x.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:x.priority})})]},x.id)})})]})})}function tHs(){const s=xa();return pt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function sHs(s){const t=xa();return pt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:r,error:n}=await U.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return r},enabled:!!t&&!!s})}function rHs(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("deal_tasks").insert({owner_user_id:s,title:r.title,description:r.description||null,deal_id:r.deal_id||null,contact_id:r.contact_id||null,stage_id:r.stage_id||null,priority:r.priority||"medium",status:r.status||"todo",due_date:r.due_date||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function nHs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("deal_tasks").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function aHs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("deal_tasks").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function fIe(){const s=is();return Mt({mutationFn:async({id:t,status:r})=>{const{data:n,error:a}=await U.from("deal_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function iHs(){const s=is();return Mt({mutationFn:async t=>{if(t.length===0)return;const{error:r}=await U.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function oHs(s){const t=xa();return pt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let r=U.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(r=r.eq("stage_id",s));const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})}function lHs(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("deal_task_templates").insert({owner_user_id:s,stage_id:r.stage_id,title:r.title,description:r.description||null,priority:r.priority||"medium",default_due_offset_days:r.default_due_offset_days||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function cHs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("deal_task_templates").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function dHs(){const s=xa(),t=is();return Mt({mutationFn:async({dealId:r,stageId:n})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",n).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await U.from("deal_tasks").select("title, stage_id").eq("deal_id",r).eq("stage_id",n),o=new Set((l||[]).map(m=>m.title)),c=a.filter(m=>!o.has(m.title)).map((m,f)=>({owner_user_id:s,deal_id:r,stage_id:n,title:m.title,description:m.description,priority:m.priority,due_date:m.default_due_offset_days?new Date(Date.now()+m.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:f,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await U.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const uHs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function hHs({open:s,onOpenChange:t,dealId:r,dealName:n,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=sHs(s?r:void 0),u=iHs(),m=dHs(),[f,x]=k.useState(new Set),[y,_]=k.useState(!1),b=(c||[]).filter(A=>A.status!=="done");k.useEffect(()=>{b.length>0&&x(new Set(b.map(A=>A.id)))},[c]);const j=A=>{x(E=>{const D=new Set(E);return D.has(A)?D.delete(A):D.add(A),D})},N=async()=>{_(!0);try{const A=Array.from(f);A.length>0&&await u.mutateAsync(A),await o(),await m.mutateAsync({dealId:r,stageId:l}),t(!1)}catch(A){console.error("Stage move failed:",A),he.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{_(!1)}},C=async()=>{_(!0);try{await o(),await m.mutateAsync({dealId:r,stageId:l}),t(!1)}catch(A){console.error("Stage move (skip) failed:",A),he.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{_(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[480px]",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Move Deal"}),e.jsxs(an,{children:["Moving ",e.jsx("span",{className:"font-medium text-foreground",children:n})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2",children:[e.jsx(Xe,{variant:"outline",className:"text-sm",children:a}),e.jsx(ci,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Xe,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You have ",e.jsx("span",{className:"font-medium text-foreground",children:b.length})," incomplete task",b.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(ui,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:b.map(A=>e.jsxs("label",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsx(Ri,{checked:f.has(A.id),onCheckedChange:()=>j(A.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[uHs[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(q,{variant:"ghost",size:"sm",onClick:()=>{f.size===b.length?x(new Set):x(new Set(b.map(A=>A.id)))},children:f.size===b.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",size:"sm",onClick:C,disabled:y,children:"Skip"}),e.jsxs(q,{size:"sm",onClick:N,disabled:y,children:[y&&e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}),f.size>0?`Complete ${f.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(qn,{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(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:N,disabled:y,children:[y&&e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const mHs=[{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 O1t({open:s,onOpenChange:t}){const r=xa(),{data:n,isLoading:a}=glt(),i=tKt(),[l,o]=k.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null}),[c,d]=k.useState(null);k.useEffect(()=>{s&&o({logo_url:(n==null?void 0:n.logo_url)??null,cover_photo_url:(n==null?void 0:n.cover_photo_url)??null,brand_color:(n==null?void 0:n.brand_color)??null,accent_color:(n==null?void 0:n.accent_color)??null,tagline:(n==null?void 0:n.tagline)??null,welcome_message:(n==null?void 0:n.welcome_message)??null})},[s,n]);const u=x=>o(y=>({...y,...x})),m=async(x,y)=>{if(r){if(x.size>5*1024*1024){he.error("Image must be under 5MB");return}d(y);try{const _=await ylt(r,x,y);u(y==="logo"?{logo_url:_}:{cover_photo_url:_})}catch(_){he.error(`Upload failed: ${_.message||_}`)}finally{d(null)}}},f=async()=>{try{await i.mutateAsync(l),he.success("Portal branding saved"),t(!1)}catch{he.error("Failed to save branding")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(dl,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(an,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(ui,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(fHs,{draft:l}),e.jsx(DKe,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:x=>m(x,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(DKe,{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:x=>m(x,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{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:mHs.map(x=>{const y=l.brand_color===x.brand&&l.accent_color===x.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:x.brand,accent_color:x.accent}),className:zt("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:x.brand}}),e.jsx("div",{className:"flex-1",style:{background:x.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:x.name})]},x.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(RKe,{label:"Brand",value:l.brand_color,onChange:x=>u({brand_color:x})}),e.jsx(RKe,{label:"Accent",value:l.accent_color,onChange:x=>u({accent_color:x})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Tagline"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Short line shown under your name."}),e.jsx(Ne,{value:l.tagline||"",onChange:x=>u({tagline:x.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(ce,{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:x=>u({welcome_message:x.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(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(q,{onClick:f,disabled:i.isPending,children:[i.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function fHs({draft:s}){const t=s.brand_color||"#2a4c64",r=s.accent_color||"#406E71";return e.jsxs("div",{className:"rounded-xl overflow-hidden border border-input shadow-sm",children:[e.jsx("div",{className:"relative h-24 flex items-center justify-center text-white",style:{background:s.cover_photo_url?`linear-gradient(135deg, ${t}cc, ${r}cc), url(${s.cover_photo_url}) center/cover`:`linear-gradient(135deg, ${t}, ${r})`},children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:"logo",className:"h-12 w-12 rounded-full object-cover border-2 border-white/40 shadow"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 border-2 border-white/40"})}),e.jsxs("div",{className:"bg-white p-3 text-center",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:"Your Name"}),e.jsx("div",{className:"text-[11px] text-slate-500",children:s.tagline||"Your tagline appears here"})]})]})}function DKe({label:s,hint:t,value:r,uploading:n,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(ce,{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:zt("rounded-lg border-2 border-dashed border-input flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",l==="square"?"h-16 w-16":"h-16 w-32"),children:r?e.jsx("img",{src:r,alt:s,className:"h-full w-full object-cover"}):e.jsx(zo,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:o=>{var d;const c=(d=o.target.files)==null?void 0:d[0];c&&a(c),o.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[n?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ka,{className:"h-3.5 w-3.5"}),r?"Replace":"Upload"]})]}),r&&e.jsx(q,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})]})}function RKe({label:s,value:t,onChange:r}){const n=t||"#000000";return e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:s}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 h-9 rounded-md border border-input bg-background px-2",children:[e.jsx("input",{type:"color",value:n,onChange:a=>r(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(Ne,{value:t||"",onChange:a=>r(a.target.value||null),placeholder:"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"})]})]})}function pHs(){const s=xa();return pt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("client_portals").select("*").eq("owner_user_id",s);if(r)throw r;return t||[]},enabled:!!s})}function xHs({dealId:s,dealName:t,contactName:r,portal:n,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=c6e(),d=nD(),u=nyt(),m=ayt(),[f,x]=k.useState(!1),y=!!(n!=null&&n.archived_at),_=async()=>{x(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),he.success("Portal enabled!")}catch{he.error("Failed to create portal")}finally{x(!1)}},b=async E=>{if(n)try{await d.mutateAsync({id:n.id,is_enabled:E}),he.success(E?"Portal enabled":"Portal disabled")}catch{he.error("Failed to update portal")}},j=()=>{n&&(navigator.clipboard.writeText(R_(n.slug)),he.success("Link copied!"))},N=()=>{n&&window.open(R_(n.slug),"_blank")},C=async()=>{if(n)try{await u.mutateAsync(n.id),he.success("Portal archived")}catch{he.error("Failed to archive portal")}},A=async()=>{if(n)try{await m.mutateAsync(n.id),he.success("Portal restored")}catch{he.error("Failed to restore portal")}};return n?y?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(Vn,{to:`/mission-control/client-portals/${n.id}`,className:"flex-1 min-w-0 hover:opacity-80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx(Xe,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.client_name||r||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(q,{variant:"ghost",size:"sm",onClick:A,className:"text-xs gap-1",children:[e.jsx(qI,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>o(n),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(zr,{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(Vn,{to:`/mission-control/client-portals/${n.id}`,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:t}),e.jsx(Xe,{variant:"outline",className:n.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:n.is_enabled?"Active":"Disabled"}),e.jsx(Ia,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.client_name||r||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:j,title:"Copy link",children:e.jsx(si,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:N,title:"Preview",children:e.jsx(un,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(n,t),title:"Invite client",children:e.jsx(hn,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(n),title:"Post update",children:e.jsx(c_,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(n),title:"Settings",children:e.jsx(Bo,{className:"h-3.5 w-3.5"})}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(f0,{className:"h-3.5 w-3.5"})})}),e.jsx(Sd,{align:"end",children:e.jsxs(ti,{onClick:C,children:[e.jsx(Qk,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(Rr,{checked:n.is_enabled,onCheckedChange:b,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r||"No contact"})]}),e.jsxs(q,{size:"sm",onClick:_,disabled:f,className:"shrink-0 ml-4",children:[f?e.jsx(ls,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function F1t(){const{data:s,isLoading:t}=Wye(),{data:r,isLoading:n}=pHs(),[a,i]=k.useState(""),[l,o]=k.useState("all"),c=iyt(),[d,u]=k.useState(null),[m,f]=k.useState(null),[x,y]=k.useState(null),[_,b]=k.useState(null),[j,N]=k.useState(!1),C=xa(),A=t||n,E=new Map;r==null||r.forEach(Z=>E.set(Z.deal_id,Z));const R=[...(s||[]).filter(Z=>{var ae,ue,me,de,fe;const Q=E.get(Z.id),W=a.toLowerCase(),te=!W||Z.deal_name.toLowerCase().includes(W)||((ue=(ae=Z.contact)==null?void 0:ae.first_name)==null?void 0:ue.toLowerCase().includes(W))||((de=(me=Z.contact)==null?void 0:me.last_name)==null?void 0:de.toLowerCase().includes(W))||((fe=Q==null?void 0:Q.client_name)==null?void 0:fe.toLowerCase().includes(W));let ne=!0;return l==="active"?ne=!!(Q!=null&&Q.is_enabled)&&!(Q!=null&&Q.archived_at):l==="disabled"?ne=!!Q&&!Q.is_enabled&&!Q.archived_at:l==="archived"?ne=!!(Q!=null&&Q.archived_at):l==="none"?ne=!Q:l==="all"&&(ne=!(Q!=null&&Q.archived_at)||!Q),te&&ne})].sort((Z,Q)=>{const W=E.get(Z.id),te=E.get(Q.id);if(W!=null&&W.archived_at&&!(te!=null&&te.archived_at))return 1;if(!(W!=null&&W.archived_at)&&(te!=null&&te.archived_at)||W&&!te)return-1;if(!W&&te)return 1;if(W&&te){if(W.is_enabled&&!te.is_enabled)return-1;if(!W.is_enabled&&te.is_enabled)return 1}return 0}),F=(r==null?void 0:r.filter(Z=>!Z.archived_at).length)||0,O=(r==null?void 0:r.filter(Z=>Z.is_enabled&&!Z.archived_at).length)||0,B=(r==null?void 0:r.filter(Z=>Z.archived_at).length)||0,K=async()=>{if(_)try{await c.mutateAsync({id:_.id,dealId:_.deal_id}),he.success("Portal permanently deleted"),b(null)}catch{he.error("Failed to delete portal")}};return A?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(ls,{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(Ir,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[F," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[O," active · ",F-O," disabled",B>0&&` · ${B} archived`]})]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>N(!0),className:"gap-1.5",children:[e.jsx(dl,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search deals or clients...",value:a,onChange: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($r,{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(q,{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(ui,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[R.map(Z=>{const Q=E.get(Z.id)||null,W=Z.contact?`${Z.contact.first_name||""} ${Z.contact.last_name||""}`.trim():"";return e.jsx(xHs,{dealId:Z.id,dealName:Z.deal_name,contactName:W,portal:Q,onSettingsOpen:u,onComposerOpen:te=>f(te),onInviteOpen:(te,ne)=>y({portal:te,dealName:ne}),onDeleteConfirm:b},Z.id)}),R.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Ir,{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(uIe,{open:!!d,onOpenChange:Z=>!Z&&u(null),portal:d,dealOwnerId:C||""}),m&&e.jsx(hIe,{open:!!m,onOpenChange:Z=>!Z&&f(null),portalId:m.id,portalSlug:m.slug,notifyClient:m.notify_client}),x&&e.jsx(mIe,{open:!!x,onOpenChange:Z=>!Z&&y(null),portal:x.portal,dealName:x.dealName}),e.jsx(O1t,{open:j,onOpenChange:N}),e.jsx(el,{open:!!_,onOpenChange:Z=>!Z&&b(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Permanently delete this portal?"}),e.jsx(Ho,{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(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:K,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class gHs extends k.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){console.error("DealPipeline error:",t,r)}render(){return this.state.hasError?e.jsx(ws,{children:e.jsxs("div",{className:"flex flex-col items-center justify-center h-[60vh] gap-4 text-center px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"text-2xl",children:"⚠️"})}),e.jsx("h2",{className:"text-xl font-semibold",children:"Something went wrong"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"There was an error in the deal pipeline. Click below to try again."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),className:"px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90",children:"Try Again"}),e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 border border-border rounded-md text-sm font-medium hover:bg-muted",children:"Refresh Page"})]})]})}):this.props.children}}const xO="deal-pipeline-detail-sheet";function yHs(){var js;const s=rD(),{data:t,isLoading:r}=Gye(),{data:n,isLoading:a,refetch:i}=Wye(),{data:l,isLoading:o}=Dqs(),c=T1t(),d=Tqs(),[u,m]=k.useState("board"),[f,x]=k.useState(!1),[y,_]=k.useState(!1),[b,j]=k.useState(null),[N,C]=k.useState(null),[A,E]=k.useState(null),[D,R]=k.useState(null),[F,O]=k.useState(!1),[B,K]=k.useState(null),[Z,Q]=k.useState(""),[W,te]=k.useState("all"),[ne,ae]=k.useState("all"),[ue,me]=k.useState("all"),{data:de}=jVs(),[fe,je]=k.useState(!1),[xe,Ee]=k.useState(!1),[Me,Oe]=k.useState(new Set),Ie=k.useRef(!1),[ze,Ve]=k.useState(null),{data:Le}=uv(),{isTeamLeader:$e,teamMembers:ve}=_Vs(),Qe=k.useMemo(()=>Array.from(Me),[Me]),{data:we}=wVs(Qe),nt=k.useMemo(()=>{const $s=new Map;return ve.forEach(Js=>$s.set(Js.id,{name:Js.name,avatar_url:Js.avatar_url,color:Js.color})),$s},[ve]),Se=k.useCallback($s=>$s.owner_user_id&&nt.get($s.owner_user_id)||null,[nt]),Ge=k.useCallback($s=>{Oe(Js=>{const or=new Set(Js);return or.has($s)?or.delete($s):or.add($s),or})},[]);k.useEffect(()=>{!r&&t&&t.length===0&&c.mutate()},[r,t]);const[We,Ce]=ic(),qe=k.useRef(!1);k.useEffect(()=>{const $s=We.get("deal");if($s&&n&&n.length>0&&!qe.current){const Js=n.find(or=>or.id===$s);Js&&(qe.current=!0,j(Js),_(!0),We.delete("deal"),Ce(We,{replace:!0}))}},[n,We]);const et=k.useMemo(()=>{if(!we||!t)return[];const $s=new Map(t.map(Js=>[Js.name,Js.id]));return we.map(Js=>{const or=Js._stage_name&&$s.get(Js._stage_name)||null;return{...Js,stage_id:or||Js.stage_id}})},[we,t]),Ze=k.useMemo(()=>[...n||[],...et],[n,et]);k.useEffect(()=>{if(Ie.current||Ze.length===0)return;Ie.current=!0;const $s=sessionStorage.getItem(xO);if($s)try{const Js=JSON.parse($s);if(!Js.open||!Js.dealId)return;const or=Ze.find(Er=>Er.id===Js.dealId);or&&(j(or),_(!0))}catch{sessionStorage.removeItem(xO)}},[Ze]),k.useEffect(()=>{y&&(b!=null&&b.id)?sessionStorage.setItem(xO,JSON.stringify({dealId:b.id,open:!0})):sessionStorage.removeItem(xO)},[y,b==null?void 0:b.id]);const rt=(de==null?void 0:de.byDeal)||{},ct=(de==null?void 0:de.unique)||[],vt=Ze.filter($s=>{var gs,mi,In,Br,ps,Or;const Js=Z.toLowerCase(),or=rt[$s.id]||[],Er=!Js||$s.deal_name.toLowerCase().includes(Js)||((mi=(gs=$s.contact)==null?void 0:gs.first_name)==null?void 0:mi.toLowerCase().includes(Js))||((Br=(In=$s.contact)==null?void 0:In.last_name)==null?void 0:Br.toLowerCase().includes(Js))||((ps=$s.property_address)==null?void 0:ps.toLowerCase().includes(Js))||((Or=$s.city)==null?void 0:Or.toLowerCase().includes(Js))||or.some(Qr=>Qr.toLowerCase().includes(Js)),Sr=W==="all"||$s.deal_type===W,Gr=ne==="all"||or.includes(ne),Yr=$s.actual_close_date||$s.target_close_date||$s.contract_date||$s.created_at,Fn=Yr?String(Yr).slice(0,4):null;return Er&&Sr&&Gr&&(ue==="all"||Fn===ue)}),kt=k.useMemo(()=>{const $s=new Set;return $s.add(String(new Date().getFullYear())),Ze.forEach(Js=>{const or=Js.actual_close_date||Js.target_close_date||Js.contract_date||Js.created_at;or&&$s.add(String(or).slice(0,4))}),Array.from($s).sort((Js,or)=>Number(or)-Number(Js))},[Ze]),St=k.useMemo(()=>{if(!t)return l||null;const $s=new Set(t.filter(Yr=>Yr.is_won_stage).map(Yr=>Yr.id)),Js=new Set(t.filter(Yr=>Yr.is_lost_stage).map(Yr=>Yr.id)),or=Ze.filter(Yr=>Yr.stage_id&&!$s.has(Yr.stage_id)&&!Js.has(Yr.stage_id)),Er=Ze.filter(Yr=>Yr.stage_id&&$s.has(Yr.stage_id)),Sr=new Date().getFullYear(),Gr=Er.filter(Yr=>Yr.actual_close_date?new Date(Yr.actual_close_date).getFullYear()===Sr:!0);return{totalDeals:Ze.length,activeDeals:or.length,wonDeals:Er.length,pipelineValue:or.reduce((Yr,Fn)=>Yr+(Fn.expected_price||0),0),expectedCommission:or.reduce((Yr,Fn)=>Yr+(Fn.expected_commission||0),0),expectedNetToAgent:or.reduce((Yr,Fn)=>Yr+(Vy(Fn)||0),0),wonValue:Er.reduce((Yr,Fn)=>Yr+(Fn.expected_price||0),0),weightedGCI:or.reduce((Yr,Fn)=>Yr+(Fn.expected_commission||0)*((Fn.probability??50)/100),0),weightedNet:or.reduce((Yr,Fn)=>Yr+(Vy(Fn)||0)*((Fn.probability??50)/100),0),ytdWonDeals:Gr.length,ytdWonGCI:Gr.reduce((Yr,Fn)=>Yr+(Fn.expected_commission||0),0),ytdWonNet:Gr.reduce((Yr,Fn)=>Yr+(Vy(Fn)||0),0),projectedAnnualNet:Gr.reduce((Yr,Fn)=>Yr+(Vy(Fn)||0),0)+or.reduce((Yr,Fn)=>Yr+(Vy(Fn)||0)*((Fn.probability??50)/100),0)}},[Ze,t,l]),Yt=$s=>{j($s),_(!0)},es=$s=>{C($s||null),j(null),x(!0)},zs=$s=>{j($s),_(!1),x(!0)},sr=$s=>{_($s),$s||sessionStorage.removeItem(xO)},ms=($s,Js)=>{E($s)},gt=($s,Js)=>{$s.preventDefault(),$s.dataTransfer.dropEffect="move",R(Js)},Ut=async($s,Js)=>{if($s.preventDefault(),R(null),!A)return;const or=n==null?void 0:n.find(Gr=>Gr.id===A),Er=t==null?void 0:t.find(Gr=>Gr.id===Js),Sr=t==null?void 0:t.find(Gr=>Gr.id===(or==null?void 0:or.stage_id));if(!or||!Er||or.stage_id===Js){E(null);return}Ve({dealId:A,dealName:or.deal_name,fromStageName:(Sr==null?void 0:Sr.name)||"Unknown",toStageName:Er.name,toStageId:Js,isWonStage:Er.is_won_stage,deal:or}),E(null)},ht=async()=>{if(!ze)return;const{dealId:$s,toStageId:Js,toStageName:or,isWonStage:Er,deal:Sr}=ze;if(await d.mutateAsync({dealId:$s,stageId:Js,stageName:or}),he.success(`Moved to ${or}`),Er&&!Sr.scorecard_transaction_id){const Gr={...Sr,stage_id:Js};K(Gr),O(!0)}},Jt=k.useCallback(async($s,Js,or)=>{const Er=n==null?void 0:n.find(Yr=>Yr.id===$s),Sr=t==null?void 0:t.find(Yr=>Yr.id===Js),Gr=t==null?void 0:t.find(Yr=>Yr.id===(Er==null?void 0:Er.stage_id));!Er||!Sr||Er.stage_id===Js||Ve({dealId:$s,dealName:Er.deal_name,fromStageName:(Gr==null?void 0:Gr.name)||"Unknown",toStageName:or,toStageId:Js,isWonStage:Sr.is_won_stage,deal:Er})},[n,t]),Ms=$s=>vt.filter(Js=>Js.stage_id===$s),ts=r||a,Xs=s?"list":u;return e.jsxs(ws,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"shrink-0 p-4 md:p-6 pb-0 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Deal Pipeline"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Track and manage your active deals"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"outline",size:"icon",onClick:()=>i(),className:"shrink-0",children:e.jsx(lo,{className:"h-4 w-4"})}),!s&&e.jsx(J_,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(q,{variant:u==="board"?"secondary":"ghost",size:"sm",onClick:()=>m("board"),className:"px-3 gap-1.5",children:[e.jsx(Ep,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(Sc,{children:"Kanban board view"})]}),e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(q,{variant:u==="list"?"secondary":"ghost",size:"sm",onClick:()=>m("list"),className:"px-3 gap-1.5",children:[e.jsx(Zf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(Sc,{children:"Grouped list view"})]}),e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(q,{variant:u==="table"?"secondary":"ghost",size:"sm",onClick:()=>m("table"),className:"px-3 gap-1.5",children:[e.jsx(iP,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(Sc,{children:"Sortable table view"})]}),e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsxs(q,{variant:u==="portals"?"secondary":"ghost",size:"sm",onClick:()=>m("portals"),className:"px-3 gap-1.5",children:[e.jsx(Ir,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(Sc,{children:"Client portal management"})]})]})}),Le&&!$e&&e.jsxs(q,{variant:"outline",onClick:()=>je(!0),children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(q,{onClick:()=>es(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),Xs!=="portals"&&e.jsx(CVs,{stats:St,isLoading:o}),Xs!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search deals, contacts, addresses, tags...",value:Z,onChange:$s=>Q($s.target.value),className:"pl-9 pr-8"}),Z&&e.jsx("button",{onClick:()=>Q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsxs(Ds,{value:W,onValueChange:te,children:[e.jsx(Ps,{className:"w-[140px]",children:e.jsx(Fs,{placeholder:"All Types"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),e.jsx(lt,{value:"buyer",children:"Buyer"}),e.jsx(lt,{value:"seller",children:"Seller"}),e.jsx(lt,{value:"dual",children:"Dual"}),e.jsx(lt,{value:"referral",children:"Referral"}),e.jsx(lt,{value:"lease",children:"Lease"})]})]}),e.jsxs(Ds,{value:ue,onValueChange:me,children:[e.jsx(Ps,{className:"w-[120px]",children:e.jsx(Fs,{placeholder:"Year"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Years"}),kt.map($s=>e.jsx(lt,{value:$s,children:$s},$s))]})]}),e.jsxs(Ds,{value:ne,onValueChange:ae,children:[e.jsxs(Ps,{className:"w-[160px]",children:[e.jsx(Fh,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(Fs,{placeholder:"All Tags"})]}),e.jsxs(Ls,{className:"max-h-[300px]",children:[e.jsx(lt,{value:"all",children:"All Tags"}),ct.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),ct.map($s=>e.jsx(lt,{value:$s,children:$s},$s))]})]}),ne!=="all"&&e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Fh,{className:"h-3 w-3"}),ne,e.jsx("button",{onClick:()=>ae("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx($r,{className:"h-3 w-3"})})]}),(Z||W!=="all"||ne!=="all"||ue!=="all")&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[vt.length," of ",(n==null?void 0:n.length)||0," deals"]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[$e&&!s&&ve.length>0&&e.jsx(bVs,{members:ve,enabledMembers:Me,onToggleMember:Ge,isOpen:xe,onToggleOpen:()=>Ee($s=>!$s)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:ts?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(dr,{className:"h-full rounded-xl"})},$s))}):Xs==="board"?e.jsxs(ui,{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(SVs,{stage:$s,deals:Ms($s.id),onDealClick:Yt,onAddDeal:es,onDragStart:ms,onDragOver:gt,onDrop:Ut,isDragOver:D===$s.id,isWonStage:$s.is_won_stage,getOwnerInfo:Se},$s.id))}),e.jsx(gge,{orientation:"horizontal"})]}):Xs==="table"?e.jsx(ui,{className:"h-full",children:e.jsx(eHs,{deals:vt,stages:t||[],onDealClick:Yt,onStageChange:Jt})}):Xs==="portals"?e.jsx(F1t,{}):e.jsx(ui,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map($s=>{const Js=Ms($s.id);return Js.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:["(",Js.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:Js.map(or=>e.jsx(D1t,{deal:or,onClick:()=>Yt(or),stages:t,onStageChange:Jt,showStagePicker:!0,isWonStage:$s.is_won_stage,ownerInfo:Se(or)},or.id))})]},$s.id)}),(n==null?void 0:n.length)===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Ep,{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(q,{onClick:()=>es(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((n==null?void 0:n.length)||0)>0&&vt.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(_n,{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(q,{variant:"outline",onClick:()=>{Q(""),te("all"),ae("all"),me("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(MVs,{open:f,onOpenChange:x,deal:b,defaultStageId:N}),e.jsx(XVs,{deal:b,open:y,onOpenChange:sr,onEdit:zs,isWonStage:b?(js=t==null?void 0:t.find($s=>$s.id===b.stage_id))==null?void 0:js.is_won_stage:!1,onAddToScorecard:$s=>{K($s),O(!0),_(!1)}}),e.jsx(QVs,{open:F,onOpenChange:O,deal:B,onComplete:()=>{i(),K(null)}}),ze&&e.jsx(hHs,{open:!!ze,onOpenChange:$s=>{$s||Ve(null)},dealId:ze.dealId,dealName:ze.dealName,fromStageName:ze.fromStageName,toStageName:ze.toStageName,toStageId:ze.toStageId,onConfirm:ht}),e.jsx(yVs,{open:fe,onOpenChange:je})]})}function vHs(){return e.jsx(gHs,{children:e.jsx(yHs,{})})}function z1t({open:s,onOpenChange:t,editTask:r,defaultDealId:n,defaultStageId:a}){var Q;const i=rHs(),l=nHs(),{data:o}=Wye(),c=xa(),{data:d}=pt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:W,error:te}=await U.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(te)throw te;return W},enabled:!!c&&s}),[u,m]=k.useState(""),[f,x]=k.useState(""),[y,_]=k.useState("none"),[b,j]=k.useState("none"),[N,C]=k.useState("medium"),[A,E]=k.useState("todo"),[D,R]=k.useState(),[F,O]=k.useState(!1),[B,K]=k.useState(!1);k.useEffect(()=>{r?(m(r.title),x(r.description||""),_(r.deal_id||"none"),j(r.contact_id||"none"),C(r.priority),E(r.status),R(r.due_date?yx(r.due_date):void 0)):(m(""),x(""),_(n||"none"),j("none"),C("medium"),E("todo"),R(void 0))},[r,s,n]);const Z=async()=>{if(!u.trim()){he.error("Task title is required");return}try{const W={title:u.trim(),description:f.trim()||null,deal_id:y==="none"?null:y,contact_id:b==="none"?null:b,stage_id:a||null,priority:N,status:A,due_date:D?As(D,"yyyy-MM-dd"):null};r?(await l.mutateAsync({id:r.id,...W}),he.success("Task updated")):(await i.mutateAsync(W),he.success("Task created")),t(!1)}catch{he.error("Failed to save task")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[480px]",children:[e.jsx(_s,{children:e.jsx(bs,{children:r?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Title *"}),e.jsx(Ne,{value:u,onChange:W=>m(W.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{value:f,onChange:W=>x(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(ce,{children:"Priority"}),e.jsxs(Ds,{value:N,onValueChange:W=>C(W),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"low",children:"🟢 Low"}),e.jsx(lt,{value:"medium",children:"🟡 Medium"}),e.jsx(lt,{value:"high",children:"🟠 High"}),e.jsx(lt,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Status"}),e.jsxs(Ds,{value:A,onValueChange:W=>E(W),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"todo",children:"To Do"}),e.jsx(lt,{value:"in_progress",children:"In Progress"}),e.jsx(lt,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Due Date"}),e.jsxs(sl,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",className:zt("w-full justify-start text-left font-normal",!D&&"text-muted-foreground"),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),D?As(D,"PPP"):"Pick a date"]})}),e.jsx(Ko,{className:"w-auto p-0",align:"start",children:e.jsx(_g,{mode:"single",selected:D,onSelect:R,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Link to Deal"}),e.jsxs(sl,{open:F,onOpenChange:O,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{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(Ga,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),y!=="none"?((Q=o==null?void 0:o.find(W=>W.id===y))==null?void 0:Q.deal_name)||"Select deal":"No Deal"]}),e.jsx(xg,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search deals..."}),e.jsxs(kg,{children:[e.jsx(Sg,{children:"No deals found."}),e.jsxs(Cg,{children:[e.jsxs(Sp,{value:"no-deal",onSelect:()=>{_("none"),O(!1)},children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",y==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(W=>e.jsxs(Sp,{value:W.deal_name,onSelect:()=>{_(W.id),O(!1)},children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",y===W.id?"opacity-100":"opacity-0")}),W.deal_name]},W.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Link to Contact"}),e.jsxs(sl,{open:B,onOpenChange:K,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{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(qi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),b!=="none"?(()=>{const W=d==null?void 0:d.find(te=>te.id===b);return W?`${W.first_name} ${W.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(xg,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search contacts..."}),e.jsxs(kg,{children:[e.jsx(Sg,{children:"No contacts found."}),e.jsxs(Cg,{children:[e.jsxs(Sp,{value:"no-contact",onSelect:()=>{j("none"),K(!1)},children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",b==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(W=>e.jsxs(Sp,{value:`${W.first_name} ${W.last_name}`,onSelect:()=>{j(W.id),K(!1)},children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",b===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(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{onClick:Z,disabled:i.isPending||l.isPending,children:r?"Save Changes":"Create Task"})]})]})]})})}const bHs={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 _Hs({tasks:s}){const t=fIe(),r=aHs(),n=qr(),[a,i]=k.useState(null),l=async u=>{const m=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:m})}catch{he.error("Failed to update task")}},o=async u=>{try{await r.mutateAsync(u),he.success("Task deleted")}catch{he.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(qn,{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 m=c.get(u.deal.id)||{dealName:u.deal.deal_name,tasks:[]};m.tasks.push(u),c.set(u.deal.id,m)}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(OKe,{task:u,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:m=>n(`/mission-control/pipeline?deal=${m}`)},u.id))]}),Array.from(c.entries()).map(([u,m])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>n(`/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(Ga,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:m.dealName}),e.jsxs(Xe,{variant:"secondary",className:"ml-auto text-xs",children:[m.tasks.filter(f=>f.status==="done").length,"/",m.tasks.length]}),e.jsx(Ia,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),m.tasks.map(f=>e.jsx(OKe,{task:f,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:x=>n(`/mission-control/pipeline?deal=${x}`)},f.id))]},u)),a&&e.jsx(z1t,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function OKe({task:s,onToggle:t,onDelete:r,onEdit:n,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&M_(yx(s.due_date))&&!um(yx(s.due_date)),o=!i&&s.due_date&&um(yx(s.due_date)),c=bHs[s.priority];return e.jsxs("div",{className:zt("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(qn,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Rh,{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:zt("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(qi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(Xe,{variant:"outline",className:zt("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:zt("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(jn,{className:"h-3 w-3"}),As(yx(s.due_date),"MMM d")]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>n(s),className:"p-1 hover:bg-muted rounded",children:e.jsx(iu,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>r(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(zr,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const wHs=[{status:"todo",label:"To Do",icon:Rh,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:Ff,color:"border-t-blue-500"},{status:"done",label:"Done",icon:qn,color:"border-t-emerald-500"}],jHs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function NHs({tasks:s}){const t=fIe(),r=k.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),n=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{he.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:wHs.map(i=>e.jsxs("div",{className:zt("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(Xe,{variant:"secondary",className:"ml-auto text-xs",children:r[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[r[i.status].map(l=>e.jsx(kHs,{task:l,onDragStart:n},l.id)),r[i.status].length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},i.status))})}function kHs({task:s,onDragStart:t}){const r=s.status==="done",n=!r&&s.due_date&&M_(yx(s.due_date))&&!um(yx(s.due_date)),a=!r&&s.due_date&&um(yx(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:zt("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",n&&"border-destructive/50"),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-xs mt-0.5",children:jHs[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:zt("text-sm font-medium",r&&"line-through text-muted-foreground"),children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[s.deal&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(Ga,{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(qi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:zt("text-[10px] mt-1.5 flex items-center gap-1",n&&"text-destructive font-medium",a&&"text-amber-600 font-medium",!n&&!a&&"text-muted-foreground"),children:[e.jsx(jn,{className:"h-2.5 w-2.5"}),n?"Overdue — ":a?"Due today — ":"",As(yx(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 FKe={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function SHs({tasks:s}){const[t,r]=k.useState(new Date),n=fIe(),a=qd(t),i=Py(t),l=Mp(a),o=ige(i),c=rOt({start:l,end:o}),d=k.useMemo(()=>{const f=new Map;return s.forEach(x=>{if(!x.due_date)return;const y=x.due_date,_=f.get(y)||[];_.push(x),f.set(y,_)}),f},[s]),u=k.useMemo(()=>s.filter(f=>!f.due_date),[s]),m=async f=>{const x=f.status==="done"?"todo":"done";try{await n.mutateAsync({id:f.id,status:x})}catch{he.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(q,{variant:"ghost",size:"icon",onClick:()=>r(YT(t,1)),children:e.jsx(jl,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:As(t,"MMMM yyyy")}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>r(Ex(t,1)),children:e.jsx(Ia,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(f=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:f},f))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(f=>{const x=As(f,"yyyy-MM-dd"),y=d.get(x)||[],_=lge(f,t),b=um(f);return e.jsxs("div",{className:zt("border-r border-b min-h-[100px] p-1",!_&&"bg-muted/30",b&&"bg-primary/5"),children:[e.jsx("div",{className:zt("text-xs font-medium mb-1 text-right px-1",!_&&"text-muted-foreground/40",b&&"text-primary font-bold"),children:As(f,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[y.slice(0,3).map(j=>e.jsxs("button",{onClick:()=>m(j),className:zt("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(qn,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Rh,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[FKe[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"]})]})]},x)})}),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(f=>e.jsxs("button",{onClick:()=>m(f),className:zt("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",f.status==="done"&&"opacity-50 line-through"),children:[f.status==="done"?e.jsx(qn,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Rh,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[FKe[f.priority]," ",f.title]}),f.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",f.deal.deal_name]})]},f.id))})]})]})}const CHs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function THs({open:s,onOpenChange:t,stages:r}){var j;const[n,a]=k.useState(((j=r[0])==null?void 0:j.id)||""),{data:i,isLoading:l}=oHs(n||void 0),o=lHs(),c=cHs(),[d,u]=k.useState(""),[m,f]=k.useState("medium"),[x,y]=k.useState(""),_=async()=>{if(!(!d.trim()||!n))try{await o.mutateAsync({stage_id:n,title:d.trim(),priority:m,default_due_offset_days:x?parseInt(x):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),y(""),he.success("Template added")}catch{he.error("Failed to add template")}},b=async N=>{try{await c.mutateAsync(N),he.success("Template deleted")}catch{he.error("Failed to delete template")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[560px]",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(jF,{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(ce,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:r.filter(N=>!N.is_won_stage&&!N.is_lost_stage).map(N=>e.jsx("button",{onClick:()=>a(N.id),className:zt("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",n===N.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:N.name},N.id))})]}),e.jsx(ui,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((N,C)=>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:CHs[N.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:N.title}),N.default_due_offset_days&&e.jsxs(Xe,{variant:"outline",className:"text-[10px]",children:["+",N.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>b(N.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(zr,{className:"h-3.5 w-3.5 text-destructive"})})]},N.id)),(i==null?void 0:i.length)===0&&n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),n&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Task title...",value:d,onChange:N=>u(N.target.value),className:"flex-1",onKeyDown:N=>N.key==="Enter"&&_()}),e.jsxs(Ds,{value:m,onValueChange:N=>f(N),children:[e.jsx(Ps,{className:"w-[100px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"low",children:"🟢 Low"}),e.jsx(lt,{value:"medium",children:"🟡 Med"}),e.jsx(lt,{value:"high",children:"🟠 High"}),e.jsx(lt,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ce,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(Ne,{type:"number",placeholder:"e.g., 7",value:x,onChange:N=>y(N.target.value)})]}),e.jsxs(q,{onClick:_,disabled:!d.trim()||o.isPending,children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function EHs(){const{data:s,isLoading:t}=tHs(),{data:r}=Gye(),[n,a]=k.useState("list"),[i,l]=k.useState(""),[o,c]=k.useState("active"),[d,u]=k.useState("all"),[m,f]=k.useState("all"),[x,y]=k.useState(!1),[_,b]=k.useState(!1),j=k.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,D])=>({id:E,name:D}))},[s]),N=k.useMemo(()=>s?s.filter(A=>{var B,K,Z,Q;const E=i.toLowerCase(),D=!E||A.title.toLowerCase().includes(E)||((K=(B=A.deal)==null?void 0:B.deal_name)==null?void 0:K.toLowerCase().includes(E))||`${((Z=A.contact)==null?void 0:Z.first_name)||""} ${((Q=A.contact)==null?void 0:Q.last_name)||""}`.toLowerCase().includes(E),R=o==="all"||o==="active"&&A.status!=="done"||o==="todo"&&A.status==="todo"||o==="in_progress"&&A.status==="in_progress"||o==="done"&&A.status==="done"||o==="overdue"&&A.status!=="done"&&A.due_date&&M_(yx(A.due_date))&&!um(yx(A.due_date)),F=d==="all"||A.priority===d,O=m==="all"||m==="no_deal"&&!A.deal_id||A.deal_id===m;return D&&R&&F&&O}):[],[s,i,o,d,m]),C=k.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&&M_(yx(E.due_date))&&!um(yx(E.due_date))).length,dueToday:A.filter(E=>E.due_date&&um(yx(E.due_date))).length,dueThisWeek:A.filter(E=>E.due_date&&JFt(yx(E.due_date))).length,completed:s.filter(E=>E.status==="done").length}},[s]);return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>b(!0),children:[e.jsx(C1,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(q,{size:"sm",onClick:()=>y(!0),children:[e.jsx(Ys,{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(Zf,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:C.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(du,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:C.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(jn,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:C.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(xu,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:C.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(qn,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:C.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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search tasks...",value:i,onChange:A=>l(A.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:d,onValueChange:u,children:[e.jsx(Ps,{className:"w-[130px]",children:e.jsx(Fs,{placeholder:"Priority"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Priorities"}),e.jsx(lt,{value:"urgent",children:"🔴 Urgent"}),e.jsx(lt,{value:"high",children:"🟠 High"}),e.jsx(lt,{value:"medium",children:"🟡 Medium"}),e.jsx(lt,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(Ds,{value:m,onValueChange:f,children:[e.jsx(Ps,{className:"w-[160px]",children:e.jsx(Fs,{placeholder:"Deal"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Deals"}),e.jsx(lt,{value:"no_deal",children:"No Deal"}),j.map(A=>e.jsx(lt,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${n==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(Zf,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("kanban"),className:`p-1.5 rounded-md transition-colors ${n==="kanban"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(i2,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("calendar"),className:`p-1.5 rounded-md transition-colors ${n==="calendar"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(xu,{className:"h-4 w-4"})})]})]}),t?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full"})}):e.jsxs(e.Fragment,{children:[n==="list"&&e.jsx(_Hs,{tasks:N}),n==="kanban"&&e.jsx(NHs,{tasks:N}),n==="calendar"&&e.jsx(SHs,{tasks:N})]}),e.jsx(z1t,{open:x,onOpenChange:y}),e.jsx(THs,{open:_,onOpenChange:b,stages:r||[]})]})})}function B1t(){const s=xa();return pt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(r)throw r;return t||[]},enabled:!!s})}function AHs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("portal_referrals").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function MHs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("portal_referrals").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const IHs=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),xje=[{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"}],PHs={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function $1t(){const{data:s=[],isLoading:t}=B1t(),r=AHs(),n=MHs(),[a,i]=k.useState("all"),[l,o]=k.useState({}),c=k.useMemo(()=>a==="all"?s:s.filter(x=>x.status===a),[s,a]),d=k.useMemo(()=>({total:s.length,new:s.filter(x=>x.status==="new").length,converted:s.filter(x=>x.status==="converted").length}),[s]),u=(x,y)=>{r.mutate({id:x.id,status:y}),he.success("Status updated")},m=x=>{const y=l[x.id];r.mutate({id:x.id,agent_notes:y}),o(_=>{const{[x.id]:b,...j}=_;return j}),he.success("Notes saved")},f=x=>{confirm(`Delete referral for ${x.friend_name}?`)&&n.mutate(x.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(Yo,{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(Di,{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"},...xje.map(x=>({v:x.value,l:x.label}))].map(x=>e.jsx("button",{onClick:()=>i(x.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===x.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:x.l},x.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(Di,{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(x=>{var j,N;const y=xje.find(C=>C.value===x.status),_=(j=x.client_portals)==null?void 0:j.slug,b=x.referrer_name||((N=x.client_portals)==null?void 0:N.client_name)||"Anonymous client";return e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:x.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(vn,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:b})," ·"," ",IHs(x.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xe,{variant:"outline",className:y==null?void 0:y.className,children:(y==null?void 0:y.label)||x.status}),e.jsxs(Ds,{value:x.status,onValueChange:C=>u(x,C),children:[e.jsx(Ps,{className:"h-8 w-[130px] text-xs",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:xje.map(C=>e.jsx(lt,{value:C.value,className:"text-xs",children:C.label},C.value))})]})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[x.friend_interest&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:PHs[x.friend_interest]||x.friend_interest}),x.friend_email&&e.jsxs("a",{href:`mailto:${x.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ks,{className:"h-3 w-3"}),x.friend_email]}),x.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${x.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Mn,{className:"h-3 w-3"}),x.friend_phone]}),e.jsxs("a",{href:`sms:${x.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(gc,{className:"h-3 w-3"}),"Text"]})]})]}),x.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:['"',x.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[x.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(pr,{value:l[x.id],onChange:C=>o(A=>({...A,[x.id]:C.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{size:"sm",onClick:()=>m(x),children:"Save"}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>o(C=>{const{[x.id]:A,...E}=C;return E}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(C=>({...C,[x.id]:x.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:x.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(un,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>f(x),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})]},x.id)})})]})}function U1t({vendor:s,onEdit:t,onDelete:r,onToggleVisible:n,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=A8.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(ke,{className:"p-4 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-muted flex items-center justify-center overflow-hidden shrink-0",children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:s.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-lg font-semibold text-muted-foreground",children:s.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:s.name}),s.is_required&&e.jsx(Gc,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(fa,{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(Xe,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(Xe,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(Xe,{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(Mn,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ks,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.website&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ql,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.website})]}),s.booking_url&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(vn,{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(Ma,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.address})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[n&&e.jsxs(q,{size:"sm",variant:a?"default":"outline",onClick:()=>n(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(Nn,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(Wf,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(q,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(iu,{className:"w-3.5 h-3.5"})}),r&&e.jsx(q,{size:"sm",variant:"ghost",onClick:r,className:"text-destructive",children:e.jsx(zr,{className:"w-3.5 h-3.5"})})]})]})}function q1t({open:s,onOpenChange:t,vendor:r,ownerType:n,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=$Wt(),[c,d]=k.useState({}),[u,m]=k.useState(!1),f=k.useRef(null),x=async b=>{if(!b.type.startsWith("image/")){he.error("Please select an image");return}if(b.size>5*1024*1024){he.error("Image must be under 5MB");return}m(!0);try{const j=b.name.split(".").pop()||"png",N=`${n}/${a||i||"misc"}/${Date.now()}.${j}`,{error:C}=await U.storage.from("vendor-logos").upload(N,b,{upsert:!0,contentType:b.type});if(C)throw C;const{data:A}=U.storage.from("vendor-logos").getPublicUrl(N);d(E=>({...E,logo_url:A.publicUrl})),he.success("Logo uploaded")}catch(j){he.error(j.message||"Upload failed")}finally{m(!1)}};k.useEffect(()=>{s&&d(r||{owner_type:n,owner_brokerage_id:n==="brokerage"&&a||null,owner_user_id:n==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,r,n,a,i]);const y=(b,j)=>d(N=>({...N,[b]:j})),_=async()=>{var b;if(!((b=c.name)!=null&&b.trim())){he.error("Name is required");return}try{await o.mutateAsync(c),he.success(r?"Vendor updated":"Vendor added"),t(!1)}catch(j){he.error(j.message||"Failed to save vendor")}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:r?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ce,{children:"Contact Name *"}),e.jsx(Ne,{value:c.name||"",onChange:b=>y("name",b.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Company"}),e.jsx(Ne,{value:c.company||"",onChange:b=>y("company",b.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Category"}),e.jsxs(Ds,{value:c.category,onValueChange:b=>y("category",b),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:A8.map(b=>e.jsx(lt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Phone"}),e.jsx(Ne,{value:c.phone||"",onChange:b=>y("phone",b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Email"}),e.jsx(Ne,{type:"email",value:c.email||"",onChange:b=>y("email",b.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Website"}),e.jsx(Ne,{value:c.website||"",onChange:b=>y("website",b.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Logo"}),e.jsx("input",{ref:f,type:"file",accept:"image/*",className:"hidden",onChange:b=>{var N;const j=(N=b.target.files)==null?void 0:N[0];j&&x(j),b.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>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($r,{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(ka,{className:"h-5 w-5"})}),e.jsxs(q,{type:"button",variant:"outline",size:"sm",onClick:()=>{var b;return(b=f.current)==null?void 0:b.click()},disabled:u,children:[u?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ka,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ce,{children:"Address"}),e.jsx(Ne,{value:c.address||"",onChange:b=>y("address",b.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{rows:3,value:c.description||"",onChange:b=>y("description",b.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Primary Action"}),e.jsxs(Ds,{value:c.action_type,onValueChange:b=>y("action_type",b),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:FWt.map(b=>e.jsx(lt,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Booking URL (Calendly etc.)"}),e.jsx(Ne,{value:c.booking_url||"",onChange:b=>y("booking_url",b.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ce,{children:"Compliance Disclosure (optional)"}),e.jsx(pr,{rows:2,value:c.disclosure_text||"",onChange:b=>y("disclosure_text",b.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(Rr,{checked:!!c.is_active,onCheckedChange:b=>y("is_active",b)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(Rr,{checked:!!c.is_featured,onCheckedChange:b=>y("is_featured",b)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(Rr,{checked:!!c.is_required,onCheckedChange:b=>y("is_required",b)})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{onClick:_,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function V1t({embedded:s=!1}={}){const t=xa(),{brokerageId:r}=Cs(),{data:n,isLoading:a}=BWt(),{data:i={}}=mlt("agent",t),l=ult(),o=UWt(),[c,d]=k.useState(null),[u,m]=k.useState(!1),[f,x]=k.useState(""),[y,_]=k.useState("all"),b=(n==null?void 0:n.vendors)||[],j=(n==null?void 0:n.selections)||[],N=k.useMemo(()=>{const B=new Map;return j.forEach(K=>B.set(K.vendor_id,K.is_visible)),B},[j]),C=k.useMemo(()=>b.filter(B=>!(y!=="all"&&B.category!==y||f&&!`${B.name} ${B.company||""}`.toLowerCase().includes(f.toLowerCase()))),[b,f,y]),A=C.filter(B=>B.owner_type==="agent"),E=C.filter(B=>B.owner_type==="brokerage"),D=async B=>{if(confirm("Delete this vendor?"))try{await l.mutateAsync(B),he.success("Vendor deleted")}catch(K){he.error(K.message)}},R=async(B,K)=>{try{await o.mutateAsync({vendorId:B,isVisible:K})}catch(Z){he.error(Z.message)}},F=B=>B.is_required?!0:N.get(B.id)??B.owner_type==="agent",O=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(bm,{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(q,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ys,{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(_n,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(Ne,{className:"pl-9",placeholder:"Search vendors...",value:f,onChange:B=>x(B.target.value)})]}),e.jsxs("select",{value:y,onChange:B=>_(B.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),A8.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(ta,{defaultValue:r?"all":"personal",children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"all",children:["All (",C.length,")"]}),r&&e.jsxs(rs,{value:"brokerage",children:["From Brokerage (",E.length,")"]}),e.jsxs(rs,{value:"personal",children:["My Personal (",A.length,")"]})]}),e.jsx(fs,{value:"all",className:"mt-4",children:e.jsx(gje,{vendors:C,isVisibleInPortals:F,onToggle:R,onEdit:B=>{d(B),m(!0)},onDelete:D,userId:t,clicks:i})}),r&&e.jsx(fs,{value:"brokerage",className:"mt-4",children:E.length===0?e.jsx(zKe,{icon:e.jsx(Ir,{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(gje,{vendors:E,isVisibleInPortals:F,onToggle:R,userId:t,clicks:i})}),e.jsx(fs,{value:"personal",className:"mt-4",children:A.length===0?e.jsx(zKe,{icon:e.jsx(bm,{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(q,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(gje,{vendors:A,isVisibleInPortals:F,onToggle:R,onEdit:B=>{d(B),m(!0)},onDelete:D,userId:t,clicks:i})})]}),e.jsx(q1t,{open:u,onOpenChange:m,vendor:c,ownerType:"agent",agentUserId:t})]});return s?O:e.jsx(ws,{children:O})}function gje({vendors:s,isVisibleInPortals:t,onToggle:r,onEdit:n,onDelete:a,userId:i,clicks:l}){return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(o=>e.jsx(U1t,{vendor:o,isVisible:t(o),onToggleVisible:c=>r(o.id,c),onEdit:o.owner_type==="agent"&&o.owner_user_id===i?()=>n==null?void 0:n(o):void 0,onDelete:o.owner_type==="agent"&&o.owner_user_id===i?()=>a==null?void 0:a(o.id):void 0,showOwnerBadge:o.owner_type,clickCount:l[o.id]},o.id))})}function zKe({icon:s,title:t,desc:r,action:n}){return e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx("div",{className:"text-muted-foreground inline-block mb-3",children:s}),e.jsx("h3",{className:"font-semibold",children:t}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-md mx-auto",children:r}),n]})}function LHs(){const{brokerageId:s,isBrokerageManager:t,isAdmin:r,loading:n}=Cs(),{data:a=[],isLoading:i}=zWt(s),{data:l={}}=mlt("brokerage",s),o=ult(),[c,d]=k.useState(null),[u,m]=k.useState(!1),[f,x]=k.useState(""),[y,_]=k.useState("all");if(n)return e.jsx(ws,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!r)return e.jsx(ws,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const b=a.filter(N=>!(y!=="all"&&N.category!==y||f&&!`${N.name} ${N.company||""}`.toLowerCase().includes(f.toLowerCase()))),j=async N=>{if(confirm("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(N),he.success("Vendor deleted")}catch(C){he.error(C.message)}};return e.jsx(ws,{children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Ga,{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(q,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ys,{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(_n,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(Ne,{className:"pl-9",placeholder:"Search vendors...",value:f,onChange:N=>x(N.target.value)})]}),e.jsxs("select",{value:y,onChange:N=>_(N.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),A8.map(N=>e.jsx("option",{value:N.value,children:N.label},N.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):b.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Ga,{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(q,{onClick:()=>{d(null),m(!0)},children:[e.jsx(Ys,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(N=>e.jsx(U1t,{vendor:N,onEdit:()=>{d(N),m(!0)},onDelete:()=>j(N.id),clickCount:l[N.id]},N.id))}),e.jsx(q1t,{open:u,onOpenChange:m,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const DHs=[{value:"overview",label:"Portals",icon:Ep},{value:"vendors",label:"Vendors",icon:j_},{value:"referrals",label:"Referrals",icon:Di},{value:"branding",label:"Branding",icon:dl},{value:"questions",label:"Onboarding",icon:l2}];function RHs(){const[s,t]=ic(),r=s.get("tab")||"overview",[n,a]=k.useState(r),[i,l]=k.useState(!1),[o,c]=k.useState(!1);return k.useEffect(()=>{t(d=>{const u=new URLSearchParams(d);return u.set("tab",n),u},{replace:!0})},[n,t]),e.jsxs(ws,{children:[e.jsx(Yo,{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(Ir,{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(i7,{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(q,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(Vn,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(ta,{value:n,onValueChange:a,className:"w-full",children:[e.jsx(ea,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:DHs.map(d=>e.jsxs(rs,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(fs,{value:"overview",className:"mt-6",children:e.jsx(F1t,{})}),e.jsx(fs,{value:"vendors",className:"mt-6",children:e.jsx(OHs,{})}),e.jsx(fs,{value:"referrals",className:"mt-6",children:e.jsx(FHs,{})}),e.jsx(fs,{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(dl,{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(q,{onClick:()=>l(!0),children:[e.jsx(Bo,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(fs,{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(l2,{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(q,{onClick:()=>c(!0),children:[e.jsx(Bo,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(O1t,{open:i,onOpenChange:l}),e.jsx(R1t,{open:o,onOpenChange:c})]})}function OHs(){return e.jsx(V1t,{embedded:!0})}function FHs(){return e.jsx($1t,{})}const q6=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function zHs(s){return pt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("client_portals").select("*").eq("id",s).maybeSingle();if(r)throw r;if(!t)return{portal:null,deal:null};const{data:n,error:a}=await U.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(n!=null&&n.contact_id){const{data:l,error:o}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",n.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:n?{deal_name:n.deal_name,contact_id:n.contact_id,contact:i}:null}},enabled:!!s})}function BHs(){const{portalId:s}=xo(),t=qr(),r=xa(),{data:n,isLoading:a}=zHs(s),{data:i=[]}=lBs(s),{data:l=[]}=B1t(),o=nD(),c=nyt(),d=ayt(),u=iyt(),[m,f]=k.useState(!1),[x,y]=k.useState(!1),[_,b]=k.useState(!1),[j,N]=k.useState(!1),C=(n==null?void 0:n.portal)??null,A=(n==null?void 0:n.deal)??null,E=k.useMemo(()=>C?l.filter(ne=>ne.portal_id===C.id):[],[l,C==null?void 0:C.id]);if(a)return e.jsx(ws,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!C)return e.jsx(ws,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx(q,{asChild:!0,variant:"outline",children:e.jsxs(Vn,{to:"/mission-control/client-portals",children:[e.jsx(Aa,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const D=R_(C.slug),R=(A==null?void 0:A.deal_name)||"Untitled deal",F=A==null?void 0:A.contact,O=F?`${F.first_name||""} ${F.last_name||""}`.trim():"",B=!!C.archived_at,K=()=>{navigator.clipboard.writeText(D),he.success("Portal link copied!")},Z=async ne=>{try{await o.mutateAsync({id:C.id,is_enabled:ne}),he.success(ne?"Portal enabled":"Portal disabled")}catch{he.error("Failed to update")}},Q=async()=>{try{await c.mutateAsync(C.id),he.success("Portal archived")}catch{he.error("Failed to archive")}},W=async()=>{try{await d.mutateAsync(C.id),he.success("Portal restored")}catch{he.error("Failed to restore")}},te=async()=>{try{await u.mutateAsync({id:C.id,dealId:C.deal_id}),he.success("Portal deleted"),t("/mission-control/client-portals")}catch{he.error("Failed to delete")}};return e.jsxs(ws,{children:[e.jsx(Yo,{children:e.jsxs("title",{children:[R," — Client Portal"]})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx(q,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(Vn,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(Aa,{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(Ir,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:R}),e.jsx(Xe,{variant:"outline",className:B?"bg-muted text-muted-foreground":C.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:B?"Archived":C.is_enabled?"Active":"Disabled"}),e.jsx(Xe,{variant:"outline",className:"capitalize text-xs",children:C.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(qi,{className:"w-3.5 h-3.5"}),C.client_name||O||"No client name set",(F==null?void 0:F.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Ks,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:F.email})]}),(F==null?void 0:F.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Mn,{className:"w-3.5 h-3.5"}),F.phone]})]}),e.jsx("div",{className:"mt-3 flex items-center gap-2 bg-background/60 border rounded-md px-3 py-1.5 max-w-full",children:e.jsx("code",{className:"text-xs font-mono text-muted-foreground truncate flex-1",children:D})})]}),!B&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(Rr,{checked:C.is_enabled,onCheckedChange:Z})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(q,{onClick:K,variant:"outline",size:"sm",children:[e.jsx(si,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(q,{onClick:()=>window.open(D,"_blank"),variant:"outline",size:"sm",children:[e.jsx(un,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(q,{onClick:()=>b(!0),size:"sm",children:[e.jsx(hn,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(q,{onClick:()=>y(!0),variant:"outline",size:"sm",children:[e.jsx(c_,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(q,{onClick:()=>f(!0),variant:"outline",size:"sm",children:[e.jsx(Bo,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[B?e.jsxs(q,{onClick:W,variant:"outline",size:"sm",children:[e.jsx(qI,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(q,{onClick:Q,variant:"ghost",size:"sm",children:[e.jsx(Qk,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(q,{onClick:()=>N(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(PV,{icon:c_,label:"Updates Posted",value:i.length}),e.jsx(PV,{icon:Di,label:"Referrals",value:E.length}),e.jsx(PV,{icon:vn,label:"Inspection",value:C.inspection_date?q6(C.inspection_date):"—"}),e.jsx(PV,{icon:vn,label:"Appraisal",value:C.appraisal_date?q6(C.appraisal_date):"—"})]}),e.jsxs(ta,{defaultValue:"updates",className:"w-full",children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(rs,{value:"referrals",children:["Referrals (",E.length,")"]}),e.jsx(rs,{value:"branding",children:"Branding"}),e.jsx(rs,{value:"details",children:"Details"})]}),e.jsx(fs,{value:"updates",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold",children:"Portal Update Feed"}),e.jsxs(q,{size:"sm",onClick:()=>y(!0),children:[e.jsx(c_,{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(c_,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No updates posted yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Keep your client in the loop — post your first update."})]}):e.jsx("div",{className:"space-y-3",children:i.map(ne=>e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium text-sm",children:ne.title}),ne.is_stage_change&&e.jsx(Xe,{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:q6(ne.created_at)}),ne.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:ne.content}),ne.video_url&&e.jsxs("a",{href:ne.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(bn,{className:"w-3 h-3"})," View video"]})]})})},ne.id))})]})})}),e.jsx(fs,{value:"referrals",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),E.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Di,{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(ne=>e.jsx(Vn,{to:"/mission-control/client-portals?tab=referrals",className:"block border rounded-lg p-3 hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:ne.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ne.friend_email||ne.friend_phone||"No contact info"," · ",q6(ne.created_at)]})]}),e.jsx(Xe,{variant:"outline",className:"text-xs capitalize",children:ne.status})]})},ne.id))})]})})}),e.jsx(fs,{value:"branding",className:"mt-4",children:e.jsx(ke,{children:e.jsx(Pe,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(dl,{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(q,{onClick:()=>f(!0),children:[e.jsx(Bo,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(fs,{value:"details",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-4",children:[e.jsx(UN,{label:"Visibility",value:C.visibility}),e.jsx(UN,{label:"Onboarding Required",value:C.require_onboarding?"Yes":"No"}),e.jsx(UN,{label:"Allow Spouse",value:C.allow_spouse?"Yes":"No"}),e.jsx(UN,{label:"Notify Client on Updates",value:C.notify_client?"Yes":"No"}),e.jsx(UN,{label:"Show Post-Close Tips",value:C.show_post_close_tips?"Yes":"No"}),e.jsx(UN,{label:"Slug",value:C.slug,mono:!0}),e.jsx(UN,{label:"Created",value:q6(C.created_at)}),e.jsx(UN,{label:"Last Updated",value:q6(C.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(q,{variant:"outline",onClick:()=>f(!0),children:[e.jsx(Bo,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(uIe,{open:m,onOpenChange:f,portal:C,dealOwnerId:r||""}),e.jsx(hIe,{open:x,onOpenChange:y,portalId:C.id,portalSlug:C.slug,notifyClient:C.notify_client}),e.jsx(mIe,{open:_,onOpenChange:b,portal:C,dealName:R}),e.jsx(el,{open:j,onOpenChange:N,children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Permanently delete this portal?"}),e.jsx(Ho,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:te,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function PV({icon:s,label:t,value:r}){return e.jsxs("div",{className:"border rounded-lg p-4 bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(s,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[11px] uppercase tracking-wide",children:t})]}),e.jsx("p",{className:"text-xl font-semibold truncate",children:r})]})}function UN({label:s,value:t,mono:r}){return e.jsxs("div",{className:"flex items-center justify-between gap-4 border-b pb-2 last:border-b-0 last:pb-0",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:s}),e.jsx("span",{className:`text-sm ${r?"font-mono text-xs":""} text-right truncate`,children:t})]})}const RCe=[{value:"video_intro",label:"Video Intro",icon:bn,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:sP,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Fh,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:Ul,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Ec,description:"Links to your social profiles"}],$Hs=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],UHs={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function H1t({cardId:s}){const{data:t,isLoading:r}=$Dt(s),n=UDt(),a=qDt(),i=VDt(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,m]=k.useState(null);if(r)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(dr,{className:"h-16 w-full"}),e.jsx(dr,{className:"h-16 w-full"})]});const f=()=>{c&&n.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:UHs[c]||{}},{onSuccess:()=>{o(!1),d("")}})},x=N=>{a.mutate({id:N.id,is_visible:!N.is_visible})},y=(N,C)=>{if(!t)return;const A=t.findIndex(R=>R.id===N.id),E=C==="up"?A-1:A+1;if(E<0||E>=t.length)return;const D=t[E];a.mutate({id:N.id,sort_order:D.sort_order}),a.mutate({id:D.id,sort_order:N.sort_order})},_=N=>{confirm("Remove this block from this card?")&&i.mutate(N.id)},b=(N,C)=>{a.mutate({id:N.id,config:C},{onSuccess:()=>m(null)})},j=N=>RCe.find(C=>C.value===N);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(q,{size:"sm",onClick:()=>o(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((N,C)=>{const A=j(N.block_type),E=(A==null?void 0:A.icon)||Fh;return e.jsx(ke,{className:N.is_visible?"":"opacity-50",children:e.jsx(Pe,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vu,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(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)||N.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:qHs(N)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(N,"up"),disabled:C===0,children:e.jsx(qu,{className:"h-3 w-3"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(N,"down"),disabled:C===t.length-1,children:e.jsx(gm,{className:"h-3 w-3"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>x(N),children:N.is_visible?e.jsx(Nn,{className:"h-3 w-3"}):e.jsx(Wf,{className:"h-3 w-3"})}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>m(N),children:"Edit"}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>_(N),children:e.jsx(zr,{className:"h-3 w-3"})})]})]})})},N.id)}),e.jsxs(q,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:RCe.map(N=>{const C=N.icon;return e.jsxs("button",{onClick:()=>d(N.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===N.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(C,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:N.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.description})]})]},N.value)})}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(q,{onClick:f,disabled:!c||n.isPending,children:"Add Block"})]})]})}),u&&e.jsx(VHs,{block:u,onSave:N=>b(u,N),onClose:()=>m(null)})]})}function qHs(s){var r;const t=s.config;switch(s.block_type){case"video_intro":return t.video_url?"Video configured":"No video set";case"testimonials":{const n=((r=t.testimonials)==null?void 0:r.length)||0;return`${n} testimonial${n!==1?"s":""}`}case"specialties":{const n=t.tags||[];return n.length?n.slice(0,3).join(", ")+(n.length>3?"...":""):"No tags"}case"custom_links":{const n=t.links||[];return`${n.length} link${n.length!==1?"s":""}`}case"social_media":{const n=t.platforms||[];return n.length?n.map(a=>a.platform).join(", "):"No platforms"}default:return""}}function VHs({block:s,onSave:t,onClose:r}){const[n,a]=k.useState(s.config),i=RCe.find(l=>l.value===s.block_type);return e.jsx(vs,{open:!0,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsxs(bs,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(HHs,{config:n,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(GHs,{config:n,onChange:a}),s.block_type==="specialties"&&e.jsx(WHs,{config:n,onChange:a}),s.block_type==="custom_links"&&e.jsx(KHs,{config:n,onChange:a}),s.block_type==="social_media"&&e.jsx(YHs,{config:n,onChange:a}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:r,children:"Cancel"}),e.jsx(q,{onClick:()=>t(n),children:"Save"})]})]})})}function HHs({config:s,onChange:t,cardId:r}){var x,y;const[n,a]=k.useState(""),[i,l]=k.useState((x=s.video_url)!=null&&x.includes("youtube")||(y=s.video_url)!=null&&y.includes("youtu.be")?"youtube":"library"),{data:o}=pt({queryKey:["card-owner",r],queryFn:async()=>{const{data:_}=await U.from("agent_cards").select("user_id").eq("id",r).single();return _==null?void 0:_.user_id},enabled:!!r}),{data:c,isLoading:d}=pt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:_,error:b}=await U.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(b)throw b;return _||[]},enabled:!!o}),u=(c==null?void 0:c.filter(_=>!n||(_.title||"").toLowerCase().includes(n.toLowerCase())))||[],m=s.bunny_video_id,f=_=>{var C;const b=(C=_.playback_url)==null?void 0:C.match(/\/(?:play|embed)\/(\d+)\//),N=`https://iframe.mediadelivery.net/embed/${b?b[1]:"570924"}/${_.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:N,bunny_video_id:_.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(ta,{value:i,onValueChange:l,children:[e.jsxs(ea,{className:"w-full",children:[e.jsx(rs,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(rs,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(fs,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search videos...",value:n,onChange:_=>a(_.target.value),className:"pl-9"})]}),e.jsx(ui,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(dr,{className:"h-14 w-full"}),e.jsx(dr,{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:()=>f(_),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${m===_.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:b=>{var j;b.currentTarget.style.display="none",(j=b.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(bn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:_.title||"Untitled Video"}),m===_.bunny_video_id&&e.jsx(la,{className:"h-4 w-4 text-primary flex-shrink-0"})]},_.id))})})]}),e.jsx(fs,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(ce,{children:"YouTube URL"}),e.jsx(Ne,{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 GHs({config:s,onChange:t}){const r=s.testimonials||[],n=(l,o,c)=>{const d=[...r];d[l]={...d[l],[o]:c},t({...s,testimonials:d})},a=()=>t({...s,testimonials:[...r,{name:"",quote:"",role:""}]}),i=l=>t({...s,testimonials:r.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-4",children:[r.map((l,o)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ce,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),r.length>1&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(zr,{className:"h-3 w-3"})})]}),e.jsx(Ne,{placeholder:"Client name",value:l.name,onChange:c=>n(o,"name",c.target.value)}),e.jsx(Ne,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>n(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>n(o,"quote",c.target.value)})]})},o)),e.jsxs(q,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function WHs({config:s,onChange:t}){const r=s.tags||[],[n,a]=k.useState(""),i=o=>{t({...s,tags:r.includes(o)?r.filter(c=>c!==o):[...r,o]})},l=()=>{n.trim()&&!r.includes(n.trim())&&(t({...s,tags:[...r,n.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:$Hs.map(o=>e.jsx("button",{onClick:()=>i(o),className:`px-3 py-1.5 text-xs rounded-full border transition-colors ${r.includes(o)?"bg-primary text-primary-foreground border-primary":"bg-muted border-border hover:bg-muted/80"}`,children:o},o))})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Add your own...",value:n,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(q,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),r.length>0&&e.jsxs("div",{children:[e.jsxs(ce,{className:"text-xs text-muted-foreground mb-1 block",children:["Selected (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-xs bg-primary/10 text-primary rounded-full",children:[o,e.jsx("button",{onClick:()=>i(o),className:"hover:text-destructive",children:"×"})]},o))})]})]})}function KHs({config:s,onChange:t}){const r=s.links||[],n=(l,o,c)=>{const d=[...r];d[l]={...d[l],[o]:c},t({...s,links:d})},a=()=>t({...s,links:[...r,{label:"",url:""}]}),i=l=>t({...s,links:r.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-3",children:[r.map((l,o)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ne,{placeholder:"Button label",value:l.label,onChange:c=>n(o,"label",c.target.value)}),e.jsx(Ne,{placeholder:"https://...",value:l.url,onChange:c=>n(o,"url",c.target.value)})]}),r.length>1&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(zr,{className:"h-3 w-3"})})]},o)),e.jsxs(q,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const BKe=[{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 YHs({config:s,onChange:t}){const r=s.platforms||[],n=c=>{r.find(d=>d.platform===c)||t({...s,platforms:[...r,{platform:c,url:""}]})},a=(c,d)=>{const u=[...r];u[c]={...u[c],url:d},t({...s,platforms:u})},i=c=>{t({...s,platforms:r.filter((d,u)=>u!==c)})},l=BKe.filter(c=>!r.find(d=>d.platform===c.value)),o=c=>{const d=YNe[c],u=BKe.find(m=>m.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:[r.length>0&&e.jsx("div",{className:"space-y-3",children:r.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(Ne,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:m=>a(d,m.target.value)})}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(ce,{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=YNe[c.value];return e.jsxs("button",{onClick:()=>n(c.value),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full border border-border bg-muted hover:bg-muted/80 transition-colors",children:[(d==null?void 0:d.icon)&&e.jsx("svg",{viewBox:"0 0 24 24",width:12,height:12,fill:d.color,children:e.jsx("path",{d:d.icon})}),c.label]},c.value)})})]}),r.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Tap a platform above to add your social media profile."})]})}var ZHs=Object.defineProperty,Vpe=Object.getOwnPropertySymbols,G1t=Object.prototype.hasOwnProperty,W1t=Object.prototype.propertyIsEnumerable,$Ke=(s,t,r)=>t in s?ZHs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,OCe=(s,t)=>{for(var r in t||(t={}))G1t.call(t,r)&&$Ke(s,r,t[r]);if(Vpe)for(var r of Vpe(t))W1t.call(t,r)&&$Ke(s,r,t[r]);return s},FCe=(s,t)=>{var r={};for(var n in s)G1t.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&Vpe)for(var n of Vpe(s))t.indexOf(n)<0&&W1t.call(s,n)&&(r[n]=s[n]);return r};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var qA;(s=>{const t=class il{constructor(c,d,u,m){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cil.MAX_VERSION)throw new RangeError("Version value out of range");if(m<-1||m>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let f=[];for(let y=0;y7)throw new RangeError("Invalid value");let y,_;for(y=u;;y++){const C=il.getNumDataCodewords(y,d)*8,A=l.getTotalBits(c,y);if(A<=C){_=A;break}if(y>=m)throw new RangeError("Data too long")}for(const C of[il.Ecc.MEDIUM,il.Ecc.QUARTILE,il.Ecc.HIGH])x&&_<=il.getNumDataCodewords(y,C)*8&&(d=C);let b=[];for(const C of c){r(C.mode.modeBits,4,b),r(C.numChars,C.mode.numCharCountBits(y),b);for(const A of C.getData())b.push(A)}a(b.length==_);const j=il.getNumDataCodewords(y,d)*8;a(b.length<=j),r(0,Math.min(4,j-b.length),b),r(0,(8-b.length%8)%8,b),a(b.length%8==0);for(let C=236;b.lengthN[A>>>3]|=C<<7-(A&7)),new il(y,d,N,f)}getModule(c,d){return 0<=c&&c>>9)*1335;const m=(d<<10|u)^21522;a(m>>>15==0);for(let f=0;f<=5;f++)this.setFunctionModule(8,f,n(m,f));this.setFunctionModule(8,7,n(m,6)),this.setFunctionModule(8,8,n(m,7)),this.setFunctionModule(7,8,n(m,8));for(let f=9;f<15;f++)this.setFunctionModule(14-f,8,n(m,f));for(let f=0;f<8;f++)this.setFunctionModule(this.size-1-f,8,n(m,f));for(let f=8;f<15;f++)this.setFunctionModule(8,this.size-15+f,n(m,f));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 m=n(d,u),f=this.size-11+u%3,x=Math.floor(u/3);this.setFunctionModule(f,x,m),this.setFunctionModule(x,f,m)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let m=-4;m<=4;m++){const f=Math.max(Math.abs(m),Math.abs(u)),x=c+m,y=d+u;0<=x&&x{(C!=_-f||E>=y)&&N.push(A[C])});return a(N.length==x),N}drawCodewords(c){if(c.length!=Math.floor(il.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 m=0;m>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(y,_),x||(c+=this.finderPenaltyCountPatterns(_)*il.PENALTY_N3),x=this.modules[f][b],y=1);c+=this.finderPenaltyTerminateAndCount(x,y,_)*il.PENALTY_N3}for(let f=0;f5&&c++):(this.finderPenaltyAddHistory(y,_),x||(c+=this.finderPenaltyCountPatterns(_)*il.PENALTY_N3),x=this.modules[b][f],y=1);c+=this.finderPenaltyTerminateAndCount(x,y,_)*il.PENALTY_N3}for(let f=0;fx+(y?1:0),d);const u=this.size*this.size,m=Math.ceil(Math.abs(d*20-u*10)/u)-1;return a(0<=m&&m<=9),c+=m*il.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 m=this.size-7;u.lengthil.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(il.getNumRawDataModules(c)/8)-il.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*il.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let m=0;m0);for(const m of c){const f=m^u.shift();u.push(0),d.forEach((x,y)=>u[y]^=il.reedSolomonMultiply(x,f))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let m=7;m>=0;m--)u=u<<1^(u>>>7)*285,u^=(d>>>m&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 r(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 n(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class Iu{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)r(u,8,d);return new Iu(Iu.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!Iu.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let u=0;u=1<{(t=>{const r=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};r.LOW=new r(0,1),r.MEDIUM=new r(1,0),r.QUARTILE=new r(2,3),r.HIGH=new r(3,2),t.Ecc=r})(s.QrCode||(s.QrCode={}))})(qA||(qA={}));(s=>{(t=>{const r=class{constructor(a,i){this.modeBits=a,this.numBitsCharCount=i}numCharCountBits(a){return this.numBitsCharCount[Math.floor((a+7)/17)]}};r.NUMERIC=new r(1,[10,12,14]),r.ALPHANUMERIC=new r(2,[9,11,13]),r.BYTE=new r(4,[8,16,16]),r.KANJI=new r(8,[8,10,12]),r.ECI=new r(7,[0,0,0]),t.Mode=r})(s.QrSegment||(s.QrSegment={}))})(qA||(qA={}));var LI=qA;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var XHs={L:LI.QrCode.Ecc.LOW,M:LI.QrCode.Ecc.MEDIUM,Q:LI.QrCode.Ecc.QUARTILE,H:LI.QrCode.Ecc.HIGH},K1t=128,Y1t="L",Z1t="#FFFFFF",X1t="#000000",Q1t=!1,J1t=1,QHs=4,JHs=0,eGs=.1;function ebt(s,t=0){const r=[];return s.forEach(function(n,a){let i=null;n.forEach(function(l,o){if(!l&&i!==null){r.push(`M${i+t} ${a+t}h${o-i}v1H${i+t}z`),i=null;return}if(o===n.length-1){if(!l)return;i===null?r.push(`M${o+t},${a+t} h1v1H${o+t}z`):r.push(`M${i+t},${a+t} h${o+1-i}v1H${i+t}z`);return}l&&i===null&&(i=o)})}),r.join("")}function tbt(s,t){return s.slice().map((r,n)=>n=t.y+t.h?r:r.map((a,i)=>i=t.x+t.w?a:!1))}function tGs(s,t,r,n){if(n==null)return null;const a=s.length+r*2,i=Math.floor(t*eGs),l=a/t,o=(n.width||i)*l,c=(n.height||i)*l,d=n.x==null?s.length/2-o/2:n.x*l,u=n.y==null?s.length/2-c/2:n.y*l,m=n.opacity==null?1:n.opacity;let f=null;if(n.excavate){let y=Math.floor(d),_=Math.floor(u),b=Math.ceil(o+d-y),j=Math.ceil(c+u-_);f={x:y,y:_,w:b,h:j}}const x=n.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:f,opacity:m,crossOrigin:x}}function sGs(s,t){return t!=null?Math.max(Math.floor(t),0):s?QHs:JHs}function sbt({value:s,level:t,minVersion:r,includeMargin:n,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Ct.useMemo(()=>{const y=(Array.isArray(s)?s:[s]).reduce((_,b)=>(_.push(...LI.QrSegment.makeSegments(b)),_),[]);return LI.QrCode.encodeSegments(y,XHs[t],r,void 0,void 0,o)},[s,t,r,o]);const{cells:d,margin:u,numCells:m,calculatedImageSettings:f}=Ct.useMemo(()=>{let x=c.getModules();const y=sGs(n,a),_=x.length+y*2,b=tGs(x,l,y,i);return{cells:x,margin:y,numCells:_,calculatedImageSettings:b}},[c,l,i,n,a]);return{qrcode:c,margin:u,cells:d,numCells:m,calculatedImageSettings:f}}var rGs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),nGs=Ct.forwardRef(function(t,r){const n=t,{value:a,size:i=K1t,level:l=Y1t,bgColor:o=Z1t,fgColor:c=X1t,includeMargin:d=Q1t,minVersion:u=J1t,boostLevel:m,marginSize:f,imageSettings:x}=n,_=FCe(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:b}=_,j=FCe(_,["style"]),N=x==null?void 0:x.src,C=Ct.useRef(null),A=Ct.useRef(null),E=Ct.useCallback(W=>{C.current=W,typeof r=="function"?r(W):r&&(r.current=W)},[r]),[D,R]=Ct.useState(!1),{margin:F,cells:O,numCells:B,calculatedImageSettings:K}=sbt({value:a,level:l,minVersion:u,boostLevel:m,includeMargin:d,marginSize:f,imageSettings:x,size:i});Ct.useEffect(()=>{if(C.current!=null){const W=C.current,te=W.getContext("2d");if(!te)return;let ne=O;const ae=A.current,ue=K!=null&&ae!==null&&ae.complete&&ae.naturalHeight!==0&&ae.naturalWidth!==0;ue&&K.excavation!=null&&(ne=tbt(O,K.excavation));const me=window.devicePixelRatio||1;W.height=W.width=i*me;const de=i/B*me;te.scale(de,de),te.fillStyle=o,te.fillRect(0,0,B,B),te.fillStyle=c,rGs?te.fill(new Path2D(ebt(ne,F))):O.forEach(function(fe,je){fe.forEach(function(xe,Ee){xe&&te.fillRect(Ee+F,je+F,1,1)})}),K&&(te.globalAlpha=K.opacity),ue&&te.drawImage(ae,K.x+F,K.y+F,K.w,K.h)}}),Ct.useEffect(()=>{R(!1)},[N]);const Z=OCe({height:i,width:i},b);let Q=null;return N!=null&&(Q=Ct.createElement("img",{src:N,key:N,style:{display:"none"},onLoad:()=>{R(!0)},ref:A,crossOrigin:K==null?void 0:K.crossOrigin})),Ct.createElement(Ct.Fragment,null,Ct.createElement("canvas",OCe({style:Z,height:i,width:i,ref:E,role:"img"},j)),Q)});nGs.displayName="QRCodeCanvas";var d$=Ct.forwardRef(function(t,r){const n=t,{value:a,size:i=K1t,level:l=Y1t,bgColor:o=Z1t,fgColor:c=X1t,includeMargin:d=Q1t,minVersion:u=J1t,boostLevel:m,title:f,marginSize:x,imageSettings:y}=n,_=FCe(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:b,cells:j,numCells:N,calculatedImageSettings:C}=sbt({value:a,level:l,minVersion:u,boostLevel:m,includeMargin:d,marginSize:x,imageSettings:y,size:i});let A=j,E=null;y!=null&&C!=null&&(C.excavation!=null&&(A=tbt(j,C.excavation)),E=Ct.createElement("image",{href:y.src,height:C.h,width:C.w,x:C.x+b,y:C.y+b,preserveAspectRatio:"none",opacity:C.opacity,crossOrigin:C.crossOrigin}));const D=ebt(A,b);return Ct.createElement("svg",OCe({height:i,width:i,viewBox:`0 0 ${N} ${N}`,ref:r,role:"img"},_),!!f&&Ct.createElement("title",null,f),Ct.createElement("path",{fill:o,d:`M0,0 h${N}v${N}H0z`,shapeRendering:"crispEdges"}),Ct.createElement("path",{fill:c,d:D,shapeRendering:"crispEdges"}),E)});d$.displayName="QRCodeSVG";function aGs({slug:s,agentName:t}){const r=k.useRef(null),n=`https://cards.relevelup.com/${s}`,a=k.useCallback(()=>{var m;const i=(m=r.current)==null?void 0:m.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const f=document.createElement("a");f.download=`${s}-qr-code.png`,f.href=l.toDataURL("image/png"),f.click(),he.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(ce,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:r,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(d$,{value:n,size:120,level:"H",bgColor:"#ffffff",fgColor:"#000000"})}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Download this QR code to use on business cards, flyers, signs, or any print materials. Scanning it opens your digital card instantly."}),e.jsxs(q,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(li,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function yje(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 iGs(){const{user:s}=Cs(),{data:t,isLoading:r}=FDt(s==null?void 0:s.id),n=rD(),[a,i]=k.useState(null),l=k.useMemo(()=>a||(t?yje(t):null),[a,t]);if(r)return e.jsx(ws,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(dr,{className:"h-8 w-48"}),e.jsx(dr,{className:"h-32 w-full"}),e.jsx(dr,{className:"h-32 w-full"})]})});if(!t)return e.jsx(ws,{children:e.jsx(lGs,{userId:s==null?void 0:s.id})});const o=l||yje(t),c=d=>{i(u=>{const m=u||yje(t);return typeof d=="function"?d(m):d})};return e.jsx(ws,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${n?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(cGs,{card:t}),e.jsx(mGs,{card:t,form:o,setForm:c})]}),!n&&e.jsx("div",{className:"w-[400px] shrink-0","aria-hidden":"true"}),!n&&e.jsx("div",{className:"fixed right-8 top-[5.5rem] w-[400px] z-30",style:{height:"calc(100vh - 6.5rem)"},children:e.jsxs("div",{className:"rounded-xl border bg-muted/30 overflow-hidden h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 border-b bg-card shrink-0",children:[e.jsx(k_,{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(oGs,{card:t,form:o})})]})})]})})}function oGs({card:s,form:t}){const{data:r}=pt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await U.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),n=k.useMemo(()=>({...s,is_published:t.is_published,theme:t.theme,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,custom_cta_url:s.custom_cta_url,show_photo:t.show_photo,show_bio:t.show_bio,show_video:s.show_video,show_credentials:t.show_credentials,show_social_links:t.show_social_links,show_save_contact:t.show_save_contact,show_leave_review:t.show_leave_review,show_refer_friend:t.show_refer_friend,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,display_email:t.display_email||null,social_links:s.social_links||[],profile:{name:(r==null?void 0:r.name)||null,email:t.display_email||(r==null?void 0:r.email)||null,phone:(r==null?void 0:r.phone)||null,brokerage_id:(r==null?void 0:r.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(r==null?void 0:r.avatar_url)||null}),[s,t,r]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(rTe,{card:n})})}function lGs({userId:s}){var c;const[t,r]=k.useState(""),n=Knt(),{data:a}=pt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await U.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){he.error("Please enter a URL slug for your card");return}n.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>he.success("Your digital card has been created!")})},o=[{icon:Ql,title:"Shareable Link",desc:"One link that works everywhere"},{icon:zh,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Oh,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:dl,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(Ir,{className:"h-3.5 w-3.5"}),"New Feature"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3 tracking-tight",children:"Your Digital Business Card"}),e.jsx("p",{className:"text-primary-foreground/80 text-lg max-w-md leading-relaxed",children:"Ditch the paper. Share a beautiful, interactive card that captures leads and makes a lasting impression."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-8",children:o.map(d=>e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl border bg-card hover:shadow-md transition-shadow",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(d.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.desc})]})]},d.title))}),e.jsxs(ke,{className:"shadow-lg border-2",children:[e.jsxs(Pt,{className:"text-center pb-2",children:[e.jsx(Dt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Ur,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Pe,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Your Card URL"}),e.jsxs("div",{className:"flex items-center gap-0 mt-1.5",children:[e.jsx("span",{className:"inline-flex items-center px-3 h-10 rounded-l-md border border-r-0 bg-muted text-sm text-muted-foreground whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(Ne,{value:t||i,onChange:d=>r(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(q,{onClick:l,disabled:n.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),n.isPending?"Creating...":"Create My Card"]})]})]})]})}function cGs({card:s}){const r=`https://cards.relevelup.com/${s.slug}`,n=()=>{navigator.clipboard.writeText(r),he.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(Xe,{variant:s.is_published?"default":"secondary",className:"text-[10px] uppercase tracking-wider",children:s.is_published?"Live":"Draft"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[e.jsx(si,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(q,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function dGs({userId:s}){const t=is(),r=k.useRef(null),[n,a]=k.useState(!1),[i,l]=k.useState(""),{data:o,isLoading:c}=pt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:K}=await U.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let Z=(K==null?void 0:K.avatar_url)||null;if(!Z){const{data:Q}=await U.storage.from("avatars").list(`${s}`);if(Q&&Q.length>0){const{data:W}=U.storage.from("avatars").getPublicUrl(`${s}/${Q[0].name}`);Z=`${W.publicUrl}?t=${Date.now()}`,await U.from("profiles").update({avatar_url:Z}).eq("id",s)}}return{...K,avatar_url:Z}}}),[d,u]=k.useState(null),[m,f]=k.useState(null),[x,y]=k.useState(null),[_,b]=k.useState(!1),j=d??(o==null?void 0:o.name)??"",N=m??(o==null?void 0:o.phone)??"",C=x??(o==null?void 0:o.email)??"",A=o==null?void 0:o.avatar_url,E=((o==null?void 0:o.name)||"A").split(" ").map(K=>K[0]).join("").toUpperCase().slice(0,2),D=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),R=Mt({mutationFn:async K=>{const{error:Z}=await U.from("profiles").update(K).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"]}),he.success("Profile updated!")},onError:()=>he.error("Failed to update profile")}),F=()=>{const K={};if(d!==null&&d!==(o==null?void 0:o.name)&&(K.name=d),m!==null&&m!==(o==null?void 0:o.phone)&&(K.phone=m||null),x!==null&&x!==(o==null?void 0:o.email)&&(K.email=x),Object.keys(K).length===0){he.info("No changes to save");return}R.mutate(K)},O=K=>{var W;const Z=(W=K.target.files)==null?void 0:W[0];if(!Z)return;if(!Z.type.startsWith("image/")){he.error("Please select an image file");return}const Q=new FileReader;Q.onloadend=()=>{l(Q.result),a(!0)},Q.readAsDataURL(Z),K.target.value=""},B=async K=>{b(!0);try{const{data:Z}=await U.storage.from("avatars").list(`${s}`);Z&&Z.length>0&&await U.storage.from("avatars").remove(Z.map(ae=>`${s}/${ae.name}`));const Q=`${s}/avatar.jpg`,{error:W}=await U.storage.from("avatars").upload(Q,K,{upsert:!0,contentType:"image/jpeg"});if(W)throw W;const{data:te}=U.storage.from("avatars").getPublicUrl(Q),ne=te.publicUrl+"?t="+Date.now();await U.from("profiles").update({avatar_url:ne}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),he.success("Photo updated!")}catch{he.error("Failed to upload photo")}finally{b(!1)}};return c?e.jsx(dr,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:D?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Pe,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ce,{className:"text-sm font-semibold",children:"Profile Info"}),D&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(go,{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 K;return(K=r.current)==null?void 0:K.click()},children:[e.jsxs(Wn,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(Xa,{src:A||void 0,alt:j}),e.jsx(Kn,{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(Tp,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:O})]}),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(ce,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(Ne,{value:j,onChange:K=>u(K.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(ce,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(Ne,{value:N,onChange:K=>f(K.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(Ne,{value:C,onChange:K=>y(K.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(q,{variant:"outline",size:"sm",onClick:F,disabled:R.isPending,className:"w-full",children:R.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(fAe,{open:n,onClose:()=>a(!1),imageSrc:i,onCropComplete:B,aspectRatio:1})]})}function uGs({form:s,setForm:t,userId:r}){const[n,a]=k.useState(null),[i,l]=k.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=k.useState(s.team_logo_url?"logo":"name"),d=x=>{l(x),t(x==="name"?y=>({...y,brokerage_logo_url:""}):y=>({...y,brokerage_display_name:""}))},u=x=>{c(x),t(x==="name"?y=>({...y,team_logo_url:""}):y=>({...y,team_name:""}))},m=async(x,y)=>{var b;const _=(b=x.target.files)==null?void 0:b[0];if(_){if(!_.type.startsWith("image/")){he.error("Please select an image file");return}a(y);try{const j=_.name.split(".").pop()||"png",C=`${r}/${y==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${j}`,{error:A}=await U.storage.from("card-logos").upload(C,_,{upsert:!0});if(A)throw A;const{data:E}=U.storage.from("card-logos").getPublicUrl(C),D=E.publicUrl+"?t="+Date.now();t(y==="brokerage_logo_url"?R=>({...R,[y]:D,brokerage_display_name:""}):R=>({...R,[y]:D,team_name:""})),he.success("Logo uploaded!")}catch{he.error("Failed to upload logo")}finally{a(null),x.target.value=""}}},f=x=>{t(y=>({...y,[x]:""}))};return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ce,{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(ce,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(q,{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(ce,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(Ne,{value:s.brokerage_display_name,onChange:x=>t(y=>({...y,brokerage_display_name:x.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{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:()=>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:"×"})]}):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(Tp,{className:"h-3.5 w-3.5"}),n==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x=>m(x,"brokerage_logo_url"),disabled:n!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{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(nf,{value:[s.brokerage_logo_size||56],onValueChange:([x])=>t(y=>({...y,brokerage_logo_size:x})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ce,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx(q,{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(ce,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(Ne,{value:s.team_name,onChange:x=>t(y=>({...y,team_name:x.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{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:()=>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:"×"})]}):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(Tp,{className:"h-3.5 w-3.5"}),n==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x=>m(x,"team_logo_url"),disabled:n!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{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(nf,{value:[s.team_logo_size||56],onValueChange:([x])=>t(y=>({...y,team_logo_size:x})),min:24,max:120,step:4})]})]})]})]})})}function hGs({form:s,setForm:t}){const r={accent:"#ff5722",dark:"#1a1a2e",button:"#ff5722"},n=s.bold_theme_colors||r,a=(o,c)=>{t(d=>({...d,bold_theme_colors:{...r,...d.bold_theme_colors,[o]:c}}))},i=()=>{t(o=>({...o,bold_theme_colors:null}))},l=[{key:"accent",label:"Accent Color",desc:"Page background, icons, highlights"},{key:"dark",label:"Dark Color",desc:"Header background, action buttons, social icons"},{key:"button",label:"CTA Button Color",desc:"Main call-to-action button"}];return e.jsxs("div",{className:"space-y-3 p-4 rounded-xl border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ce,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(dl,{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(q,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:i,children:"Reset to Default"})]}),e.jsx("div",{className:"grid gap-3",children:l.map(({key:o,label:c,desc:d})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"relative shrink-0",children:[e.jsx("input",{type:"color",value:n[o],onChange: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:n[o]}})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsx(Ne,{value:n[o],onChange:u=>{const m=u.target.value;/^#[0-9a-fA-F]{0,6}$/.test(m)&&a(o,m)},className:"w-24 h-8 text-xs font-mono",placeholder:"#ff5722"})]},o))}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Preview:"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.accent}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.dark}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.button}})]})]})]})}function mGs({card:s,form:t,setForm:r}){var _;const n=Ynt(),a=is(),{data:i}=Znt(s.id),[l,o]=k.useState(s.slug),[c,d]=k.useState(!1),[u,m]=k.useState("idle"),f=k.useRef(JSON.stringify(t)),x=k.useRef(null);k.useEffect(()=>{const b=JSON.stringify(t);if(b!==f.current)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{m("saving"),n.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{f.current=b,m("saved"),setTimeout(()=>m("idle"),2e3)},onError:()=>m("idle")})},1500),()=>{x.current&&clearTimeout(x.current)}},[t]);const y=async()=>{const b=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!b){he.error("Please enter a valid URL");return}if(b===s.slug){he.info("No changes to save");return}d(!0);try{const{data:j}=await U.from("agent_cards").select("id").eq("slug",b).neq("id",s.id).maybeSingle();if(j){he.error("This URL is already taken. Try another one.");return}const{error:N}=await U.from("agent_cards").update({slug:b}).eq("id",s.id);if(N)throw N;o(b),a.invalidateQueries({queryKey:["agent-card"]}),he.success("Card address updated!")}catch{he.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ta,{defaultValue:"content",children:[e.jsxs(ea,{className:"w-full h-11 p-1",children:[e.jsxs(rs,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(S0,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(rs,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(rs,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(zh,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(rs,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(S_,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(rs,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Bc,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(fs,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(dGs,{userId:s.user_id}),e.jsx(uGs,{form:t,setForm:r,userId:s.user_id}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{checked:t.is_published,onCheckedChange:b=>r(j=>({...j,is_published:b}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(Ne,{value:l,onChange:b=>o(b.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx(q,{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(ce,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(Ne,{value:t.display_email,onChange:b=>r(j=>({...j,display_email:b.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(Ds,{value:t.theme,onValueChange:b=>r(j=>({...j,theme:b})),children:[e.jsx(Ps,{className:"h-11",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(lt,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(lt,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(lt,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(hGs,{form:t,setForm:r}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(Ne,{value:t.title,onChange:b=>r(j=>({...j,title:b.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(Ne,{value:t.positioning_statement,onChange:b=>r(j=>({...j,positioning_statement:b.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Bio"}),e.jsx(pr,{value:t.bio,onChange:b=>r(j=>({...j,bio:b.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(Ne,{value:t.review_snippet,onChange:b=>r(j=>({...j,review_snippet:b.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(Ne,{value:t.review_source_url,onChange:b=>r(j=>({...j,review_source_url:b.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(Ne,{value:t.booking_url,onChange:b=>r(j=>({...j,booking_url:b.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(Ne,{value:t.custom_cta_label,onChange:b=>r(j=>({...j,custom_cta_label:b.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(fs,{value:"sections",className:"mt-4",children:e.jsx(ke,{children:e.jsx(Pe,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:b,label:j,desc:N})=>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(ce,{className:"text-sm font-medium",children:j}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N})]}),e.jsx(Rr,{checked:t[b],onCheckedChange:C=>r(A=>({...A,[b]:C}))})]},b))})})}),e.jsx(fs,{value:"blocks",className:"mt-4",children:e.jsx(H1t,{cardId:s.id})}),e.jsx(fs,{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:Nn,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:Bc,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:xl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(b=>e.jsx(ke,{className:"overflow-hidden",children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`p-1.5 rounded-md ${b.color}`,children:e.jsx(b.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:b.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:b.value})]})},b.label))}),i&&i.leads.length>0&&e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsx(Dt,{className:"text-base",children:"Recent Leads"})}),e.jsx(Pe,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(b=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:b.name}),b.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:b.phone})]}),b.intent&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:b.intent})]},b.id))})]}),(!i||i.leads.length===0)&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-8 text-center",children:[e.jsx(Bc,{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(fs,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(ke,{children:e.jsx(Pe,{className:"p-6",children:e.jsx(aGs,{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 fGs(){const s=is(),[t,r]=k.useState(""),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState(!1),[m,f]=k.useState(!1),[x,y]=k.useState(null),[_,b]=k.useState(null),[j,N]=k.useState(0),[C,A]=k.useState(""),[E,D]=k.useState(!1),{data:R,isLoading:F}=pt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:me,error:de}=await U.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(de)throw de;return me}}),O=Mt({mutationFn:async me=>{const{data:de,error:fe}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:me}});if(fe)throw fe;if(de!=null&&de.error)throw new Error(de.error);return de},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),r(""),he.success("BoldTrail connected successfully!")},onError:me=>{he.error(me.message||"Failed to connect BoldTrail")}}),B=Mt({mutationFn:async()=>{const{data:me,error:de}=await U.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(de)throw de;return me},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),he.success("BoldTrail disconnected")},onError:()=>he.error("Failed to disconnect")}),K=Mt({mutationFn:async me=>{const{data:de,error:fe}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:me}});if(fe)throw fe;if(de!=null&&de.error)throw new Error(de.error);return de},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),he.success("Sync direction saved")},onError:me=>{he.error(me.message||"Failed to save sync direction")}}),Z=Mt({mutationFn:async()=>{const{data:me,error:de}=await U.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(de)throw de;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:me=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),me.kvcore_user_id){const de=me.detected_name||me.detected_email||`ID ${me.kvcore_user_id}`;he.success(`Detected your BoldTrail account: ${de}`)}else if(me.candidates&&me.candidates.length>0){const de=me.candidates.slice(0,5).map(fe=>`${fe.id} (${fe.count} contacts)`).join(", ");he.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${de}. Pick yours and enter it below.`,{duration:12e3}),D(!0)}else he.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),D(!0)},onError:me=>he.error(me.message||"Detection failed")}),Q=Mt({mutationFn:async me=>{const{data:de,error:fe}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...me}});if(fe)throw fe;if(de!=null&&de.error)throw new Error(de.error);return de},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),he.success("Settings saved"),D(!1)},onError:me=>he.error(me.message||"Failed to save settings")}),W=Mt({mutationFn:async()=>{const{data:me,error:de}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(de)throw de;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:me=>{y(null),c(me),a(!0)},onError:me=>{he.error(me.message||"Failed to generate sync preview")}}),te=Mt({mutationFn:async()=>{b("Initializing sync..."),N(5);const{data:me,error:de}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ue}});if(de)throw de;if(me!=null&&me.error)throw new Error(me.error);const fe=me;let je=fe.sync_log_id,xe=fe.next_phase,Ee=fe.next_offset,Me=fe.push_total||0,Oe=fe.pull_total||0,Ie=0,ze=0;for(;xe!=="finalize";){const $e=Me+Oe;xe==="fetch_bt"?b("Fetching BoldTrail contacts..."):xe==="analyze"?(b("Analyzing contacts..."),N(15)):xe==="push"?(b(`Pushing contacts to BoldTrail... (${Ie}/${Me})`),N($e>0?Ie/$e*100:0)):xe==="pull"&&(b(`Pulling contacts from BoldTrail... (${ze}/${Oe})`),N($e>0?(Me+ze)/$e*100:0));const{data:ve,error:Qe}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:xe,offset:Ee,sync_log_id:je,sync_direction:ue}});if(Qe)throw Qe;if(ve!=null&&ve.error)throw new Error(ve.error);const we=ve;Ie+=we.chunk_pushed||0,ze+=we.chunk_pulled||0,we.push_total!==void 0&&(Me=we.push_total||0),we.pull_total!==void 0&&(Oe=we.pull_total||0),we.progress&&b(we.progress),xe==="pull"&&Oe>0?N(Math.min(95,ze/Oe*100)):xe==="push"&&Me>0&&N(Math.min(95,Ie/Me*100)),xe=we.next_phase,Ee=we.next_offset}b("Finalizing sync..."),N(95);const{data:Ve,error:Le}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:je,sync_direction:ue}});if(Le)throw Le;return N(100),Ve},onSuccess:me=>{b(null),N(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"]}),he.success(`Sync complete! Pushed ${me.contacts_pushed||0}, pulled ${me.contacts_pulled||0}, skipped ${me.contacts_skipped||0} duplicates.`)},onError:me=>{b(null),N(0),he.error(me.message||"Sync failed")}}),ne=R==null?void 0:R.connected,ae=(R==null?void 0:R.sync_direction)||"bidirectional",ue=x??ae;return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Pt,{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(Uu,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",ne&&e.jsx(Xe,{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(Ff,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Ur,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Ti,{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(Ti,{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(Ti,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Syncs name, email, phone, address, notes, and lead source"})]}),ne?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(R==null?void 0:R.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(R.last_sync_at).toLocaleString(),R.last_sync_status&&e.jsx(Xe,{variant:R.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:R.last_sync_status})]}),(R==null?void 0:R.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[R.boldtrail_contact_count," contacts in BoldTrail"]}),(R==null?void 0:R.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:R.last_sync_message})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect BoldTrail?"}),e.jsx(Ho,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>B.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(M1,{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(Rr,{checked:!!(R!=null&&R.sync_only_owned),onCheckedChange:me=>Q.mutate({sync_only_owned:me}),disabled:Q.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs",children:"Your BoldTrail Agent ID"}),E?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"number",placeholder:"e.g. 12345",value:C,onChange:me=>A(me.target.value),className:"h-8 text-sm"}),e.jsx(q,{size:"sm",onClick:()=>{const me=C.trim()===""?null:Number(C);Q.mutate({kvcore_user_id:me})},disabled:Q.isPending,children:"Save"}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>D(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(R==null?void 0:R.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>Z.mutate(),disabled:Z.isPending,children:[Z.isPending?e.jsx(lo,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>{var me;A(((me=R==null?void 0:R.kvcore_user_id)==null?void 0:me.toString())??""),D(!0)},children:"Edit"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Your numeric BoldTrail (kvCORE) user ID. To find it: log into BoldTrail → click your avatar (top right) → ",e.jsx("strong",{children:"My Profile"}),". The ID appears in the page URL after ",e.jsx("code",{children:"/users/"})," (e.g. ",e.jsxs("code",{children:[".../users/",e.jsx("strong",{children:"12345"})]}),"). You can also open any contact you own in BoldTrail and look at the URL — your ID is shown as the assigned agent. Auto-detect tries to find it via your API token first."]})]})]}),e.jsx("div",{className:"rounded-lg border p-3",children:e.jsx(uCe,{value:ae,onChange:me=>K.mutate(me)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(q,{onClick:()=>W.mutate(),disabled:W.isPending||te.isPending,variant:"outline",className:"gap-2",children:[W.isPending?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4"}),"Preview Sync"]})})]}):e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:me=>r(me.target.value),className:"flex-1"}),e.jsxs(q,{onClick:()=>O.mutate(t),disabled:!t||t.length<10||O.isPending,children:[O.isPending?e.jsx(lo,{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(vs,{open:n,onOpenChange:me=>{te.isPending||a(me)},children:e.jsxs(ys,{className:"sm:max-w-lg",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Uu,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(an,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const me=ue==="pull_only"?0:o.to_push,de=ue==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(uCe,{value:ue,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(M1,{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 ${ue==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:me}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(qu,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${ue==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:de}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(gm,{className:"h-3 w-3"})," 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(Dr,{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"]}),te.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(ki,{value:j||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:_||"Sync in progress..."})]}),me>0&&e.jsxs(E0,{open:d,onOpenChange:u,children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qu,{className:"h-3 w-3 text-emerald-600"}),me," contacts to push to BoldTrail"]}),e.jsx(Co,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(M0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((fe,je)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:fe.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:fe.email})]},je)),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"]})]})})]}),de>0&&e.jsxs(E0,{open:m,onOpenChange:f,children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gm,{className:"h-3 w-3 text-blue-600"}),de," contacts to pull from BoldTrail"]}),e.jsx(Co,{className:`h-3 w-3 transition-transform ${m?"rotate-180":""}`})]})}),e.jsx(M0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((fe,je)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:fe.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:fe.email})]},je)),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"]})]})})]}),me===0&&de===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(q,{variant:"outline",onClick:()=>a(!1),disabled:te.isPending,children:"Cancel"}),e.jsxs(q,{onClick:()=>te.mutate(),disabled:te.isPending||me===0&&de===0,className:"gap-2",children:[te.isPending?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Uu,{className:"h-4 w-4"}),te.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(_s,{className:"p-6 pb-0",children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Uu,{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 pGs(){const s=is(),[t,r]=k.useState(""),[n,a]=k.useState(!1),[i,l]=k.useState(0),[o,c]=k.useState(null),{data:d,isLoading:u}=pt({queryKey:["fub-status"],queryFn:async()=>{const{data:_,error:b}=await U.functions.invoke("followupboss-sync",{body:{action:"status"}});if(b)throw b;return _}}),m=Mt({mutationFn:async _=>{const{data:b,error:j}=await U.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:_}});if(j)throw j;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{he.success("Connected to Follow Up Boss"),r(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:_=>he.error(_.message)}),f=Mt({mutationFn:async()=>{const{error:_}=await U.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(_)throw _},onSuccess:()=>{he.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),x=Mt({mutationFn:async _=>{const{error:b}=await U.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:_}});if(b)throw b},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),y=async()=>{a(!0),l(0),c("Pulling from FUB…");let _=0,b=0,j=0,N=0;try{for(;;){const{data:D,error:R}=await U.functions.invoke("followupboss-sync",{body:{action:"sync",offset:_}});if(R)throw R;if(D!=null&&D.error)throw new Error(D.error);b+=D.chunk_created||0,j+=D.chunk_updated||0,N+=D.chunk_skipped||0,_=D.next_offset;const F=D.total?Math.min(100,Math.round(_/D.total*100)):100;if(l(F),c(`Pulling · ${_} / ${D.total||"?"}`),D.done)break;await new Promise(O=>setTimeout(O,400))}let C=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let D=0;for(l(0),c("Pushing to FUB…");;){const{data:R,error:F}=await U.functions.invoke("followupboss-sync",{body:{action:"push",offset:D}});if(F)throw F;if(R!=null&&R.error)throw new Error(R.error);C+=R.chunk_pushed||0,A+=R.chunk_failed||0,D=R.next_offset;const O=R.total?Math.min(100,Math.round(D/R.total*100)):100;if(l(O),c(`Pushing · ${D} / ${R.total||"?"}`),R.done)break;await new Promise(B=>setTimeout(B,400))}}const E=C||A?` · pushed ${C}${A?`, ${A} failed`:""}`:"";he.success(`Sync complete · ${b} new, ${j} updated${N?`, ${N} skipped`:""}${E}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(C){he.error(C.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(d2,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(Xe,{variant:"default",className:"ml-1",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Ur,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Pe,{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(Rr,{checked:d.sync_direction==="bidirectional",onCheckedChange:_=>x.mutate(_?"bidirectional":"pull_only"),disabled:n||x.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ki,{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(q,{onClick:y,disabled:n,children:[e.jsx(lo,{className:`h-4 w-4 mr-2 ${n?"animate-spin":""}`}),n?"Syncing…":"Sync Now"]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsxs(q,{variant:"outline",disabled:n,children:[e.jsx(zr,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Follow Up Boss?"}),e.jsx(Ho,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>f.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(Ne,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:_=>r(_.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(un,{className:"h-3 w-3"})]})]})]}),e.jsx(q,{onClick:()=>m.mutate(t),disabled:!t.trim()||m.isPending,children:m.isPending?"Connecting…":"Connect"})]})})]})}function xGs(){var W;const s=is(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState(!1),[o,c]=k.useState(0),[d,u]=k.useState(null),[m,f]=k.useState(!1),[x,y]=k.useState(null),[_,b]=k.useState(!1),[j,N]=k.useState(new Set),{data:C,isLoading:A}=pt({queryKey:["cloze-status"],queryFn:async()=>{const{data:te,error:ne}=await U.functions.invoke("cloze-sync",{body:{action:"status"}});if(ne)throw ne;return te}}),E=Mt({mutationFn:async()=>{const{data:te,error:ne}=await U.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:n.trim()}});if(ne)throw ne;if(te!=null&&te.error)throw new Error(te.error);return te},onSuccess:()=>{he.success("Connected to Cloze"),r(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:te=>he.error(te.message)}),D=Mt({mutationFn:async()=>{const{error:te}=await U.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(te)throw te},onSuccess:()=>{he.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),R=Mt({mutationFn:async te=>{const{error:ne}=await U.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:te}});if(ne)throw ne},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),F=Mt({mutationFn:async te=>{const{error:ne}=await U.functions.invoke("cloze-sync",{body:{action:"set_scope",...te}});if(ne)throw ne},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),O=async()=>{b(!0);try{const{data:te,error:ne}=await U.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(ne)throw ne;if(te!=null&&te.error)throw new Error(te.error);y(te.segments||[]),N(new Set((C==null?void 0:C.selected_segments)||[])),f(!0)}catch(te){he.error(te.message||"Failed to load segments")}finally{b(!1)}},B=async()=>{const te=Array.from(j);await F.mutateAsync({sync_scope:"segments",selected_segments:te}),he.success(`Saved · ${te.length} segment(s) selected`),f(!1)},K=async()=>{const te=(C==null?void 0:C.sync_direction)||"pull_only";l(!0),c(0);try{if(te==="pull_only"||te==="bidirectional"){u("Pulling from Cloze…");let ne=0,ae=0,ue=0;for(;;){const{data:me,error:de}=await U.functions.invoke("cloze-sync",{body:{action:"sync",offset:ne}});if(de)throw de;if(me!=null&&me.error)throw new Error(me.error);if(ae+=me.chunk_created||0,ue+=me.chunk_updated||0,ne=me.next_offset,u(`Pulling · ${ae+ue} contacts processed`),c(me.done?100:Math.min(95,(ae+ue)%200/2)),me.done)break;await new Promise(fe=>setTimeout(fe,300))}he.success(`Pulled · ${ae} new, ${ue} updated`)}if(te==="push_only"||te==="bidirectional"){c(0),u("Pushing to Cloze…");let ne=0,ae=0,ue=0;for(;;){const{data:me,error:de}=await U.functions.invoke("cloze-sync",{body:{action:"push",offset:ne}});if(de)throw de;if(me!=null&&me.error)throw new Error(me.error);ae+=me.chunk_pushed||0,ue+=me.chunk_failed||0,ne=me.next_offset;const fe=me.total?Math.min(100,Math.round(ne/me.total*100)):100;if(c(fe),u(`Pushing · ${ne} / ${me.total||"?"}`),me.done)break;await new Promise(je=>setTimeout(je,300))}he.success(`Pushed · ${ae}${ue?`, ${ue} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(ne){he.error(ne.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},Z=(C==null?void 0:C.sync_scope)||"all",Q=((W=C==null?void 0:C.selected_segments)==null?void 0:W.length)||0;return e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(d2,{className:"h-5 w-5 text-primary"}),"Cloze",(C==null?void 0:C.connected)&&e.jsxs(Xe,{variant:"default",className:"ml-1",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Ur,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Pe,{className:"space-y-4",children:A?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):C!=null&&C.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:C.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:C.last_sync_at?new Date(C.last_sync_at).toLocaleString():"Never"})]})]}),C.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:C.last_sync_message}),e.jsx("div",{className:"rounded-lg border px-3 py-2 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sync direction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which way contacts should flow."})]}),e.jsxs(Ds,{value:C.sync_direction||"pull_only",onValueChange:te=>R.mutate(te),disabled:i||R.isPending,children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(lt,{value:"push_only",children:"Push to Cloze"}),e.jsx(lt,{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.":`${Q} segment${Q===1?"":"s"} selected.`})]}),e.jsxs(Ds,{value:Z,onValueChange:te=>{te==="all"?F.mutate({sync_scope:"all",selected_segments:[]}):(F.mutate({sync_scope:"segments",selected_segments:C.selected_segments||[]}),O())},disabled:i||F.isPending,children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All contacts"}),e.jsx(lt,{value:"segments",children:"Selected segments"})]})]})]}),Z==="segments"&&e.jsxs("div",{children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:O,disabled:_,children:[e.jsx(QF,{className:"h-4 w-4 mr-2"}),_?"Loading segments…":"Choose segments"]}),m&&x&&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:[x.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),x.map(te=>{const ne=j.has(te.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(Ri,{checked:ne,onCheckedChange:ae=>{const ue=new Set(j);ae?ue.add(te.id):ue.delete(te.id),N(ue)}}),e.jsx("span",{className:"flex-1 text-sm",children:te.name}),te.count!=null&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:te.count})]},te.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{size:"sm",onClick:B,disabled:F.isPending,children:["Save selection (",j.size,")"]}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>f(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ki,{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(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsxs(q,{disabled:i,children:[e.jsx(lo,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Preview sync"}),e.jsx(Ho,{asChild:!0,children:e.jsx(gGs,{segments:x})})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:K,children:"Start Sync"})]})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsxs(q,{variant:"outline",disabled:i,children:[e.jsx(zr,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Cloze?"}),e.jsx(Ho,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>D.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(Ne,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:n,onChange:te=>a(te.target.value)})]}),e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(Ne,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:te=>r(te.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(un,{className:"h-3 w-3"})]})]})]}),e.jsx(q,{onClick:()=>E.mutate(),disabled:!t.trim()||!n.trim()||E.isPending,children:E.isPending?"Connecting…":"Connect Cloze"})]})})]})}function gGs({segments:s}){var m;const[t,r]=k.useState(!0),[n,a]=k.useState(null),[i,l]=k.useState(null);if(k.useEffect(()=>{(async()=>{try{const{data:f,error:x}=await U.functions.invoke("cloze-sync",{body:{action:"preview"}});if(x)throw x;if(f!=null&&f.error)throw new Error(f.error);a(f)}catch(f){l(f.message||"Could not load preview")}finally{r(!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(f=>[f.id,f.name])),c=n.total_incoming??0,d=n.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 (",n.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()]})]})]}),n.scope==="segments"&&((m=n.segment_counts)==null?void 0:m.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:n.segment_counts.map(f=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(f.id)||f.id}),e.jsx("span",{className:"text-muted-foreground",children:f.total})]},f.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.note})]})}function yGs(){const s=is(),[t,r]=k.useState(""),[n,a]=k.useState(!1),[i,l]=k.useState(0),[o,c]=k.useState(null),{data:d,isLoading:u}=pt({queryKey:["boomtown-status"],queryFn:async()=>{const{data:_,error:b}=await U.functions.invoke("boomtown-sync",{body:{action:"status"}});if(b)throw b;return _}}),m=Mt({mutationFn:async _=>{const{data:b,error:j}=await U.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:_}});if(j)throw j;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{he.success("Connected to Boomtown"),r(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:_=>he.error(_.message)}),f=Mt({mutationFn:async()=>{const{error:_}=await U.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(_)throw _},onSuccess:()=>{he.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),x=Mt({mutationFn:async _=>{const{error:b}=await U.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:_}});if(b)throw b},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),y=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let _=0,b=0,j=0,N=0;try{for(;;){const{data:D,error:R}=await U.functions.invoke("boomtown-sync",{body:{action:"sync",offset:_}});if(R)throw R;if(D!=null&&D.error)throw new Error(D.error);b+=D.chunk_created||0,j+=D.chunk_updated||0,N+=D.chunk_skipped||0,_=D.next_offset;const F=D.total?Math.min(100,Math.round(_/D.total*100)):100;if(l(F),c(`Pulling · ${_} / ${D.total||"?"}`),D.done)break;await new Promise(O=>setTimeout(O,400))}let C=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let D=0;for(l(0),c("Pushing to Boomtown…");;){const{data:R,error:F}=await U.functions.invoke("boomtown-sync",{body:{action:"push",offset:D}});if(F)throw F;if(R!=null&&R.error)throw new Error(R.error);C+=R.chunk_pushed||0,A+=R.chunk_failed||0,D=R.next_offset;const O=R.total?Math.min(100,Math.round(D/R.total*100)):100;if(l(O),c(`Pushing · ${D} / ${R.total||"?"}`),R.done)break;await new Promise(B=>setTimeout(B,400))}}const E=C||A?` · pushed ${C}${A?`, ${A} failed`:""}`:"";he.success(`Sync complete · ${b} new, ${j} updated${N?`, ${N} skipped`:""}${E}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(C){he.error(C.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(d2,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(Xe,{variant:"default",className:"ml-1",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Ur,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Pe,{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(Rr,{checked:d.sync_direction==="bidirectional",onCheckedChange:_=>x.mutate(_?"bidirectional":"pull_only"),disabled:n||x.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ki,{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(q,{onClick:y,disabled:n,children:[e.jsx(lo,{className:`h-4 w-4 mr-2 ${n?"animate-spin":""}`}),n?"Syncing…":"Sync Now"]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsxs(q,{variant:"outline",disabled:n,children:[e.jsx(zr,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Boomtown?"}),e.jsx(Ho,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>f.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(Ne,{id:"boomtown-key",type:"password",placeholder:"Paste your Boomtown Ambassador API key",value:t,onChange:_=>r(_.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(un,{className:"h-3 w-3"})]})]}),e.jsx(q,{onClick:()=>m.mutate(t),disabled:!t.trim()||m.isPending,children:m.isPending?"Connecting…":"Connect"})]})})]})}function rbt(){const s=qr(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState("Test from ReLevelUp"),[o,c]=k.useState(!1),{data:d,isLoading:u}=pt({queryKey:["ses-config"],queryFn:async()=>{const{data:{session:x}}=await U.auth.getSession();if(!x)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 ${x.access_token}`},body:JSON.stringify({action:"check_config"})})).json()}}),m=async()=>{if(!t||!n){he.error("Please fill in From and To email addresses");return}c(!0);try{const{data:{session:x}}=await U.auth.getSession();if(!x)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 ${x.access_token}`},body:JSON.stringify({action:"test_send",to:t,from_email:n,subject:i,body_html:"

Test Email

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

If you received this, SES is configured correctly! 🎉

"})})).json();_.success?he.success(`Test email sent! Message ID: ${_.messageId}`):he.error(_.error||"Failed to send test email")}catch(x){he.error(x.message||"Failed to send test email")}finally{c(!1)}},f=(d==null?void 0:d.configured)===!0;return e.jsxs(ke,{children:[e.jsx(Pt,{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(Ks,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Ur,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(Xe,{variant:f?"default":"secondary",children:u?"Checking...":f?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ti,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(go,{className:"h-3 w-3"})," Not Configured"]})})]})}),f&&e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Send Test Email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Verify your SES setup by sending a test email. The "From" address must be verified in SES or belong to a verified domain.'}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs",children:"From Email"}),e.jsx(Ne,{placeholder:"notifications@mail.relevelup.com",value:n,onChange:x=>a(x.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs",children:"To Email"}),e.jsx(Ne,{placeholder:"your@email.com",value:t,onChange:x=>r(x.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs",children:"Subject"}),e.jsx(Ne,{value:i,onChange:x=>l(x.target.value),className:"text-sm"})]})]}),e.jsxs(q,{onClick:m,disabled:o,size:"sm",children:[o?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(q,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(fh,{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)"]})]})]}),!f&&!u&&e.jsx(Pe,{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["AWS SES credentials are not configured. Add ",e.jsx("code",{children:"AWS_SES_ACCESS_KEY_ID"}),", ",e.jsx("code",{children:"AWS_SES_SECRET_ACCESS_KEY"}),", and ",e.jsx("code",{children:"AWS_SES_REGION"})," as secrets to enable."]})})]})}async function vje(s){const{data:{session:t}}=await U.auth.getSession();if(!t)throw new Error("Not authenticated");const r=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),n=await r.json();if(!r.ok)throw new Error(n.error||"Request failed");return n}function vGs({status:s}){return s==="verified"?e.jsxs(Xe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Xe,{variant:"secondary",children:[e.jsx(jn,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Xe,{variant:"destructive",children:[e.jsx(go,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Xe,{variant:"outline",children:[e.jsx(go,{className:"h-3 w-3 mr-1"})," Not started"]})}function nbt({brokerageId:s,onVerifiedSelect:t}){const r=is(),[n,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,u]=k.useState(null),[m,f]=k.useState(null),{data:x,isLoading:y}=pt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:N,error:C}=await U.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(C)throw C;return N||[]}}),_=Mt({mutationFn:async()=>vje({action:"request_verification",brokerage_id:s,email:n,display_name:i||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),he.success("Verification email sent",{description:`Check ${n} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:N=>he.error(N.message)}),b=async N=>{var C,A;u(N.id);try{const E=await vje({action:"check_status",sender_id:N.id});r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((C=E.sender)==null?void 0:C.status)==="verified"?he.success(`${N.email} is verified! 🎉`):he.info(`Status: ${((A=E.sender)==null?void 0:A.status)||"unknown"}`)}catch(E){he.error(E.message)}finally{u(null)}},j=Mt({mutationFn:async N=>vje({action:"delete",sender_id:N}),onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),he.success("Sender removed"),f(null)},onError:N=>he.error(N.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…"}):x&&x.length>0?e.jsx("div",{className:"space-y-2",children:x.map(N=>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(Ks,{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:N.email}),e.jsx(vGs,{status:N.status})]}),N.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',N.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[N.status==="verified"&&t&&e.jsx(q,{size:"sm",variant:"outline",onClick:()=>t(N.email),children:"Use"}),N.status!=="verified"&&e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>b(N),disabled:d===N.id,title:"Refresh status from AWS",children:d===N.id?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(lo,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>f(N),className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})]})]},N.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(ce,{className:"text-xs",children:"Email Address *"}),e.jsx(Ne,{type:"email",value:n,onChange:N=>a(N.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(Ne,{value:i,onChange:N=>l(N.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(q,{size:"sm",onClick:()=>_.mutate(),disabled:!n.trim()||_.isPending,children:[_.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(el,{open:!!m,onOpenChange:N=>!N&&f(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Remove this sender?"}),e.jsxs(Ho,{children:['"',m==null?void 0:m.email,`" will be removed from your verified senders and from Amazon SES. You'd need to verify it again to use it.`]})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>m&&j.mutate(m.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function bje(s){const{data:{session:t}}=await U.auth.getSession();if(!t)throw new Error("Not authenticated");const r=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),n=await r.json();if(!r.ok)throw new Error(n.error||"Request failed");return n}function bGs({status:s}){return s==="verified"?e.jsxs(Xe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Xe,{variant:"secondary",children:[e.jsx(jn,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Xe,{variant:"destructive",children:[e.jsx(go,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Xe,{variant:"outline",children:[e.jsx(go,{className:"h-3 w-3 mr-1"})," Not started"]})}function _Gs({userId:s,onVerifiedSelect:t}){const r=is(),[n,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,u]=k.useState(null),[m,f]=k.useState(null),{data:x,isLoading:y}=pt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:N,error:C}=await U.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(C)throw C;return N||[]}}),_=Mt({mutationFn:async()=>bje({action:"request_verification",scope:"user",email:n,display_name:i||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-verified-senders",s]}),he.success("Verification email sent",{description:`Check ${n} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:N=>he.error(N.message)}),b=async N=>{var C,A;u(N.id);try{const E=await bje({action:"check_status",sender_id:N.id});r.invalidateQueries({queryKey:["user-verified-senders",s]}),((C=E.sender)==null?void 0:C.status)==="verified"?he.success(`${N.email} is verified! 🎉`):he.info(`Status: ${((A=E.sender)==null?void 0:A.status)||"unknown"}`)}catch(E){he.error(E.message)}finally{u(null)}},j=Mt({mutationFn:async N=>bje({action:"delete",sender_id:N}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-verified-senders",s]}),he.success("Sender removed"),f(null)},onError:N=>he.error(N.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…"}):x&&x.length>0?e.jsx("div",{className:"space-y-2",children:x.map(N=>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(Ks,{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:N.email}),e.jsx(bGs,{status:N.status})]}),N.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',N.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[N.status==="verified"&&t&&e.jsx(q,{size:"sm",variant:"outline",onClick:()=>t(N.email),children:"Use"}),N.status!=="verified"&&e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>b(N),disabled:d===N.id,title:"Refresh status from AWS",children:d===N.id?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(lo,{className:"h-4 w-4"})}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>f(N),className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})]})]},N.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(ce,{className:"text-xs",children:"Email Address *"}),e.jsx(Ne,{type:"email",value:n,onChange:N=>a(N.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(Ne,{value:i,onChange:N=>l(N.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(q,{size:"sm",onClick:()=>_.mutate(),disabled:!n.trim()||_.isPending,children:[_.isPending?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(el,{open:!!m,onOpenChange:N=>!N&&f(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Remove this sender?"}),e.jsxs(Ho,{children:['"',m==null?void 0:m.email,`" will be removed from your verified senders and from Amazon. You'd need to verify it again to use it.`]})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>m&&j.mutate(m.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function wGs(){var A,E,D,R,F;const{user:s,isBrokerageManager:t,isAdmin:r,managedBrokerages:n,selectedBrokerageId:a}=Cs(),i=a||((A=n==null?void 0:n[0])==null?void 0:A.id)||null,l=(t||r)&&!!i,o=is(),[c,d]=k.useState(!1),[u,m]=k.useState(""),[f,x]=k.useState(""),{data:y}=pt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:O,error:B}=await U.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(B)throw B;return O}}),{data:_}=pt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:O,error:B}=await U.from("profiles").select("email, name").eq("id",s.id).single();if(B)throw B;return O}}),b=((E=y==null?void 0:y.reply_to_email)==null?void 0:E.trim())||((D=_==null?void 0:_.email)==null?void 0:D.trim())||"",j=((R=y==null?void 0:y.display_name)==null?void 0:R.trim())||((F=_==null?void 0:_.name)==null?void 0:F.trim())||"";k.useEffect(()=>{c||(m(b),x(j))},[c,b,j]);const N=Mt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const O={reply_to_email:u.trim(),display_name:f.trim()||null,updated_at:new Date().toISOString()};if(y){const{error:B}=await U.from("mass_email_settings").update(O).eq("user_id",s.id);if(B)throw B}else{const{error:B}=await U.from("mass_email_settings").insert({user_id:s.id,...O});if(B)throw B}},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]}),he.success("Reply-to email saved!"),d(!1)},onError:O=>he.error(O.message)}),C=!!b;return e.jsxs(ke,{children:[e.jsx(Pt,{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(hn,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["Mass Email",C?e.jsxs(Xe,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Ti,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Ur,{children:"Set the email address where replies from your campaigns will be sent. If you haven't customized it yet, we'll use your profile email."})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[C&&!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:b})]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(Ua,{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(ce,{className:"text-xs",children:"Display Name"}),e.jsx(Ne,{placeholder:"e.g. 🏡 Karen Hall",value:f,onChange:O=>x(O.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(ce,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(Ne,{type:"email",placeholder:"your@email.com",value:u,onChange:O=>m(O.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{size:"sm",onClick:()=>N.mutate(),disabled:N.isPending||!u.trim(),children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>{d(!1),m(b),x(j)},children:[e.jsx($r,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{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(A1,{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(_Gs,{userId:s.id,onVerifiedSelect:O=>{m(O),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{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(A1,{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(nbt,{brokerageId:i})]})]})]})]})}function jGs(){const s=qr(),{isAdmin:t}=Cs(),r=is(),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(!1),{data:d,isLoading:u}=pt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:E,error:D}=await U.from("gmail_integrations").select("*").maybeSingle();if(D)throw D;return E}}),{data:m}=pt({queryKey:["social-accounts"],queryFn:async()=>{const{data:{user:E}}=await U.auth.getUser();if(!E)return[];const{data:D,error:R}=await U.from("social_accounts").select("*").eq("user_id",E.id).order("created_at",{ascending:!1});if(R)throw R;return D}}),f=async()=>{a(!0);try{const{data:E,error:D}=await U.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(D)throw D;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),he.error("Failed to start Gmail connection"),a(!1)}},x=async E=>{l(!0);try{const{data:D,error:R}=await U.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:E}});if(R)throw R;if(D!=null&&D.authUrl)window.location.href=D.authUrl;else throw new Error("Failed to get authorization URL")}catch(D){console.error("Meta OAuth error:",D),he.error("Failed to start connection. Make sure Meta App credentials are configured."),l(!1)}},y=async()=>{c(!0);try{const{data:E,error:D}=await U.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(D)throw D;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),he.error("Failed to start LinkedIn connection. Please try again."),c(!1)}},_=Mt({mutationFn:async E=>{const{error:D}=await U.from("gmail_integrations").delete().eq("id",E);if(D)throw D},onSuccess:()=>{r.invalidateQueries({queryKey:["gmail-integration"]}),he.success("Gmail disconnected")},onError:()=>{he.error("Failed to disconnect Gmail")}}),b=Mt({mutationFn:async E=>{const{error:D}=await U.from("social_accounts").delete().eq("id",E);if(D)throw D},onSuccess:()=>{r.invalidateQueries({queryKey:["social-accounts"]}),he.success("Account disconnected")},onError:()=>{he.error("Failed to disconnect account")}}),j=!!(d!=null&&d.is_active),N=(m==null?void 0:m.filter(E=>E.platform==="facebook"))||[],C=(m==null?void 0:m.filter(E=>E.platform==="instagram"))||[],A=(m==null?void 0:m.filter(E=>E.platform==="linkedin"))||[];return e.jsx(ws,{children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Integrations"}),e.jsx("p",{className:"text-muted-foreground",children:"Connect third-party services to supercharge your Agent OS workflow."})]}),e.jsxs(ke,{children:[e.jsx(Pt,{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(eS,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"ChatGPT"}),e.jsx(Ur,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(Pe,{children:e.jsxs(q,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(ci,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{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(Ks,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["Gmail",j&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Ur,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Ti,{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(Ti,{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(Ti,{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(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Gmail?"}),e.jsx(Ho,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>_.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(q,{className:"mt-4",onClick:f,disabled:n||u,children:[n?e.jsx(lo,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(ci,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{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(Dt,{className:"text-lg flex items-center gap-2",children:["Facebook",N.length>0&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Ur,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[N.length>0&&e.jsx("div",{className:"space-y-2",children:N.map(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(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:E.profile_picture_url||""}),e.jsx(Kn,{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(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Facebook?"}),e.jsx(Ho,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>b.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(q,{onClick:()=>x("facebook"),disabled:i,variant:"outline",className:"gap-2",children:[i?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{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(gu,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["Instagram",C.length>0&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Ur,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[C.length>0&&e.jsx("div",{className:"space-y-2",children:C.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(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:E.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(gu,{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(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Instagram?"}),e.jsx(Ho,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>b.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(q,{onClick:()=>x("instagram"),disabled:i,variant:"outline",className:"gap-2",children:[i?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Uses Instagram's professional login for Business or Creator accounts. Personal accounts cannot post via Meta's API — convert your account in the Instagram app (Profile → Menu → Settings → Account type → Switch to Professional)."})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{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(Yf,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["LinkedIn",A.length>0&&e.jsx(Xe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Ur,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Pe,{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(Wn,{className:"h-8 w-8",children:[e.jsx(Xa,{src:E.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(Yf,{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(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect LinkedIn?"}),e.jsx(Ho,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>b.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(q,{onClick:y,disabled:o,variant:"outline",className:"gap-2",children:[o?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(fGs,{}),e.jsx(pGs,{}),e.jsx(xGs,{}),e.jsx(yGs,{}),e.jsx(wGs,{}),t&&e.jsx(rbt,{})]})})}const NGs="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function kGs(){const[s,t]=k.useState(null),[r,n]=k.useState(!1),[a,i]=k.useState(0),[l,o]=k.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),m=async b=>{const j=new Uint8Array(await b.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},f=b=>{const j=document.createElement("a");j.href=b,j.download="levelup-extension.zip",j.rel="noopener noreferrer",j.target="_blank",document.body.appendChild(j),j.click(),j.remove()},x=async()=>{o(!0);try{if(u){f(`${d}?v=${Date.now()}`);return}const b=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!b.ok)throw new Error(`Download failed (${b.status})`);const j=await b.blob();if(!await m(j)){f(`${d}?v=${Date.now()}`);return}const N=new Blob([j],{type:"application/zip"}),C=URL.createObjectURL(N),A=document.createElement("a");A.href=C,A.download="levelup-extension.zip",document.body.appendChild(A),A.click(),A.remove(),setTimeout(()=>URL.revokeObjectURL(C),1e3)}catch(b){he.error(b.message||"Download failed")}finally{o(!1)}},y=async()=>{n(!0);try{await U.auth.refreshSession();const{data:b}=await U.auth.getSession();if(!b.session){he.error("Your session has expired. Please sign in again.");return}const{data:j,error:N}=await U.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${b.session.access_token}`}});if(N)throw N;t(j.code),i(j.expires_in||300);const C=setInterval(()=>{i(A=>A<=1?(clearInterval(C),t(null),0):A-1)},1e3)}catch(b){console.error("generateCode error",b),he.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{n(!1)}},_=()=>{s&&(navigator.clipboard.writeText(s),he.success("Copied"))};return e.jsx(ws,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(Yo,{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(CE,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Browser Extension"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts and import listings from anywhere on the web."})]})]})}),e.jsxs(ke,{className:"p-6 space-y-4 border-2 border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"1"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Install from the Chrome Web Store"})]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Quick-add contacts from any webpage with one click or right-click"}),e.jsx("li",{children:"Import listings from Zillow, Realtor.com, and Redfin as drafts"}),e.jsx("li",{children:'"Add to LevelUp" button on Gmail threads and LinkedIn profiles'}),e.jsx("li",{children:"Toolbar launcher with shortcuts to Dashboard, ReelFlow, Card Studio, and more"})]}),e.jsxs(q,{size:"lg",className:"w-full",onClick:()=>window.open(NGs,"_blank","noopener,noreferrer"),children:[e.jsx(CE,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(un,{className:"w-3.5 h-3.5 ml-2 opacity-70"})]}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Works in Chrome, Edge, Brave, and Arc. Free to install."})]}),e.jsxs(ke,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"2"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Pair the extension"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a one-time pairing code, then enter it inside the extension popup."}),s?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-muted rounded-xl p-6 text-center",children:[e.jsx("div",{className:"text-4xl font-mono font-bold tracking-[0.4em] text-primary",children:s}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Expires in ",Math.floor(a/60),":",String(a%60).padStart(2,"0")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{onClick:_,variant:"outline",className:"flex-1",children:[e.jsx(si,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(q,{onClick:y,variant:"outline",className:"flex-1",children:[e.jsx(lo,{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(la,{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(q,{onClick:y,disabled:r,size:"lg",className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(lo,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(ke,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yc,{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(q,{variant:"link",className:"h-auto p-0 text-sm",onClick:x,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 SGs(){const[s]=ic(),t=qr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your Gmail account...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:m,error:f}=await U.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(f)throw f;if(m!=null&&m.success)n("success"),i(m.message||"Gmail connected successfully!"),he.success("Gmail connected!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("Gmail OAuth callback error:",m),n("error"),i(m instanceof Error?m.message:"Failed to connect Gmail"),he.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{className:"text-center",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(Ti,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(ad,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Dt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Ur,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(q,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"Back to Integrations":"Try Again"})})]})})}function CGs(){const s=qr();return k.useEffect(()=>{const t=setTimeout(()=>{s("/mission-control/integrations",{replace:!0})},1500);return()=>clearTimeout(t)},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Finishing Canva connection…"})]})})}function TGs(){const[s]=ic(),t=qr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing your connection...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:f,error:x}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/mission-control/integrations/meta/callback"}});if(f&&f.success===!1)throw new Error(f.error||"Failed to connect accounts");if(x){let y=x.message||"Failed to connect accounts";try{const _=x.context;if(_&&typeof _.json=="function"){const b=await _.json();b!=null&&b.error&&(y=b.error)}}catch{}throw new Error(y)}if(f!=null&&f.success)n("success"),i(`Successfully connected ${((m=f.accounts)==null?void 0:m.length)||0} account(s)!`),he.success("Social accounts connected successfully!");else throw new Error((f==null?void 0:f.error)||"Unknown error")}catch(f){console.error("OAuth callback error:",f),n("error"),i(f instanceof Error?f.message:"Failed to connect accounts"),he.error("Failed to connect: "+(f instanceof Error?f.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{className:"text-center",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(Ti,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(ad,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Dt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Ur,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(q,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"View Integrations":"Try Again"})})]})})}const abt=new Date().getFullYear(),EGs=Array.from({length:5},(s,t)=>abt-t);function AGs(){const[s,t]=k.useState(abt),r=qr(),{data:n,isLoading:a}=iJt();return a?e.jsx(ws,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(dr,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(dr,{className:"h-24"},i))}),e.jsx(dr,{className:"h-96"})]})}):e.jsx(ws,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Scorecard Admin"}),e.jsx("p",{className:"text-muted-foreground",children:"View agent performance and scorecards"})]}),e.jsxs(Ds,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(Ps,{className:"w-[120px]",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:EGs.map(i=>e.jsx(lt,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Dr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Agents Tracking"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(n==null?void 0:n.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Mo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(n==null?void 0:n.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Agents with Scorecards"}),e.jsx(Ur,{children:"Click to view individual agent scorecards"})]}),e.jsx(Pe,{children:!n||n.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Mo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Email"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:n.map(i=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:i.name}),e.jsx(xt,{className:"text-muted-foreground",children:i.email}),e.jsx(xt,{className:"text-right",children:e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>r(`/admin/scorecard/${i.id}`),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const ibt=new Date().getFullYear(),MGs=Array.from({length:10},(s,t)=>ibt-t);function UKe(){var _;const{userId:s}=xo(),t=qr(),n=vc().pathname.startsWith("/mission-control"),[a,i]=k.useState(ibt),{data:l,isLoading:o}=pt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:b,error:j}=await U.from("profiles").select("id, name, email").eq("id",s).single();if(j)throw j;return b},enabled:!!s}),{data:c,isLoading:d}=NEe(a,s),{yearStats:u,lifetimeStats:m,isLoading:f,showCommission:x}=Wct(a,s),{data:y}=Gct(a,s);return o?e.jsx(ws,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(dr,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(b=>e.jsx(dr,{className:"h-24"},b))})]})}):e.jsx(ws,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>t(n?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:l==null?void 0:l.name}),e.jsx("p",{className:"text-muted-foreground",children:l==null?void 0:l.email})]})]}),e.jsxs(Ds,{value:String(a),onValueChange:b=>i(Number(b)),children:[e.jsx(Ps,{className:"w-[120px]",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:MGs.map(b=>e.jsx(lt,{value:String(b),children:b},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Pn,{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:[m.totalTransactions," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Dr,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Xl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:nd(u.totalVolume,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Wo,{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:nd(u.averagePrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Uc,{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(f1t,{goals:y,stats:u,year:a,showCommission:x}),e.jsxs(ta,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"transactions",children:"Transactions"}),e.jsx(rs,{value:"charts",children:"Charts"}),e.jsxs(rs,{value:"map",children:[e.jsx(Ma,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(fs,{value:"transactions",children:e.jsx(aIe,{transactions:c||[],showCommission:x,isLoading:d})}),e.jsx(fs,{value:"charts",children:e.jsx(iIe,{stats:u,year:a})}),e.jsx(fs,{value:"map",children:e.jsx(oIe,{transactions:c||[],isLoading:d})})]})]})})}function IGs(){const s=is(),[t,r]=k.useState(""),[n,a]=k.useState("all"),[i,l]=k.useState(null);Slt();const{data:o,refetch:c}=pt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:O}=await U.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(O==null?void 0:O.enabled)??!1}}),{data:d,isLoading:u}=pt({queryKey:["admin-listings"],queryFn:async()=>{const{data:O,error:B}=await U.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(B)throw B;return O}}),{data:m}=pt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:O}=await U.from("listings").select("id, is_approved, status"),{data:B}=await U.from("listing_shares").select("id"),{data:K}=await U.from("listing_views").select("id"),{count:Z}=await U.from("listing_leads").select("id",{count:"exact",head:!0}),Q=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:W}=await U.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",Q);return{total:(O==null?void 0:O.length)||0,pending:(O==null?void 0:O.filter(te=>!te.is_approved).length)||0,active:(O==null?void 0:O.filter(te=>te.status==="active").length)||0,totalShares:(B==null?void 0:B.length)||0,totalViews:(K==null?void 0:K.length)||0,totalLeads:Z||0,leadsLast7:W||0}}}),{data:f}=pt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const O={};let B=0;const K=1e3;for(;;){const{data:Z,error:Q}=await U.from("listing_leads").select("listing_id").range(B,B+K-1);if(Q)throw Q;if(!Z||Z.length===0)break;for(const W of Z)W.listing_id&&(O[W.listing_id]=(O[W.listing_id]||0)+1);if(Z.length{const{data:O,error:B}=await U.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(B)throw B;return O}}),_=async(O,B,K="submit_url")=>{try{const{data:{session:Z}}=await U.auth.getSession();if(!Z)return;const{data:Q,error:W}=await U.functions.invoke("google-indexing",{body:{action:K,listing_id:O,listing_slug:B}});if(W)throw W;if((Q==null?void 0:Q.configured)===!1)return;Q!=null&&Q.success&&he.success("Submitted to Google for indexing")}catch(Z){console.error("Google indexing submission failed:",Z)}},b=Mt({mutationFn:async()=>{const{data:{session:O}}=await U.auth.getSession();if(!O)throw new Error("Not authenticated");const{data:B,error:K}=await U.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(K)throw K;return B},onSuccess:O=>{if((O==null?void 0:O.configured)===!1){he.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}he.success(`Submitted ${(O==null?void 0:O.succeeded)||0} URLs to Google (${(O==null?void 0:O.failed)||0} failed)`)},onError:O=>{he.error("Failed to submit to Google"),console.error(O)}}),j=Mt({mutationFn:async({id:O,approved:B,slug:K})=>{const{error:Z}=await U.from("listings").update({is_approved:B}).eq("id",O);if(Z)throw Z;return{id:O,approved:B,slug:K}},onSuccess:O=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),he.success(O.approved?"Listing approved":"Listing unapproved"),O.approved?_(O.id,O.slug||null,"submit_url"):_(O.id,O.slug||null,"remove_url")}}),N=Mt({mutationFn:async({id:O,featured:B})=>{const{error:K}=await U.from("listings").update({is_featured:B}).eq("id",O);if(K)throw K},onSuccess:(O,{featured:B})=>{s.invalidateQueries({queryKey:["admin-listings"]}),he.success(B?"Listing featured":"Listing unfeatured")}}),C=Mt({mutationFn:async O=>{const{error:B}=await U.from("listings").delete().eq("id",O);if(B)throw B},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),he.success("Listing deleted")}}),A=Mt({mutationFn:async O=>{const{error:B}=await U.from("feature_flags").update({enabled:O}).eq("key","listing_exchange_enabled");if(B)throw B},onSuccess:()=>{c(),he.success("Feature flag updated")}}),E=o??!1,D=d==null?void 0:d.filter(O=>{var Z,Q,W,te;const B=((Z=O.city)==null?void 0:Z.toLowerCase().includes(t.toLowerCase()))||((W=(Q=O.agent)==null?void 0:Q.name)==null?void 0:W.toLowerCase().includes(t.toLowerCase()))||((te=O.property_address)==null?void 0:te.toLowerCase().includes(t.toLowerCase())),K=n==="all"||n==="pending"&&!O.is_approved||n==="approved"&&O.is_approved;return B&&K}),R=O=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(O),F=O=>{const B={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 B[O]||B.active};return e.jsxs(ws,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>b.mutate(),disabled:b.isPending,className:"gap-2",children:[b.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(Ql,{className:"h-4 w-4"}),"Submit All to Google"]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Feature visible to agents"}),e.jsx(Rr,{checked:E,onCheckedChange:O=>A.mutate(O)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.total)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wo,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.active)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Pending Review"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.pending)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Views"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.totalViews)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ec,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Shares"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.totalShares)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(m==null?void 0:m.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by city, address, or agent...",value:t,onChange:O=>r(O.target.value),className:"pl-9"})]}),e.jsx(ta,{value:n,onValueChange:O=>a(O),children:e.jsxs(ea,{children:[e.jsx(rs,{value:"all",children:"All"}),e.jsx(rs,{value:"pending",children:"Pending"}),e.jsx(rs,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{children:["Listings (",(D==null?void 0:D.length)||0,")"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Property"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Price"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-center",children:"Approved"}),e.jsx(At,{className:"text-center",children:"Featured"}),e.jsx(At,{children:"Views"}),e.jsx(At,{children:"Shares"}),e.jsx(At,{children:"Leads"}),e.jsx(At,{children:"Date"}),e.jsx(At,{})]})}),e.jsx(ha,{children:u?e.jsx(Ws,{children:e.jsx(xt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(D==null?void 0:D.length)===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):D==null?void 0:D.map(O=>{var B,K,Z,Q,W;return e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(K=(B=O.photos)==null?void 0:B[0])!=null&&K.photo_url?e.jsx("img",{src:O.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(Ga,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:O.property_address||`${O.city}, ${O.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Z=O.property_type)==null?void 0:Z.replace("_"," ")})]})]})}),e.jsx(xt,{children:e.jsx("p",{className:"text-sm",children:((Q=O.agent)==null?void 0:Q.name)||"Unknown"})}),e.jsx(xt,{className:"font-medium",children:R(O.price)}),e.jsx(xt,{children:e.jsx(Xe,{variant:"outline",className:F(O.status),children:(W=O.status)==null?void 0:W.replace("_"," ")})}),e.jsx(xt,{className:"text-center",children:e.jsx(Rr,{checked:O.is_approved??!1,onCheckedChange:te=>j.mutate({id:O.id,approved:te,slug:O.slug})})}),e.jsx(xt,{className:"text-center",children:e.jsx(Rr,{checked:O.is_featured??!1,onCheckedChange:te=>N.mutate({id:O.id,featured:te})})}),e.jsx(xt,{children:O.view_count||0}),e.jsx(xt,{children:O.share_count||0}),e.jsx(xt,{children:((f==null?void 0:f[O.id])??0)>0?e.jsx(q,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:O.id,label:O.property_address||`${O.city}, ${O.state}`}),children:f==null?void 0:f[O.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:As(new Date(O.created_at),"MMM d, yyyy")}),e.jsx(xt,{children:e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",children:e.jsx(f0,{className:"h-4 w-4"})})}),e.jsxs(Sd,{align:"end",children:[e.jsxs(ti,{onClick:()=>window.open(`/mission-control/listings/${O.id}`,"_blank"),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(ti,{onClick:()=>N.mutate({id:O.id,featured:!O.is_featured}),children:[e.jsx(fa,{className:"h-4 w-4 mr-2"}),O.is_featured?"Unfeature":"Feature"]}),e.jsxs(ti,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&C.mutate(O.id)},children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},O.id)})})]})})})]})]}),e.jsx(vs,{open:!!i,onOpenChange:O=>!O&&l(null),children:e.jsxs(ys,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Leads from listing"}),e.jsx(an,{children:i==null?void 0:i.label})]}),y?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(ls,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!x||x.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Phone"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Captured"})]})}),e.jsx(ha,{children:x.map(O=>{var B;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:[O.first_name,O.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(xt,{children:O.email}),e.jsx(xt,{children:O.phone||"—"}),e.jsx(xt,{children:e.jsx(Xe,{variant:"outline",children:(B=O.lead_type)==null?void 0:B.replace("_"," ")})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:As(new Date(O.created_at),"MMM d, yyyy h:mm a")})]},O.id)})})]})]})})]})}function PGs(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function LGs(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("all"),{data:l,isLoading:o}=pt({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const m=[];let f=0;const x=1e3;for(;;){const{data:y,error:_}=await U.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(f,f+x-1);if(_)throw _;if(!y||y.length===0||(m.push(...y),y.length{if(!l)return[];const m=r==="all"?0:Date.now()-parseInt(r)*24*60*60*1e3,f=s.trim().toLowerCase();return l.filter(x=>{var _,b,j,N,C,A;return m&&new Date(x.created_at).getTime(){const m=c.length,f=c.filter(_=>_.lead_type==="showing_request").length,x=new Set(c.map(_=>_.agent_id)).size,y=new Set(c.map(_=>_.listing_id)).size;return{total:m,showings:f,uniqueAgents:x,uniqueListings:y}},[c]),u=()=>{const f=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(b=>{var j,N,C,A,E,D;return[As(new Date(b.created_at),"yyyy-MM-dd HH:mm"),`${b.first_name||""} ${b.last_name||""}`.trim(),b.email,b.phone||"",b.lead_type,b.preferred_date?`${b.preferred_date} ${b.preferred_time||""}`:"",((j=b.listing)==null?void 0:j.property_address)||"",((N=b.listing)==null?void 0:N.city)||"",(C=b.listing)!=null&&C.price?String(b.listing.price):"",((A=b.agent)==null?void 0:A.name)||"",((E=b.agent)==null?void 0:E.email)||"",((D=b.referrer)==null?void 0:D.name)||"",(b.message||"").replace(/[\r\n]+/g," ")]})].map(b=>b.map(j=>`"${String(j).replace(/"/g,'""')}"`).join(",")).join(` `),x=new Blob([f],{type:"text/csv"}),y=URL.createObjectURL(x),_=document.createElement("a");_.href=y,_.download=`listing-leads-${As(new Date,"yyyy-MM-dd")}.csv`,_.click(),URL.revokeObjectURL(y)};return e.jsx(ws,{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(q,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(li,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xl,{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(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{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(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pn,{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(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xl,{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(ke,{children:e.jsx(Pe,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search name, email, property, agent...",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:a,onValueChange:m=>i(m),children:[e.jsx(Ps,{className:"w-full sm:w-48",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Types"}),e.jsx(lt,{value:"info_request",children:"Info Request"}),e.jsx(lt,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(Ds,{value:r,onValueChange:m=>n(m),children:[e.jsx(Ps,{className:"w-full sm:w-40",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Time"}),e.jsx(lt,{value:"7",children:"Last 7 days"}),e.jsx(lt,{value:"30",children:"Last 30 days"}),e.jsx(lt,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{children:["Leads (",c.length,")"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Date"}),e.jsx(At,{children:"Lead"}),e.jsx(At,{children:"Contact"}),e.jsx(At,{children:"Property"}),e.jsx(At,{children:"Type"}),e.jsx(At,{children:"Assigned To"}),e.jsx(At,{children:"Referred By"}),e.jsx(At,{children:"Message"})]})}),e.jsx(ha,{children:o?e.jsx(Ws,{children:e.jsx(xt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(m=>{var f,x;return e.jsxs(Ws,{children:[e.jsxs(xt,{className:"whitespace-nowrap text-sm",children:[As(new Date(m.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:As(new Date(m.created_at),"h:mm a")})]}),e.jsx(xt,{children:e.jsx("div",{className:"font-medium",children:`${m.first_name||""} ${m.last_name||""}`.trim()||"—"})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col gap-1 text-sm",children:[e.jsxs("a",{href:`mailto:${m.email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Ks,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("a",{href:`tel:${m.phone}`,className:"flex items-center gap-1 text-muted-foreground hover:underline",children:[e.jsx(Mn,{className:"h-3 w-3"}),m.phone]})]})}),e.jsx(xt,{children:m.listing?e.jsxs(Vn,{to:`/public/listings/${m.listing.slug||m.listing.id}`,target:"_blank",className:"group",children:[e.jsxs("div",{className:"font-medium text-sm group-hover:underline flex items-center gap-1",children:[m.listing.property_address||"Untitled",e.jsx(un,{className:"h-3 w-3 opacity-60"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[[m.listing.city,m.listing.state].filter(Boolean).join(", ")," · ",PGs(m.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(xt,{children:[e.jsx(Xe,{variant:m.lead_type==="showing_request"?"default":"secondary",className:"text-xs",children:m.lead_type==="showing_request"?"Showing":"Info"}),m.preferred_date&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[m.preferred_date," ",m.preferred_time||""]}),m.showing_mode&&e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:m.showing_mode.replace("_"," ")})]}),e.jsxs(xt,{children:[e.jsx("div",{className:"text-sm font-medium",children:((f=m.agent)==null?void 0:f.name)||"—"}),((x=m.agent)==null?void 0:x.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:m.agent.email})]}),e.jsx(xt,{children:m.referrer?e.jsxs("div",{children:[e.jsx("div",{className:"text-sm",children:m.referrer.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.referrer.email})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Direct"})}),e.jsx(xt,{className:"max-w-xs",children:m.message?e.jsxs("div",{className:"text-xs text-muted-foreground line-clamp-3 flex items-start gap-1",children:[e.jsx(Ui,{className:"h-3 w-3 mt-0.5 shrink-0"}),m.message]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})})]},m.id)})})]})})})]})]})})}const V6={new_listing_alerts:{label:"New Listing Alerts",icon:ym,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:OE,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:yi,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:_n,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:vm,color:"bg-emerald-100 text-emerald-800"}},qKe=[{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 VKe(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function DGs(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState("30d"),[l,o]=k.useState("all"),[c,d]=k.useState("");k.useEffect(()=>{let x=!1;return(async()=>{n(!0);let y=U.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const _=qKe.find(N=>N.key===a);if(_&&_.days>0){const N=new Date(Date.now()-_.days*864e5).toISOString();y=y.gte("created_at",N)}const{data:b,error:j}=await y;x||(j?(console.error(j),t([])):t(b||[]),n(!1))})(),()=>{x=!0}},[a]);const u=k.useMemo(()=>s.filter(x=>{if(l!=="all"&&x.lead_type!==l)return!1;if(c){const y=c.toLowerCase();if(![x.email,x.first_name,x.last_name,x.phone,x.source_page,x.referrer].filter(Boolean).join(" ").toLowerCase().includes(y))return!1}return!0}),[s,l,c]),m=k.useMemo(()=>{const x=u.length,y=new Set(u.map(b=>b.email.toLowerCase())).size,_={};return u.forEach(b=>{_[b.lead_type]=(_[b.lead_type]||0)+1}),{total:x,uniqueEmails:y,byType:_}},[u]),f=()=>{const y=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(N=>{var A;const C=[VKe(N.created_at),((A=V6[N.lead_type])==null?void 0:A.label)||N.lead_type,N.email,N.first_name||"",N.last_name||"",N.phone||"",N.listing_id||"",N.source_page||"",N.referrer||"",N.criteria?JSON.stringify(N.criteria):""].map(E=>`"${String(E).replace(/"/g,'""')}"`);y.push(C.join(","))});const _=new Blob([y.join(` `)],{type:"text/csv"}),b=URL.createObjectURL(_),j=document.createElement("a");j.href=b,j.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,j.click(),URL.revokeObjectURL(b)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(Yo,{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(Vn,{to:"/admin",children:e.jsxs(q,{variant:"ghost",size:"sm",children:[e.jsx(Aa,{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(q,{onClick:f,variant:"outline",size:"sm",children:[e.jsx(li,{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(ke,{children:e.jsxs(Pe,{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:m.total}),e.jsxs("div",{className:"text-xs text-slate-500 mt-1",children:[m.uniqueEmails," unique"]})]})}),Object.keys(V6).map(x=>{const y=V6[x],_=y.icon;return e.jsx(ke,{children:e.jsxs(Pe,{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:m.byType[x]||0})]})},x)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ds,{value:a,onValueChange:x=>i(x),children:[e.jsx(Ps,{className:"w-[160px] bg-white",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:qKe.map(x=>e.jsx(lt,{value:x.key,children:x.label},x.key))})]}),e.jsxs(Ds,{value:l,onValueChange:o,children:[e.jsx(Ps,{className:"w-[200px] bg-white",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All lead types"}),Object.keys(V6).map(x=>e.jsx(lt,{value:x,children:V6[x].label},x))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(Ne,{placeholder:"Search name, email, phone…",value:c,onChange:x=>d(x.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(ke,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-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:r?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(x=>{const y=V6[x.lead_type],_=y==null?void 0:y.icon,b=[x.first_name,x.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:VKe(x.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(Xe,{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)||x.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:b}),e.jsxs("a",{href:`mailto:${x.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Ks,{className:"h-3 w-3"}),x.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:x.phone?e.jsxs("a",{href:`tel:${x.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"}),x.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:[x.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[x.listing_id.slice(0,8),"…"]})]}),x.criteria&&Object.keys(x.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(x.criteria).map(([j,N])=>`${j}: ${N}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[x.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:x.source_page})]}),x.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",x.referrer]})]})]},x.id)})})]})})})]})]})}const RGs=()=>{var m,f;const[s,t]=k.useState(""),[r,n]=k.useState(null),{data:a,isLoading:i}=pt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:x,error:y}=await U.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(y)throw y;const _=(x==null?void 0:x.map(N=>N.user_id))||[],{data:b}=await U.from("profiles").select("id, name, email").in("id",_);return x==null?void 0:x.map(N=>({...N,profiles:(b==null?void 0:b.find(C=>C.id===N.user_id))||null}))}}),l=a==null?void 0:a.filter(x=>{var _,b,j,N,C;const y=s.toLowerCase();return((b=(_=x.profiles)==null?void 0:_.name)==null?void 0:b.toLowerCase().includes(y))||((N=(j=x.profiles)==null?void 0:j.email)==null?void 0:N.toLowerCase().includes(y))||((C=x.review_text)==null?void 0:C.toLowerCase().includes(y))}),o=a!=null&&a.length?(a.reduce((x,y)=>x+y.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((x,y)=>(x[y.rating]=(x[y.rating]||0)+1,x),{}),d=(a==null?void 0:a.filter(x=>x.posted_to_google).length)||0,u=x=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(y=>e.jsx(fa,{className:zt("h-4 w-4",x>=y?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},y))});return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Membership Reviews",description:"View and manage feedback from LevelUp members"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"Total Reviews"}),e.jsx(Dt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"Average Rating"}),e.jsxs(Dt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(fa,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"5-Star Reviews"}),e.jsx(Dt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(ke,{children:e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Ur,{children:"Posted to Google"}),e.jsxs(Dt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(un,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or review...",value:s,onChange:x=>t(x.target.value),className:"pl-9"})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Member"}),e.jsx(At,{children:"Rating"}),e.jsx(At,{className:"hidden md:table-cell",children:"Review"}),e.jsx(At,{children:"Google"}),e.jsx(At,{children:"Date"})]})}),e.jsx(ha,{children:i?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(x=>{var y,_;return e.jsxs(Ws,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>n(x),children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((y=x.profiles)==null?void 0:y.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(_=x.profiles)==null?void 0:_.email})]})}),e.jsx(xt,{children:u(x.rating)}),e.jsx(xt,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:x.review_text||"-"})}),e.jsx(xt,{children:x.posted_to_google?e.jsx(Xe,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(Xe,{variant:"outline",children:"No"})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:As(new Date(x.created_at),"MMM d, yyyy")})]},x.id)})})]})})}),e.jsx(vs,{open:!!r,onOpenChange:()=>n(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Review Details"})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((m=r.profiles)==null?void 0:m.name)||"Unknown Member"}),((f=r.profiles)==null?void 0:f.email)&&e.jsxs("a",{href:`mailto:${r.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(Ks,{className:"h-3 w-3"}),r.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[u(r.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[r.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:r.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(vn,{className:"h-4 w-4"}),As(new Date(r.created_at),"MMMM d, yyyy 'at' h:mm a")]}),r.posted_to_google?e.jsxs(Xe,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(Xe,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},OGs=[{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"}],FGs=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 zGs(){const s=is(),{user:t}=Cs(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),{data:c,isLoading:d}=pt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:F,error:O}=await U.from("weekly_digest_settings").select("*").single();if(O)throw O;return F}}),{data:u,isLoading:m}=pt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:F,error:O}=await U.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(O)throw O;return F}}),{data:f}=pt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:F,error:O}=await U.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(O)throw O;return F||0}}),{data:x,refetch:y}=pt({queryKey:["digest-queue-status"],queryFn:async()=>{const F=new Date;F.setUTCHours(0,0,0,0);const[O,B,K,Z]=await Promise.all([U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",F.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",F.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",F.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",F.toISOString())]);return{pending:O.count||0,processing:B.count||0,sent:K.count||0,failed:Z.count||0,total:(O.count||0)+(B.count||0)+(K.count||0)+(Z.count||0)}},refetchInterval:5e3});k.useEffect(()=>{if(x&&(x.pending>0||x.processing>0)){const F=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(F)}},[x,y,s]);const{data:_=0}=pt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const F=new Date;F.setUTCHours(0,0,0,0);const{count:O,error:B}=await U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",F.toISOString());if(B)throw B;return O||0}}),b=Mt({mutationFn:async F=>{const{error:O}=await U.from("weekly_digest_settings").update(F).eq("id",c==null?void 0:c.id);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),he.success("Settings updated")},onError:F=>{he.error("Failed to update settings: "+F.message)}}),j=async()=>{n(!0);try{const{data:F,error:O}=await U.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(O)throw O;F.queued?he.success(`${F.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):F.sent!==void 0&&he.success(`Digest sent! ${F.sent} emails delivered, ${F.failed} failed`),y(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(F){he.error("Failed to send digest: "+F.message)}finally{n(!1)}},N=async()=>{var F,O,B,K,Z,Q;if(!(t!=null&&t.email)){he.error("No email found for your account");return}i(!0);try{const{data:W,error:te}=await U.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(te)throw te;const ne=W==null?void 0:W.resendId,ae=W==null?void 0:W.resendDetails,ue=ae==null?void 0:ae.status,me=((F=ae==null?void 0:ae.body)==null?void 0:F.status)||((B=(O=ae==null?void 0:ae.body)==null?void 0:O.data)==null?void 0:B.status),de=((Z=(K=ae==null?void 0:ae.body)==null?void 0:K.error)==null?void 0:Z.message)||((Q=ae==null?void 0:ae.body)==null?void 0:Q.message);he.success(ne?`Preview accepted by email provider (id: ${ne})${ue?`, status check: ${ue}`:""}${me?`, provider: ${me}`:""}${de?` (${de})`:""}. 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){he.error("Failed to send preview: "+W.message)}finally{i(!1)}},C=async()=>{o(!0);try{const{data:F,error:O}=await U.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(O)throw O;F.queued===0||F.sent===0&&F.failed===0&&!F.queued?he.info("No failed emails to retry"):F.queued?he.success(`${F.queued} emails queued for retry!`):he.success(`Retry complete! ${F.sent} emails delivered, ${F.failed} failed`),y(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(F){he.error("Failed to retry: "+F.message)}finally{o(!1)}},A=x!=null&&x.total?Math.round((x.sent+x.failed)/x.total*100):0,E=((x==null?void 0:x.pending)||0)>0||((x==null?void 0:x.processing)||0)>0,{data:D}=pt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var Q,W;const F=new Date;F.setUTCHours(0,0,0,0);const[O,B,K,Z]=await Promise.all([U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",F.toISOString()),U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",F.toISOString()),U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",F.toISOString()),U.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:O.count||0,totalFailed:B.count||0,agentOsEngaged:K.count||0,lastSent:((W=(Q=Z.data)==null?void 0:Q[0])==null?void 0:W.sent_at)||null}},refetchInterval:E?5e3:!1}),R={totalSent:(D==null?void 0:D.totalSent)||0,totalFailed:(D==null?void 0:D.totalFailed)||0,lastSent:D==null?void 0:D.lastSent,agentOsEngaged:(D==null?void 0:D.agentOsEngaged)||0};return d?e.jsx(ws,{title:"Weekly Digest",description:"Manage automated weekly email digests",children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-32 bg-muted rounded-lg"}),e.jsx("div",{className:"h-64 bg-muted rounded-lg"})]})}):e.jsx(ws,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(ta,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(rs,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(Mo,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(fs,{value:"settings",className:"space-y-6",children:[E&&x&&e.jsx(ke,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(ls,{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:[x.sent.toLocaleString()," sent, ",x.pending.toLocaleString()," pending",x.failed>0&&`, ${x.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[A,"%"]})]}),e.jsx(ki,{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(x.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(Dr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:f}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-emerald-500/10",children:e.jsx(qn,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-destructive/10",children:e.jsx(ad,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(jn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.lastSent?As(new Date(R.lastSent),"MMM d"):"Never"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Ur,{children:"Configure when the digest is sent"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(Rr,{checked:c==null?void 0:c.is_enabled,onCheckedChange:F=>b.mutate({is_enabled:F})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Cron Frequency"}),e.jsxs(Ds,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:F=>b.mutate({cron_frequency:F}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(lt,{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(ce,{children:"Day of Week"}),e.jsxs(Ds,{value:String(c==null?void 0:c.send_day),onValueChange:F=>b.mutate({send_day:parseInt(F)}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:OGs.map(F=>e.jsx(lt,{value:F.value,children:F.label},F.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Time (UTC)"}),e.jsxs(Ds,{value:String(c==null?void 0:c.send_hour),onValueChange:F=>b.mutate({send_hour:parseInt(F)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:FGs.map(F=>e.jsx(lt,{value:F.value,children:F.label},F.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{onClick:N,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(q,{onClick:j,disabled:r,className:"flex-1",children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),r?"Sending...":"Send to All"]})]}),_>0&&e.jsxs(q,{onClick:C,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(lo,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${_} Failed`]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Ur,{children:"Choose what to include in the digest"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ce,{children:"New Resources"})]}),e.jsx(Rr,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:F=>b.mutate({include_new_resources:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ce,{children:"Community Highlights"})]}),e.jsx(Rr,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:F=>b.mutate({include_community_posts:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ce,{children:"Agent OS Stats"})]}),e.jsx(Rr,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:F=>b.mutate({include_agent_os_stats:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ce,{children:"Upcoming Events"})]}),e.jsx(Rr,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:F=>b.mutate({include_upcoming_events:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hu,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ce,{children:"Goals Progress"})]}),e.jsx(Rr,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:F=>b.mutate({include_goals_progress:F})})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Custom Introduction"}),e.jsx(Ur,{children:"Personalize the intro message (optional)"})]}),e.jsx(Pe,{children:e.jsx(pr,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:F=>b.mutate({custom_intro_text:F.target.value||null}),rows:3})})]})]}),e.jsx(fs,{value:"stats",children:e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Ur,{children:"Recent digest emails sent to members"})]}),e.jsx(Pe,{children:m?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(F=>e.jsx("div",{className:"h-12 bg-muted rounded"},F))}):u&&u.length>0?e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Email"}),e.jsx(At,{children:"Sent At"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Resources"}),e.jsx(At,{children:"Agent OS"})]})}),e.jsx(ha,{children:u.map(F=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:F.email_sent_to}),e.jsx(xt,{children:As(new Date(F.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(xt,{children:e.jsx(Xe,{variant:F.delivery_status==="sent"?"default":"destructive",children:F.delivery_status})}),e.jsx(xt,{children:F.resources_count}),e.jsx(xt,{children:F.has_agent_os_activity?e.jsx(Xe,{variant:"secondary",children:"Active"}):e.jsx(Xe,{variant:"outline",children:"Not Started"})})]},F.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ks,{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 BGs={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 $Gs(){var je,xe,Ee;const s=is(),[t,r]=k.useState(""),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(!0),[_,b]=k.useState(!1),[j,N]=k.useState(""),[C,A]=k.useState(null),{data:E,isLoading:D}=pt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:Me,error:Oe}=await U.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(Oe)throw Oe;const Ie=(Me==null?void 0:Me.map(Le=>Le.user_id))||[],{data:ze}=await U.from("profiles").select("id, name, email").in("id",Ie),Ve=new Map((ze==null?void 0:ze.map(Le=>[Le.id,{name:Le.name,email:Le.email}]))||[]);return Me==null?void 0:Me.map(Le=>({...Le,profile:Ve.get(Le.user_id)||null}))}}),{data:R}=pt({queryKey:["all-profiles-for-points",E],queryFn:async()=>{const Oe=[];let Ie=0;for(;;){const{data:ze,error:Ve}=await U.from("profiles").select("id, name, email").order("name").range(Ie,Ie+1e3-1);if(Ve)throw Ve;if(Oe.push(...ze),!ze||ze.length<1e3)break;Ie+=1e3}return Oe}}),O=((R==null?void 0:R.filter(Me=>!(E!=null&&E.some(Oe=>Oe.user_id===Me.id))))||[]).filter(Me=>{var Ie,ze;if(!j)return!0;const Oe=j.toLowerCase();return((Ie=Me.name)==null?void 0:Ie.toLowerCase().includes(Oe))||((ze=Me.email)==null?void 0:ze.toLowerCase().includes(Oe))}),{data:B,isLoading:K}=pt({queryKey:["agent-point-history",n==null?void 0:n.user_id],queryFn:async()=>{if(!(n!=null&&n.user_id))return[];const{data:Me,error:Oe}=await U.from("agent_points").select("*").eq("user_id",n.user_id).order("created_at",{ascending:!1});if(Oe)throw Oe;return Me},enabled:!!(n!=null&&n.user_id)&&o}),{data:Z}=pt({queryKey:["agent-badges",n==null?void 0:n.user_id],queryFn:async()=>{if(!(n!=null&&n.user_id))return[];const{data:Me,error:Oe}=await U.from("agent_badges").select("*").eq("user_id",n.user_id).order("earned_at",{ascending:!1});if(Oe)throw Oe;return Me},enabled:!!(n!=null&&n.user_id)}),Q=Mt({mutationFn:async({userId:Me,points:Oe,reason:Ie})=>{const{error:ze}=await U.from("agent_points").insert({user_id:Me,points:Oe,reason:Ie});if(ze)throw ze;const{data:Ve}=await U.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",Me).maybeSingle(),Le=((Ve==null?void 0:Ve.total_points)||0)+Oe,$e=((Ve==null?void 0:Ve.spendable_points)||0)+Oe,{error:ve}=await U.from("agent_attendance_stats").upsert({user_id:Me,total_points:Math.max(0,Le),spendable_points:Math.max(0,$e),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(ve)throw ve},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),f(""),he.success(x?"Points awarded successfully!":"Points deducted successfully!")},onError:Me=>{console.error("Error modifying points:",Me),he.error("Failed to modify points")}}),W=()=>{if(!n||!d||!m){he.error("Please fill in all fields");return}const Me=parseInt(d);if(isNaN(Me)||Me<=0){he.error("Please enter a valid positive number");return}Q.mutate({userId:n.user_id,points:x?Me:-Me,reason:m})},te=()=>{if(!C||!d||!m){he.error("Please fill in all fields");return}const Me=parseInt(d);if(isNaN(Me)||Me<=0){he.error("Please enter a valid positive number");return}Q.mutate({userId:C.id,points:Me,reason:m},{onSuccess:()=>{b(!1),A(null),N("")}})},ne=(Me,Oe)=>{a(Me),y(Oe),l(!0)},ae=Me=>{a(Me),c(!0)},ue=E==null?void 0:E.filter(Me=>{var Ve,Le,$e,ve;const Oe=((Le=(Ve=Me.profile)==null?void 0:Ve.name)==null?void 0:Le.toLowerCase())||"",Ie=((ve=($e=Me.profile)==null?void 0:$e.email)==null?void 0:ve.toLowerCase())||"",ze=t.toLowerCase();return Oe.includes(ze)||Ie.includes(ze)}),me=(E==null?void 0:E.reduce((Me,Oe)=>Me+Oe.total_points,0))||0,de=(E==null?void 0:E.length)||0,fe=de>0?Math.round(me/de):0;return D?e.jsx(ws,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(dr,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(Me=>e.jsx(dr,{className:"h-24"},Me))}),e.jsx(dr,{className:"h-96"})]})}):e.jsx(ws,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Agent Points Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Track, view, and manage agent gamification points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Dr,{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:de}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wo,{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:me.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Wo,{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:fe}),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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:t,onChange:Me=>r(Me.target.value),className:"pl-10"})]}),e.jsxs(q,{onClick:()=>b(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Agent Leaderboard"}),e.jsx(Ur,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Pe,{children:!ue||ue.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(wo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-12",children:"#"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{className:"text-center",children:"Total Points"}),e.jsx(At,{className:"text-center",children:"Spendable"}),e.jsx(At,{className:"text-center",children:"Events"}),e.jsx(At,{className:"text-center",children:"Streak"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:ue.map((Me,Oe)=>{var Ie,ze,Ve,Le;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:Oe<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${Oe===0?"bg-yellow-100 text-yellow-700":Oe===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:Oe+1}):e.jsx("span",{className:"text-muted-foreground",children:Oe+1})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wn,{className:"h-8 w-8",children:e.jsx(Kn,{children:((ze=(Ie=Me.profile)==null?void 0:Ie.name)==null?void 0:ze.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Ve=Me.profile)==null?void 0:Ve.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Le=Me.profile)==null?void 0:Le.email})]})]})}),e.jsx(xt,{className:"text-center",children:e.jsxs(Xe,{variant:"secondary",className:"font-bold",children:[e.jsx(fa,{className:"h-3 w-3 mr-1"}),Me.total_points]})}),e.jsx(xt,{className:"text-center",children:e.jsxs(Xe,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Di,{className:"h-3 w-3 mr-1"}),Me.spendable_points||0]})}),e.jsx(xt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(vn,{className:"h-3 w-3 text-muted-foreground"}),Me.total_events_attended]})}),e.jsx(xt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ld,{className:"h-3 w-3 text-orange-500"}),Me.current_streak]})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>ne(Me,!0),title:"Award points",children:e.jsx(Ys,{className:"h-4 w-4 text-green-600"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>ne(Me,!1),title:"Deduct points",children:e.jsx(N_,{className:"h-4 w-4 text-red-600"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>ae(Me),title:"View history",children:e.jsx(ZI,{className:"h-4 w-4"})})]})})]},Me.user_id)})})]})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:x?"Award Points":"Deduct Points"}),e.jsxs(an,{children:[x?"Award":"Deduct"," points ",x?"to":"from"," ",((je=n==null?void 0:n.profile)==null?void 0:je.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"points",children:"Points Amount"}),e.jsx(Ne,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Me=>u(Me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"reason",children:"Reason"}),e.jsx(pr,{id:"reason",placeholder:"Enter reason for this adjustment...",value:m,onChange:Me=>f(Me.target.value)})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(q,{onClick:W,disabled:Q.isPending,className:x?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:Q.isPending?"Saving...":x?"Award Points":"Deduct Points"})]})]})}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(_s,{children:[e.jsxs(bs,{children:["Point History: ",(xe=n==null?void 0:n.profile)==null?void 0:xe.name]}),e.jsx(an,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(ta,{defaultValue:"history",className:"w-full",children:[e.jsxs(ea,{className:"grid w-full grid-cols-2",children:[e.jsx(rs,{value:"history",children:"Point History"}),e.jsx(rs,{value:"badges",children:"Badges"})]}),e.jsx(fs,{value:"history",className:"mt-4",children:K?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(Me=>e.jsx(dr,{className:"h-12"},Me))}):!B||B.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ZI,{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:B.map(Me=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:Me.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:As(new Date(Me.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Xe,{variant:Me.points>=0?"default":"destructive",className:Me.points>=0?"bg-green-100 text-green-800":"",children:[Me.points>=0?"+":"",Me.points]})]},Me.id))})}),e.jsx(fs,{value:"badges",className:"mt-4",children:!Z||Z.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Uc,{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(Me=>e.jsxs("div",{className:`p-3 rounded-lg ${BGs[Me.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Uc,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:Me.badge_name})]}),Me.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:Me.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",As(new Date(Me.earned_at),"MMM d, yyyy")]})]},Me.id))})})]})]})}),e.jsx(vs,{open:_,onOpenChange:Me=>{b(Me),Me||(A(null),N(""),u(""),f(""))},children:e.jsxs(ys,{className:"max-w-md",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Award Points to New Agent"}),e.jsx(an,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:C?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Wn,{className:"h-10 w-10",children:e.jsx(Kn,{children:((Ee=C.name)==null?void 0:Ee.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:C.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:C.email})]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>A(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(Ne,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Me=>u(Me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"new-reason",children:"Reason"}),e.jsx(pr,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:m,onChange:Me=>f(Me.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:j,onChange:Me=>N(Me.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:O.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Dr,{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"})]}):O.slice(0,20).map(Me=>{var Oe;return e.jsxs("button",{onClick:()=>A(Me),className:"w-full flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors border-b last:border-b-0 text-left",children:[e.jsx(Wn,{className:"h-8 w-8",children:e.jsx(Kn,{children:((Oe=Me.name)==null?void 0:Oe.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Me.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Me.email})]})]},Me.id)})})]})}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),C&&e.jsxs(q,{onClick:te,disabled:Q.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function UGs(){const{data:s,isLoading:t}=ODt(),[r,n]=k.useState(null),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState("all"),[u,m]=k.useState("newest"),[f,x]=k.useState("table"),y=k.useMemo(()=>(s==null?void 0:s.map(C=>C.user_id))||[],[s]),_=k.useMemo(()=>(s==null?void 0:s.map(C=>C.id))||[],[s]),{data:b}=pt({queryKey:["card-profiles-lookup",y],queryFn:async()=>{if(y.length===0)return{};const{data:C}=await U.from("profiles").select("id, name, email").in("id",y),A={};return C==null||C.forEach(E=>{A[E.id]={name:E.name||"",email:E.email||""}}),A},enabled:y.length>0}),{data:j}=pt({queryKey:["card-stats-all",_],queryFn:async()=>{if(_.length===0)return{};const C={};_.forEach(D=>{C[D]={views:0,leads:0}});const{data:A}=await U.from("agent_card_interactions").select("card_id").in("card_id",_).eq("interaction_type","card_view");A==null||A.forEach(D=>{C[D.card_id]&&C[D.card_id].views++});const{data:E}=await U.from("agent_card_leads").select("card_id").in("card_id",_);return E==null||E.forEach(D=>{C[D.card_id]&&C[D.card_id].leads++}),C},enabled:_.length>0}),N=k.useMemo(()=>{if(!s)return[];let C=[...s];if(c==="live"?C=C.filter(A=>A.is_published):c==="draft"&&(C=C.filter(A=>!A.is_published)),l.trim()){const A=l.toLowerCase();C=C.filter(E=>{var R,F;const D=b==null?void 0:b[E.user_id];return E.slug.toLowerCase().includes(A)||((R=D==null?void 0:D.name)==null?void 0:R.toLowerCase().includes(A))||((F=D==null?void 0:D.email)==null?void 0:F.toLowerCase().includes(A))})}return u==="newest"?C.sort((A,E)=>new Date(E.created_at).getTime()-new Date(A.created_at).getTime()):u==="oldest"?C.sort((A,E)=>new Date(A.created_at).getTime()-new Date(E.created_at).getTime()):u==="name"?C.sort((A,E)=>{var D,R;return(((D=b==null?void 0:b[A.user_id])==null?void 0:D.name)||"").localeCompare(((R=b==null?void 0:b[E.user_id])==null?void 0:R.name)||"")}):u==="slug"?C.sort((A,E)=>A.slug.localeCompare(E.slug)):u==="views_desc"?C.sort((A,E)=>{var D,R;return(((D=j==null?void 0:j[E.id])==null?void 0:D.views)||0)-(((R=j==null?void 0:j[A.id])==null?void 0:R.views)||0)}):u==="views_asc"?C.sort((A,E)=>{var D,R;return(((D=j==null?void 0:j[A.id])==null?void 0:D.views)||0)-(((R=j==null?void 0:j[E.id])==null?void 0:R.views)||0)}):u==="leads_desc"?C.sort((A,E)=>{var D,R;return(((D=j==null?void 0:j[E.id])==null?void 0:D.leads)||0)-(((R=j==null?void 0:j[A.id])==null?void 0:R.leads)||0)}):u==="leads_asc"&&C.sort((A,E)=>{var D,R;return(((D=j==null?void 0:j[A.id])==null?void 0:D.leads)||0)-(((R=j==null?void 0:j[E.id])==null?void 0:R.leads)||0)}),C},[s,c,l,u,b]);return e.jsxs(ws,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs(q,{onClick:()=>i(!0),children:[e.jsx(Ys,{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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or slug...",value:l,onChange:C=>o(C.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:c,onValueChange:d,children:[e.jsx(Ps,{className:"w-full sm:w-36",children:e.jsx(Fs,{placeholder:"Status"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All Status"}),e.jsx(lt,{value:"live",children:"Live"}),e.jsx(lt,{value:"draft",children:"Draft"})]})]}),e.jsxs(Ds,{value:u,onValueChange:m,children:[e.jsx(Ps,{className:"w-full sm:w-44",children:e.jsx(Fs,{placeholder:"Sort by"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"newest",children:"Newest First"}),e.jsx(lt,{value:"oldest",children:"Oldest First"}),e.jsx(lt,{value:"name",children:"Name A–Z"}),e.jsx(lt,{value:"slug",children:"Slug A–Z"}),e.jsx(lt,{value:"views_desc",children:"Most Views"}),e.jsx(lt,{value:"views_asc",children:"Fewest Views"}),e.jsx(lt,{value:"leads_desc",children:"Most Leads"}),e.jsx(lt,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(q,{variant:f==="table"?"default":"ghost",size:"sm",onClick:()=>x("table"),className:"rounded-r-none",children:e.jsx(iP,{className:"h-4 w-4"})}),e.jsx(q,{variant:f==="grid"?"default":"ghost",size:"sm",onClick:()=>x("grid"),className:"rounded-l-none",children:e.jsx(Ep,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",N.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(C=>e.jsx(dr,{className:"h-48"},C))}):N.length>0?f==="table"?e.jsx(qGs,{cards:N,cardProfiles:b,cardStats:j,onEdit:n,sortBy:u,setSortBy:m}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:N.map(C=>e.jsx(VGs,{card:C,onEdit:()=>n(C),stats:j==null?void 0:j[C.id]},C.id))}):s&&s.length>0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(_n,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Dr,{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(q,{onClick:()=>i(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(HGs,{open:a,onOpenChange:i}),r&&e.jsx(GGs,{card:r,open:!!r,onOpenChange:C=>!C&&n(null)})]})}function qGs({cards:s,cardProfiles:t,cardStats:r,onEdit:n,sortBy:a,setSortBy:i}){const l=c=>{a===`${c}_desc`?i(`${c}_asc`):i(`${c}_desc`)},o=({field:c})=>a===`${c}_desc`?e.jsx(gm,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(qu,{className:"h-3 w-3"}):e.jsx(Uu,{className:"h-3 w-3 opacity-40"});return e.jsx(ke,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"text-left p-3 font-medium",children:e.jsxs("button",{onClick:()=>{i(a==="name"?"newest":"name")},className:"flex items-center gap-1 hover:text-foreground text-muted-foreground",children:["Agent ",a==="name"&&e.jsx(qu,{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=r==null?void 0:r[c.id],m=`https://cards.relevelup.com/${c.slug}`;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:(d==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.email)||""})]})}),e.jsx("td",{className:"p-3 hidden md:table-cell",children:e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",c.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx(Xe,{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(q,{variant:"ghost",size:"sm",onClick:()=>n(c),className:"h-8 w-8 p-0",children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(m),he.success("Link copied!")},children:e.jsx(si,{className:"h-3.5 w-3.5"})}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",children:e.jsx(un,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function VGs({card:s,onEdit:t,stats:r}){const[n,a]=k.useState(null);k.useEffect(()=>{(async()=>{const{data:c}=await U.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await U.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:m}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=m.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),he.success("Link copied!")};return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:(n==null?void 0:n.avatar_url)||void 0}),e.jsx(Kn,{children:((n==null?void 0:n.name)||"U")[0]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold truncate",children:(n==null?void 0:n.name)||"Loading..."}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["/card/",s.slug]})]}),e.jsx(Xe,{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(Nn,{className:"h-3.5 w-3.5"}),(r==null?void 0:r.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Dr,{className:"h-3.5 w-3.5"}),(r==null?void 0:r.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(q,{variant:"outline",size:"sm",onClick:l,children:e.jsx(si,{className:"h-3 w-3"})}),e.jsx(q,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(un,{className:"h-3 w-3"})})})]})]})})}function HGs({open:s,onOpenChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(!1),u=Knt(),m=l.trim(),{data:f}=pt({queryKey:["profiles-search-for-cards",m],queryFn:async()=>{let N=U.from("profiles").select("id, name, email").order("name").limit(50);m.length>=2&&(N=N.or(`name.ilike.%${m}%,email.ilike.%${m}%`));const{data:C}=await N;return C||[]},enabled:s}),[x,y]=k.useState(null),_=(f==null?void 0:f.find(N=>N.id===r))||x,b=()=>{if(!r||!a.trim()){he.error("Select an agent and enter a slug");return}u.mutate({user_id:r,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),n(""),i(""),o("")}})},j=N=>{var A;n(N),d(!1);const C=f==null?void 0:f.find(E=>E.id===N);C&&(y(C),i(((A=C.name)==null?void 0:A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create Agent Card"}),e.jsx(an,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Agent"}),e.jsxs(sl,{open:c,onOpenChange:d,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[_?`${_.name} (${_.email})`:"Search for an agent...",e.jsx(xg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(jg,{shouldFilter:!1,children:[e.jsx(Ng,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(kg,{children:[e.jsx(Sg,{children:"No agents found."}),e.jsx(Cg,{children:(f||[]).map(N=>e.jsxs(Sp,{value:N.id,onSelect:j,children:[e.jsx(la,{className:zt("mr-2 h-4 w-4",r===N.id?"opacity-100":"opacity-0")}),N.name," (",N.email,")"]},N.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"URL Slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/card/"}),e.jsx(Ne,{value:a,onChange:N=>i(N.target.value),placeholder:"john-doe"})]})]}),e.jsx(q,{onClick:b,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function GGs({card:s,open:t,onOpenChange:r}){const n=Ynt(),{data:a}=Znt(s.id),i=is(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,m]=k.useState(!1),[f,x]=k.useState(""),[y,_]=k.useState(s.slug),[b,j]=k.useState(!1),[N,C]=k.useState({is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",custom_cta_url:s.custom_cta_url||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56});k.useEffect(()=>{t&&(async()=>{try{const{data:B}=await U.storage.from("avatars").list(`${s.user_id}`);if(B&&B.length>0){const{data:K}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${B[0].name}`);o(`${K.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const A=O=>{var Z;const B=(Z=O.target.files)==null?void 0:Z[0];if(!B)return;if(!B.type.startsWith("image/")){he.error("Please select an image file");return}if(B.size>5*1024*1024){he.error("Image must be under 5MB");return}const K=new FileReader;K.onloadend=()=>{x(K.result),m(!0)},K.readAsDataURL(B),O.target.value=""},E=async O=>{d(!0);try{const{data:B}=await U.storage.from("avatars").list(`${s.user_id}`);B&&B.length>0&&await U.storage.from("avatars").remove(B.map(te=>`${s.user_id}/${te.name}`));const K=`${s.user_id}/avatar.jpg`,{error:Z}=await U.storage.from("avatars").upload(K,O,{upsert:!0,contentType:"image/jpeg"});if(Z)throw Z;const{data:Q}=U.storage.from("avatars").getPublicUrl(K),W=`${Q.publicUrl}?t=${Date.now()}`;o(W),await U.from("profiles").update({avatar_url:W}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),he.success("Photo updated!")}catch(B){he.error(B.message||"Upload failed")}finally{d(!1)}},D=async()=>{const O=y.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!O){he.error("Please enter a valid URL");return}if(O===s.slug){he.info("No changes to save");return}j(!0);try{const{data:B}=await U.from("agent_cards").select("id").eq("slug",O).neq("id",s.id).maybeSingle();if(B){he.error("This URL is already taken. Try another one.");return}const{error:K}=await U.from("agent_cards").update({slug:O}).eq("id",s.id);if(K)throw K;_(O),i.invalidateQueries({queryKey:["agent-cards-admin"]}),he.success("Card address updated!")}catch{he.error("Failed to update card address")}finally{j(!1)}},R=async(O,B)=>{var Z;const K=(Z=O.target.files)==null?void 0:Z[0];if(K){if(!K.type.startsWith("image/")){he.error("Please select an image file");return}try{const Q=K.name.split(".").pop()||"png",W=B==="brokerage_logo_url"?"brokerage-logo":"team-logo",te=`${s.user_id}/${W}.${Q}`,{error:ne}=await U.storage.from("card-logos").upload(te,K,{upsert:!0});if(ne)throw ne;const{data:ae}=U.storage.from("card-logos").getPublicUrl(te),ue=ae.publicUrl+"?t="+Date.now();C(B==="brokerage_logo_url"?me=>({...me,[B]:ue,brokerage_display_name:""}):me=>({...me,[B]:ue,team_name:""})),he.success("Logo uploaded!")}catch{he.error("Failed to upload logo")}finally{O.target.value=""}}},F=()=>{n.mutate({id:s.id,...N,title:N.title||null,positioning_statement:N.positioning_statement||null,bio:N.bio||null,review_snippet:N.review_snippet||null,review_source_url:N.review_source_url||null,booking_url:N.booking_url||null,custom_cta_label:N.custom_cta_label||null,custom_cta_url:N.custom_cta_url||null,brokerage_display_name:N.brokerage_display_name||null,brokerage_logo_url:N.brokerage_logo_url||null,brokerage_logo_size:N.brokerage_logo_size,team_name:N.team_name||null,team_logo_url:N.team_logo_url||null,team_logo_size:N.team_logo_size},{onSuccess:()=>r(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(vs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Edit Agent Card"}),e.jsxs(an,{children:["/card/",s.slug]})]}),e.jsxs(ta,{defaultValue:"content",children:[e.jsxs(ea,{className:"w-full",children:[e.jsx(rs,{value:"content",className:"flex-1",children:"Content"}),e.jsx(rs,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(rs,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(rs,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(fs,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Published"}),e.jsx(Rr,{checked:N.is_published,onCheckedChange:O=>C(B=>({...B,is_published:O}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Wn,{className:"h-16 w-16",children:[e.jsx(Xa,{src:l||void 0}),e.jsx(Kn,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:A,disabled:c}),e.jsx(q,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(Ne,{value:y,onChange:O=>_(O.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(q,{variant:"outline",size:"sm",onClick:D,disabled:b||y===s.slug,className:"shrink-0",children:b?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Theme"}),e.jsxs(Ds,{value:N.theme,onValueChange:O=>C(B=>({...B,theme:O})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(lt,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(lt,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(lt,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Title / Tagline"}),e.jsx(Ne,{value:N.title,onChange:O=>C(B=>({...B,title:O.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(ce,{children:"Positioning Statement"}),e.jsx(Ne,{value:N.positioning_statement,onChange:O=>C(B=>({...B,positioning_statement:O.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Bio"}),e.jsx(pr,{value:N.bio,onChange:O=>C(B=>({...B,bio:O.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Review Snippet"}),e.jsx(Ne,{value:N.review_snippet,onChange:O=>C(B=>({...B,review_snippet:O.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Review Source URL"}),e.jsx(Ne,{value:N.review_source_url,onChange:O=>C(B=>({...B,review_source_url:O.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(Ne,{value:N.booking_url,onChange:O=>C(B=>({...B,booking_url:O.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Custom CTA Label (optional)"}),e.jsx(Ne,{value:N.custom_cta_label,onChange:O=>C(B=>({...B,custom_cta_label:O.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Custom CTA URL (optional)"}),e.jsx(Ne,{value:N.custom_cta_url,onChange:O=>C(B=>({...B,custom_cta_url:O.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(ce,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ne,{value:N.brokerage_display_name,onChange:O=>C(B=>({...B,brokerage_display_name:O.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!N.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[N.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:N.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${N.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>C(O=>({...O,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(ka,{className:"h-3.5 w-3.5"}),N.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:O=>R(O,"brokerage_logo_url")})]})]}),N.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[N.brokerage_logo_size||56,"px"]})]}),e.jsx(nf,{value:[N.brokerage_logo_size||56],onValueChange:([O])=>C(B=>({...B,brokerage_logo_size:O})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ce,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ne,{value:N.team_name,onChange:O=>C(B=>({...B,team_name:O.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!N.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[N.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:N.team_logo_url,alt:"Team logo",style:{height:`${N.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>C(O=>({...O,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(ka,{className:"h-3.5 w-3.5"}),N.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:O=>R(O,"team_logo_url")})]})]}),N.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[N.team_logo_size||56,"px"]})]}),e.jsx(nf,{value:[N.team_logo_size||56],onValueChange:([O])=>C(B=>({...B,team_logo_size:O})),min:24,max:120,step:4})]})]})]})]}),e.jsx(fs,{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:O,label:B,hint:K})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(ce,{children:B}),K&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[K," ",O==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(Rr,{checked:N[O],onCheckedChange:Z=>C(Q=>({...Q,[O]:Z}))})]},O))}),e.jsx(fs,{value:"blocks",className:"mt-4",children:e.jsx(H1t,{cardId:s.id})}),e.jsx(fs,{value:"analytics",className:"mt-4",children:a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.views}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.clicks}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clicks"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.leads.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Leads"})]})})]}),a.leads.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Recent Leads"}),e.jsx("div",{className:"space-y-2",children:a.leads.slice(0,5).map(O=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:O.name}),O.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",O.phone]}),O.intent&&e.jsx(Xe,{variant:"secondary",className:"ml-2 text-xs",children:O.intent})]},O.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(q,{onClick:F,disabled:n.isPending,className:"w-full mt-4",children:n.isPending?"Saving...":"Save Changes"})]})}),e.jsx(fAe,{open:u,onClose:()=>m(!1),imageSrc:f,onCropComplete:E,aspectRatio:1})]})}const DP={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"},pIe={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 xIe(s=!0){return pt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=U.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:r,error:n}=await t;if(n)throw n;return r}})}function WGs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("marketplace_categories").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),he.success("Category created successfully")},onError:t=>{he.error("Failed to create category: "+t.message)}})}function KGs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("marketplace_categories").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),he.success("Category updated successfully")},onError:t=>{he.error("Failed to update category: "+t.message)}})}function YGs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("marketplace_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),he.success("Category deleted successfully")},onError:t=>{he.error("Failed to delete category: "+t.message)}})}function obt(s,t=!0){return pt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let r=U.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(r=r.eq("category_id",s)),t&&(r=r.eq("is_active",!0));const{data:n,error:a}=await r;if(a)throw a;return n}})}function ZGs(s){return pt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:r}=await U.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function XGs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("marketplace_products").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),he.success("Product created successfully")},onError:t=>{he.error("Failed to create product: "+t.message)}})}function QGs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("marketplace_products").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.id]}),he.success("Product updated successfully")},onError:t=>{he.error("Failed to update product: "+t.message)}})}function JGs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("marketplace_products").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),he.success("Product deleted successfully")},onError:t=>{he.error("Failed to delete product: "+t.message)}})}function eWs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("marketplace_product_images").insert([t]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.product_id]})}})}function tWs(){const s=is();return Mt({mutationFn:async({id:t,productId:r})=>{const{error:n}=await U.from("marketplace_product_images").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),he.success("Image deleted successfully")},onError:t=>{he.error("Failed to delete image: "+t.message)}})}function sWs(){const s=is();return Mt({mutationFn:async({imageId:t,productId:r})=>{const{error:n}=await U.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",r);if(n)throw n;const{error:a}=await U.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),he.success("Primary image updated")},onError:t=>{he.error("Failed to set primary image: "+t.message)}})}function rWs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("marketplace_product_variants").insert([t]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.product_id]}),he.success("Variant added successfully")}})}function nWs(){const s=is();return Mt({mutationFn:async({id:t,productId:r})=>{const{error:n}=await U.from("marketplace_product_variants").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),he.success("Variant deleted successfully")}})}function aWs(){const s=is();return Mt({mutationFn:async({productId:t,videoUrl:r})=>{await U.from("marketplace_product_videos").delete().eq("product_id",t);const{data:n,error:a}=await U.from("marketplace_product_videos").insert({product_id:t,video_url:r}).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.productId]}),he.success("Video updated successfully")}})}function iWs(s){const{isAdmin:t}=Cs();return pt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let r=U.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:n,error:a}=await r;if(a)throw a;if(t&&n){const i=[...new Set(n.map(c=>c.user_id))],{data:l}=await U.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return n.map(c=>({...c,user:o.get(c.user_id)}))}return n}})}function oWs(){const{user:s}=Cs();return pt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await U.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function lWs(s){return pt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:r}=await U.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function cWs(){const s=is(),{user:t}=Cs();return Mt({mutationFn:async({orderId:r,status:n,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:n};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await U.from("marketplace_orders").update(c).eq("id",r);if(d)throw d;const{error:u}=await U.from("marketplace_order_status_history").insert({order_id:r,status:n,notes:a,created_by:t==null?void 0:t.id});if(u)throw u;if(["shipped","in_production","processing","completed"].includes(n)&&n!==o)try{await U.functions.invoke("marketplace-order-notify",{body:{orderId:r,notificationType:n==="shipped"?"shipped":"status_update",newStatus:n,trackingNumber:i,trackingUrl:l}})}catch(f){console.error("Failed to send notification email:",f)}},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",n.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),he.success("Order status updated")},onError:r=>{he.error("Failed to update order: "+r.message)}})}function dWs(){const s=is();return Mt({mutationFn:async({itemId:t,proofUrl:r,proofNotes:n,orderId:a})=>{const{error:i}=await U.from("marketplace_order_items").update({proof_url:r,proof_notes:n,proof_status:"pending"}).eq("id",t);if(i)throw i;await U.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await U.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),he.success("Proof uploaded & customer notified")}})}function uWs(){const s=is();return Mt({mutationFn:async({itemId:t,orderId:r})=>{const{error:n}=await U.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),he.success("Proof approved")}})}function hWs(){const s=is();return Mt({mutationFn:async({itemId:t,orderId:r,reason:n})=>{const{error:a}=await U.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),he.success("Proof rejected - please upload a new proof")}})}function mWs(){const{data:s,isLoading:t}=xIe(!1),r=WGs(),n=KGs(),a=YGs(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),m=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},f=_=>{c(_),u({name:_.name,description:_.description||"",image_url:_.image_url||"",sort_order:_.sort_order,is_active:_.is_active}),l(!0)},x=async _=>{_.preventDefault(),o?await n.mutateAsync({id:o.id,...d}):await r.mutateAsync(d),l(!1),m()},y=async _=>{confirm("Are you sure you want to delete this category?")&&await a.mutateAsync(_)};return t?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(dr,{className:"h-8 w-48"})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(_=>e.jsx(dr,{className:"h-12 w-full"},_))})})]}):e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{children:"Categories"}),e.jsxs(vs,{open:i,onOpenChange:_=>{l(_),_||m()},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",value:d.name,onChange:_=>u({...d,name:_.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",value:d.description,onChange:_=>u({...d,description:_.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"image_url",children:"Image URL"}),e.jsx(Ne,{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(ce,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(Ne,{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(Rr,{id:"is_active",checked:d.is_active,onCheckedChange:_=>u({...d,is_active:_})}),e.jsx(ce,{htmlFor:"is_active",children:"Active"})]}),e.jsx(q,{type:"submit",className:"w-full",disabled:r.isPending||n.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Pe,{children:s&&s.length>0?e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{children:"Sort Order"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:s.map(_=>e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium",children:_.name}),e.jsx(xt,{className:"max-w-xs truncate",children:_.description}),e.jsx(xt,{children:_.sort_order}),e.jsx(xt,{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(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>f(_),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>y(_.id),disabled:a.isPending,children:e.jsx(zr,{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 fWs(){var fe,je;const{data:s,isLoading:t}=obt(void 0,!1),{data:r}=xIe(!1),n=XGs(),a=QGs(),i=JGs(),l=eWs(),o=tWs(),c=sWs(),d=rWs(),u=nWs(),m=aWs(),[f,x]=k.useState(!1),[y,_]=k.useState(!1),[b,j]=k.useState(!1),[N,C]=k.useState(null),[A,E]=k.useState(null),[D,R]=k.useState(!1),[F,O]=k.useState({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),[B,K]=k.useState({name:"",price_adjustment:0}),[Z,Q]=k.useState(""),W=()=>{O({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),C(null)},te=xe=>{C(xe),O({name:xe.name,description:xe.description||"",base_price:Number(xe.base_price),shipping_fee:Number(xe.shipping_fee),category_id:xe.category_id||"",allow_artwork_upload:xe.allow_artwork_upload,requires_proof_approval:xe.requires_proof_approval,is_active:xe.is_active,sort_order:xe.sort_order}),x(!0)},ne=async xe=>{xe.preventDefault();const Ee={...F,category_id:F.category_id||null};N?await a.mutateAsync({id:N.id,...Ee}):await n.mutateAsync(Ee),x(!1),W()},ae=async xe=>{confirm("Are you sure you want to delete this product?")&&await i.mutateAsync(xe)},ue=async xe=>{if(!A||!xe.target.files||xe.target.files.length===0)return;R(!0);const Ee=xe.target.files[0],Me=Ee.name.split(".").pop(),Oe=`products/${A.id}/${Date.now()}.${Me}`;try{const{error:Ie}=await U.storage.from("marketplace").upload(Oe,Ee);if(Ie)throw Ie;const{data:{publicUrl:ze}}=U.storage.from("marketplace").getPublicUrl(Oe);await l.mutateAsync({product_id:A.id,image_url:ze,is_primary:!A.images||A.images.length===0}),he.success("Image uploaded successfully")}catch(Ie){he.error("Failed to upload image: "+Ie.message)}finally{R(!1)}},me=async xe=>{xe.preventDefault(),A&&(await d.mutateAsync({product_id:A.id,name:B.name,price_adjustment:B.price_adjustment}),K({name:"",price_adjustment:0}))},de=async()=>{!A||!Z||(await m.mutateAsync({productId:A.id,videoUrl:Z}),Q(""))};return t?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(dr,{className:"h-8 w-48"})}),e.jsx(Pe,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(xe=>e.jsx(dr,{className:"h-64 w-full"},xe))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{children:"Products"}),e.jsxs(vs,{open:f,onOpenChange:xe=>{x(xe),xe||W()},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:N?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:ne,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"name",children:"Product Name"}),e.jsx(Ne,{id:"name",value:F.name,onChange:xe=>O({...F,name:xe.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"category",children:"Category"}),e.jsxs(Ds,{value:F.category_id,onValueChange:xe=>O({...F,category_id:xe}),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select category"})}),e.jsx(Ls,{children:r==null?void 0:r.map(xe=>e.jsx(lt,{value:xe.id,children:xe.name},xe.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"description",children:"Description"}),e.jsx(pr,{id:"description",value:F.description,onChange:xe=>O({...F,description:xe.target.value}),rows:4})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(Ne,{id:"base_price",type:"number",step:"0.01",min:"0",value:F.base_price,onChange:xe=>O({...F,base_price:parseFloat(xe.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(Ne,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:F.shipping_fee,onChange:xe=>O({...F,shipping_fee:parseFloat(xe.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(Ne,{id:"sort_order",type:"number",value:F.sort_order,onChange:xe=>O({...F,sort_order:parseInt(xe.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{id:"allow_artwork_upload",checked:F.allow_artwork_upload,onCheckedChange:xe=>O({...F,allow_artwork_upload:xe})}),e.jsx(ce,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{id:"requires_proof_approval",checked:F.requires_proof_approval,onCheckedChange:xe=>O({...F,requires_proof_approval:xe})}),e.jsx(ce,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{id:"is_active",checked:F.is_active,onCheckedChange:xe=>O({...F,is_active:xe})}),e.jsx(ce,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(q,{type:"submit",className:"w-full",disabled:n.isPending||a.isPending,children:N?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Pe,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(xe=>{var Ee,Me;return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[xe.images&&xe.images.length>0?e.jsx("img",{src:((Ee=xe.images.find(Oe=>Oe.is_primary))==null?void 0:Ee.image_url)||xe.images[0].image_url,alt:xe.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No image"}),!xe.is_active&&e.jsx(Xe,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Pe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:xe.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((Me=xe.category)==null?void 0:Me.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(xe.base_price).toFixed(2)]}),Number(xe.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(xe.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[xe.allow_artwork_upload&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),xe.requires_proof_approval&&e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Proof Required"}),xe.variants&&xe.variants.length>0&&e.jsxs(Xe,{variant:"outline",className:"text-xs",children:[xe.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>te(xe),children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>{E(xe),_(!0)},children:[e.jsx(Qy,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>{E(xe),j(!0)},children:[e.jsx(Fh,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>ae(xe.id),children:e.jsx(zr,{className:"h-3 w-3 text-destructive"})})]})]})]},xe.id)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No products yet. Create your first product to get started."})})]}),e.jsx(vs,{open:y,onOpenChange:_,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsxs(bs,{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:(fe=A==null?void 0:A.images)==null?void 0:fe.map(xe=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:xe.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),xe.is_primary&&e.jsx(Xe,{className:"absolute top-2 left-2",variant:"default",children:"Primary"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[!xe.is_primary&&e.jsx(q,{variant:"secondary",size:"icon",onClick:async()=>{var Ee;await c.mutateAsync({imageId:xe.id,productId:A.id}),E({...A,images:(Ee=A.images)==null?void 0:Ee.map(Me=>({...Me,is_primary:Me.id===xe.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(fa,{className:"h-4 w-4"})}),e.jsx(q,{variant:"destructive",size:"icon",onClick:async()=>{var Me;await o.mutateAsync({id:xe.id,productId:A.id});const Ee=s==null?void 0:s.find(Oe=>Oe.id===A.id);Ee&&E({...Ee,images:(Me=Ee.images)==null?void 0:Me.filter(Oe=>Oe.id!==xe.id)})},disabled:o.isPending,children:e.jsx(zr,{className:"h-4 w-4"})})]})]},xe.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ue,className:"hidden",id:"image-upload",disabled:D}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(Qy,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(ce,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(Ne,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:Z,onChange:xe=>Q(xe.target.value)}),e.jsxs(q,{onClick:de,disabled:!Z,children:[e.jsx(bn,{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(vs,{open:b,onOpenChange:j,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsxs(bs,{children:["Manage Variants - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:me,className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Variant name (e.g., 500 count)",value:B.name,onChange:xe=>K({...B,name:xe.target.value}),required:!0}),e.jsx(Ne,{type:"number",step:"0.01",placeholder:"Price adj.",value:B.price_adjustment,onChange:xe=>K({...B,price_adjustment:parseFloat(xe.target.value)||0}),className:"w-32"}),e.jsx(q,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(je=A==null?void 0:A.variants)==null?void 0:je.map(xe=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:xe.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(xe.price_adjustment)>=0?"+":"","$",Number(xe.price_adjustment).toFixed(2)]})]}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:xe.id,productId:A.id}),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]},xe.id)),(!(A!=null&&A.variants)||A.variants.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No variants yet. Add variants like "250 count", "500 count", etc.'})]})]})]})})]})}const pWs=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function xWs(){var _,b,j;const{data:s,isLoading:t}=iWs(),r=cWs(),n=dWs(),[a,i]=k.useState(null),[l,o]=k.useState(!1),[c,d]=k.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,m]=k.useState(!1),f=N=>{i(N),d({status:N.status,notes:"",trackingNumber:N.tracking_number||"",trackingUrl:N.tracking_url||""}),o(!0)},x=async()=>{a&&(await r.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},y=async(N,C)=>{if(!a||!N.target.files||N.target.files.length===0)return;m(!0);const A=N.target.files[0],E=A.name.split(".").pop(),D=`proofs/${a.id}/${C}/${Date.now()}.${E}`;try{const{error:R}=await U.storage.from("marketplace").upload(D,A);if(R)throw R;const{data:{publicUrl:F}}=U.storage.from("marketplace").getPublicUrl(D);await n.mutateAsync({itemId:C,proofUrl:F,orderId:a.id}),he.success("Proof uploaded successfully")}catch(R){he.error("Failed to upload proof: "+R.message)}finally{m(!1)}};return t?e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(dr,{className:"h-8 w-48"})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(N=>e.jsx(dr,{className:"h-16 w-full"},N))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Orders"})}),e.jsx(Pe,{children:s&&s.length>0?e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Order #"}),e.jsx(At,{children:"Customer"}),e.jsx(At,{children:"Date"}),e.jsx(At,{children:"Total"}),e.jsx(At,{children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:s.map(N=>{var C,A;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-mono",children:N.order_number}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((C=N.user)==null?void 0:C.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(A=N.user)==null?void 0:A.email})]})}),e.jsx(xt,{children:As(new Date(N.created_at),"MMM d, yyyy")}),e.jsxs(xt,{className:"font-bold",children:["$",Number(N.total).toFixed(2)]}),e.jsx(xt,{children:e.jsx(Xe,{className:pIe[N.status],children:DP[N.status]})}),e.jsx(xt,{className:"text-right",children:e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>f(N),children:[e.jsx(Nn,{className:"h-4 w-4 mr-1"}),"View"]})})]},N.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(vs,{open:l,onOpenChange:o,children:e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsxs(bs,{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:(b=a.user)==null?void 0:b.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(j=a.items)==null?void 0:j.map(N=>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:N.product_name}),N.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:N.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(N.unit_price).toFixed(2)," x ",N.quantity]})]}),N.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:N.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(Xe,{variant:N.proof_status==="approved"?"default":"secondary",children:N.proof_status||"No proof yet"})]}),N.proof_url?e.jsx("a",{href:N.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:C=>y(C,N.id),className:"hidden",id:`proof-${N.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${N.id}`,children:e.jsx(q,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},N.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(ce,{children:"Status"}),e.jsxs(Ds,{value:c.status,onValueChange:N=>d({...c,status:N}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:pWs.map(N=>e.jsx(lt,{value:N,children:DP[N]},N))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Tracking Number"}),e.jsx(Ne,{value:c.trackingNumber,onChange:N=>d({...c,trackingNumber:N.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Tracking URL"}),e.jsx(Ne,{value:c.trackingUrl,onChange:N=>d({...c,trackingUrl:N.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Notes (optional)"}),e.jsx(pr,{value:c.notes,onChange:N=>d({...c,notes:N.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(q,{onClick:x,disabled:r.isPending,className:"w-full",children:[e.jsx(yc,{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(N=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(Xe,{variant:"outline",children:DP[N.status]}),N.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:N.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:As(new Date(N.created_at),"MMM d, h:mm a")})]},N.id))})]})]})]})})]})}function gWs(){const[s,t]=k.useState("products"),r=qr();return e.jsx(ws,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs(q,{variant:"outline",onClick:()=>r("/marketplace"),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(ta,{value:s,onValueChange:t,children:[e.jsxs(ea,{className:"grid w-full grid-cols-3",children:[e.jsxs(rs,{value:"products",className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"}),"Products"]}),e.jsxs(rs,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(Kf,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(rs,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(lg,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(fs,{value:"products",children:e.jsx(fWs,{})}),e.jsx(fs,{value:"categories",children:e.jsx(mWs,{})}),e.jsx(fs,{value:"orders",children:e.jsx(xWs,{})})]})]})})}function lbt(){return pt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await U.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function yWs(s){return pt({queryKey:["reward-items",s],queryFn:async()=>{let t=U.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:r,error:n}=await t;if(n)throw n;return r}})}function vWs(s){return pt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=U.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:r,error:n}=await t;if(n)throw n;return r}})}function bWs(s){return pt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function _Ws(){return pt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await U.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const r=[...new Set(s.map(l=>l.user_id))],{data:n,error:a}=await U.from("profiles").select("id, name, email").in("id",r);if(a)throw a;const i=new Map((n==null?void 0:n.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function wWs(s){return pt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:r}=await U.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(r&&r.code!=="PGRST116")throw r;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function jWs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.rpc("purchase_reward_item",{p_item_id:t});if(n)throw n;const a=r;if(!a.success)throw new Error(a.error||"Purchase failed");return a},onSuccess:()=>{s.invalidateQueries({queryKey:["user-purchases"]}),s.invalidateQueries({queryKey:["spendable-points"]}),s.invalidateQueries({queryKey:["active-reward-items"]}),s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["homereel-credits"]})}})}function NWs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("reward_store_categories").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function kWs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("reward_store_categories").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function SWs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("reward_store_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function CWs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("reward_store_items").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function TWs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("reward_store_items").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function EWs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("reward_store_items").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function AWs(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function _je(s,t){const r=AWs(s);if(r)try{const{data:n,error:a}=await U.storage.from(r.bucket).download(r.path);if(a){console.error("Error downloading file:",a),he.error("Failed to download file");return}const i=URL.createObjectURL(n),l=document.createElement("a");l.href=i,l.download=t||r.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(n){console.error("Download error:",n),he.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(n){console.error("External download error:",n),he.error("Failed to download file")}}function cbt(){return pt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await U.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function MWs(){const s=is();return Mt({mutationFn:async({id:t,points:r,is_active:n})=>{const a={points:r};n!==void 0&&(a.is_active=n);const{data:i,error:l}=await U.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function IWs(){const{user:s}=Cs(),[t,r]=k.useState("items"),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(null),[_,b]=k.useState(!1),[j,N]=k.useState(null),[C,A]=k.useState(""),[E,D]=k.useState(""),[R,F]=k.useState(null),[O,B]=k.useState(""),[K,Z]=k.useState("file"),[Q,W]=k.useState(""),[te,ne]=k.useState(""),[ae,ue]=k.useState(""),[me,de]=k.useState(!0),[fe,je]=k.useState(null),[xe,Ee]=k.useState(!1),[Me,Oe]=k.useState(!1),Ie=k.useRef(null),ze=k.useRef(null),{data:Ve,isLoading:Le}=lbt(),{data:$e,isLoading:ve}=yWs(),{data:Qe,isLoading:we}=_Ws(),{data:nt,isLoading:Se}=cbt(),Ge=NWs(),We=kWs(),Ce=SWs(),qe=CWs(),et=TWs(),Ze=EWs(),rt=MWs(),[ct,vt]=k.useState({}),kt=ht=>{ht?(l(ht),c(ht.name),u(ht.description||""),f(ht.icon||"")):(l(null),c(""),u(""),f("")),a(!0)},St=async()=>{if(!o.trim()){he.error("Please enter a category name");return}try{i?(await We.mutateAsync({id:i.id,name:o,description:d||null,icon:m||null}),he.success("Category updated successfully")):(await Ge.mutateAsync({name:o,description:d||null,icon:m||null,sort_order:((Ve==null?void 0:Ve.length)||0)+1}),he.success("Category created successfully")),a(!1)}catch(ht){console.error("Error saving category:",ht),he.error("Failed to save category")}},Yt=async()=>{if(x)try{await Ce.mutateAsync(x),he.success("Category deleted successfully"),y(null)}catch(ht){console.error("Error deleting category:",ht),he.error("Failed to delete category")}},es=ht=>{var Jt;ht?(N(ht),A(ht.name),D(ht.description||""),F(ht.category_id),B(ht.points_cost.toString()),Z(ht.item_type),W(ht.file_url||""),ne(ht.preview_image_url||""),ue(((Jt=ht.max_quantity)==null?void 0:Jt.toString())||""),de(ht.is_active)):(N(null),A(""),D(""),F(null),B(""),Z("file"),W(""),ne(""),ue(""),de(!0)),b(!0)},zs=async(ht,Jt)=>{Jt==="file"?Ee(!0):Oe(!0);try{const Ms=ht.name.split(".").pop(),ts=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Ms}`,Xs=`${Jt==="file"?"items":"previews"}/${ts}`,{error:js}=await U.storage.from("reward-store").upload(Xs,ht);if(js)throw js;const{data:{publicUrl:$s}}=U.storage.from("reward-store").getPublicUrl(Xs);Jt==="file"?W($s):ne($s),he.success("File uploaded successfully")}catch(Ms){console.error("Error uploading file:",Ms),he.error("Failed to upload file")}finally{Jt==="file"?Ee(!1):Oe(!1)}},sr=async()=>{if(!C.trim()){he.error("Please enter an item name");return}if(!O||parseInt(O)<0){he.error("Please enter a valid points cost");return}try{const ht={name:C,description:E||null,category_id:R,points_cost:parseInt(O),item_type:K,file_url:Q||null,preview_image_url:te||null,max_quantity:ae?parseInt(ae):null,current_quantity:ae?parseInt(ae):null,is_active:me,created_by:s==null?void 0:s.id};j?(await et.mutateAsync({id:j.id,...ht,current_quantity:j.max_quantity!==(ae?parseInt(ae):null)?ae?parseInt(ae):null:j.current_quantity}),he.success("Item updated successfully")):(await qe.mutateAsync(ht),he.success("Item created successfully")),b(!1)}catch(ht){console.error("Error saving item:",ht),he.error("Failed to save item")}},ms=async()=>{if(fe)try{await Ze.mutateAsync(fe),he.success("Item deleted successfully"),je(null)}catch(ht){console.error("Error deleting item:",ht),he.error("Failed to delete item")}},gt=async(ht,Jt)=>{const Ms=ct[ht];if(Ms===void 0||Ms===Jt.toString())return;const ts=parseInt(Ms);if(isNaN(ts)||ts<0){he.error("Please enter a valid positive number");return}try{await rt.mutateAsync({id:ht,points:ts}),he.success("Points updated successfully"),vt(Xs=>{const js={...Xs};return delete js[ht],js})}catch(Xs){console.error("Error updating points:",Xs),he.error("Failed to update points")}};return Le||ve||we||Se?e.jsx(ws,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(dr,{className:"h-8 w-64"}),e.jsx(dr,{className:"h-96"})]})}):e.jsxs(ws,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Reward Store Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage store items that agents can purchase with their points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(yc,{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:($e==null?void 0:$e.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[($e==null?void 0:$e.filter(ht=>ht.is_active).length)||0," active"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Kf,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Ve==null?void 0:Ve.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fa,{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:[$e&&$e.length>0?Math.round($e.reduce((ht,Jt)=>ht+Jt.points_cost,0)/$e.length):0," pts"]})]})})]}),e.jsxs(ta,{value:t,onValueChange:r,children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"items",children:"Items"}),e.jsx(rs,{value:"categories",children:"Categories"}),e.jsx(rs,{value:"purchases",children:"Purchases"}),e.jsx(rs,{value:"point-settings",children:"Point Settings"})]}),e.jsx(fs,{value:"items",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Store Items"}),e.jsx(Ur,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(q,{onClick:()=>es(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Pe,{children:!$e||$e.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Di,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No items yet. Add your first reward item!"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Item"}),e.jsx(At,{children:"Category"}),e.jsx(At,{className:"text-center",children:"Cost"}),e.jsx(At,{className:"text-center",children:"Type"}),e.jsx(At,{className:"text-center",children:"Quantity"}),e.jsx(At,{className:"text-center",children:"Status"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:$e.map(ht=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ht.preview_image_url?e.jsx("img",{src:ht.preview_image_url,alt:ht.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(Di,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ht.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:ht.description||"No description"})]})]})}),e.jsx(xt,{children:ht.category?e.jsx(Xe,{variant:"outline",children:ht.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(xt,{className:"text-center",children:e.jsxs(Xe,{variant:"secondary",className:"font-bold",children:[e.jsx(fa,{className:"h-3 w-3 mr-1"}),ht.points_cost]})}),e.jsx(xt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[ht.item_type==="file"?e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(tl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:ht.item_type})]})}),e.jsx(xt,{className:"text-center",children:ht.max_quantity!==null?e.jsxs("span",{className:ht.current_quantity===0?"text-red-500":"",children:[ht.current_quantity,"/",ht.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(xt,{className:"text-center",children:e.jsx(Xe,{variant:ht.is_active?"default":"secondary",children:ht.is_active?"Active":"Inactive"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>es(ht),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>je(ht.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},ht.id))})]})})]})}),e.jsx(fs,{value:"categories",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Categories"}),e.jsx(Ur,{children:"Organize your store items into categories"})]}),e.jsxs(q,{onClick:()=>kt(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Pe,{children:!Ve||Ve.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Kf,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Name"}),e.jsx(At,{children:"Description"}),e.jsx(At,{className:"text-center",children:"Items"}),e.jsx(At,{className:"text-right",children:"Actions"})]})}),e.jsx(ha,{children:Ve.map(ht=>e.jsxs(Ws,{children:[e.jsxs(xt,{className:"font-medium",children:[ht.icon&&e.jsx("span",{className:"mr-2",children:ht.icon}),ht.name]}),e.jsx(xt,{className:"text-muted-foreground",children:ht.description||"—"}),e.jsx(xt,{className:"text-center",children:($e==null?void 0:$e.filter(Jt=>Jt.category_id===ht.id).length)||0}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>kt(ht),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>y(ht.id),children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})})]})})]},ht.id))})]})})]})}),e.jsx(fs,{value:"purchases",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(lg,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Ur,{children:"View all reward redemptions by agents"})]}),e.jsx(Pe,{children:!Qe||Qe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(lg,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Date"}),e.jsx(At,{children:"Agent"}),e.jsx(At,{children:"Item"}),e.jsx(At,{className:"text-center",children:"Points Spent"})]})}),e.jsx(ha,{children:Qe.map(ht=>{var Jt,Ms,ts,Xs;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"text-muted-foreground",children:As(new Date(ht.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center",children:e.jsx(qi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Jt=ht.user)==null?void 0:Jt.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Ms=ht.user)==null?void 0:Ms.email)||"—"})]})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(ts=ht.item)!=null&&ts.preview_image_url?e.jsx("img",{src:ht.item.preview_image_url,alt:ht.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(Di,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Xs=ht.item)==null?void 0:Xs.name)||"Deleted item"})]})}),e.jsx(xt,{className:"text-center",children:e.jsxs(Xe,{variant:"secondary",className:"font-bold",children:[e.jsx(fa,{className:"h-3 w-3 mr-1"}),ht.points_spent]})})]},ht.id)})})]})})]})})]})]}),e.jsx(vs,{open:n,onOpenChange:a,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:i?"Edit Category":"Add Category"}),e.jsx(an,{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(ce,{htmlFor:"categoryName",children:"Name"}),e.jsx(Ne,{id:"categoryName",value:o,onChange:ht=>c(ht.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(pr,{id:"categoryDescription",value:d,onChange:ht=>u(ht.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(Ne,{id:"categoryIcon",value:m,onChange:ht=>f(ht.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(q,{onClick:St,disabled:Ge.isPending||We.isPending,children:Ge.isPending||We.isPending?"Saving...":"Save"})]})]})}),e.jsx(vs,{open:_,onOpenChange:b,children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:j?"Edit Item":"Add Item"}),e.jsx(an,{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(ce,{htmlFor:"itemName",children:"Name *"}),e.jsx(Ne,{id:"itemName",value:C,onChange:ht=>A(ht.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"itemDescription",children:"Description"}),e.jsx(pr,{id:"itemDescription",value:E,onChange:ht=>D(ht.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(ce,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(Ds,{value:R||"none",onValueChange:ht=>F(ht==="none"?null:ht),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select category"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No category"}),Ve==null?void 0:Ve.map(ht=>e.jsxs(lt,{value:ht.id,children:[ht.icon&&`${ht.icon} `,ht.name]},ht.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(Ne,{id:"itemPointsCost",type:"number",min:"0",value:O,onChange:ht=>B(ht.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(ce,{htmlFor:"itemType",children:"Type"}),e.jsxs(Ds,{value:K,onValueChange:Z,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"file",children:"File Download"}),e.jsx(lt,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(Ne,{id:"itemMaxQuantity",type:"number",min:"1",value:ae,onChange:ht=>ue(ht.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:Q,onChange:ht=>W(ht.target.value),placeholder:K==="file"?"Upload a file or paste URL":"Paste external link"}),K==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(q,{type:"button",variant:"outline",size:"icon",onClick:()=>{var ht;return(ht=Ie.current)==null?void 0:ht.click()},disabled:xe,children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ie,type:"file",className:"hidden",onChange:ht=>{var Ms;const Jt=(Ms=ht.target.files)==null?void 0:Ms[0];Jt&&zs(Jt,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:te,onChange:ht=>ne(ht.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(q,{type:"button",variant:"outline",size:"icon",onClick:()=>{var ht;return(ht=ze.current)==null?void 0:ht.click()},disabled:Me,children:e.jsx(zo,{className:"h-4 w-4"})}),e.jsx("input",{ref:ze,type:"file",accept:"image/*",className:"hidden",onChange:ht=>{var Ms;const Jt=(Ms=ht.target.files)==null?void 0:Ms[0];Jt&&zs(Jt,"preview")}})]}),te&&e.jsx("img",{src:te,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{id:"itemIsActive",checked:me,onCheckedChange:de}),e.jsx(ce,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(q,{onClick:sr,disabled:qe.isPending||et.isPending,children:qe.isPending||et.isPending?"Saving...":"Save"})]})]})}),e.jsx(el,{open:!!x,onOpenChange:()=>y(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete Category"}),e.jsx(Ho,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:Yt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(el,{open:!!fe,onOpenChange:()=>je(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete Item"}),e.jsx(Ho,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:ms,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(ke,{className:"mt-4",children:[e.jsx(Pt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Dt,{children:"Point Reward Settings"}),e.jsx(Ur,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Pe,{children:!nt||nt.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Bo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Action"}),e.jsx(At,{children:"Description"}),e.jsx(At,{className:"text-center w-32",children:"Points"}),e.jsx(At,{className:"text-right w-24",children:"Save"})]})}),e.jsx(ha,{children:nt.map(ht=>e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsx("p",{className:"font-medium",children:ht.action_name})}),e.jsx(xt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:ht.description})}),e.jsx(xt,{className:"text-center",children:e.jsx(Ne,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:ct[ht.id]??ht.points.toString(),onChange:Jt=>vt(Ms=>({...Ms,[ht.id]:Jt.target.value}))})}),e.jsx(xt,{className:"text-right",children:e.jsx(q,{size:"sm",variant:"outline",disabled:ct[ht.id]===void 0||ct[ht.id]===ht.points.toString()||rt.isPending,onClick:()=>gt(ht.id,ht.points),children:e.jsx(Ml,{className:"h-4 w-4"})})})]},ht.id))})]})})]})]})}const HKe=()=>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"})]}),GKe=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function PWs(){const s=is(),[t,r]=k.useState(!1),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=pt({queryKey:["canva-integration"],queryFn:async()=>{const{data:N,error:C}=await U.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(C)throw C;return N}}),{data:m}=pt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:N,error:C}=await U.from("brokerages").select("id, name").order("name");if(C)throw C;return N}}),{data:f}=pt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:N,error:C}=await U.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(C)throw C;return N}}),x=async()=>{var N;r(!0);try{const{data:C}=await U.auth.getSession(),A=(N=C==null?void 0:C.session)==null?void 0:N.access_token;if(!A)throw new Error("Not authenticated");const R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),F=await R.json();if(!R.ok||F!=null&&F.error)throw new Error((F==null?void 0:F.error)||"Failed to get authorization URL");if(F!=null&&F.authUrl){localStorage.setItem("canva_code_verifier",F.codeVerifier),localStorage.setItem("canva_oauth_state",F.state);const O=window.open(F.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!O){he.error("Popup was blocked. Please allow popups for this site and try again."),r(!1);return}const B=Z=>{var Q,W;Z.origin===window.location.origin&&(((Q=Z.data)==null?void 0:Q.type)==="canva-oauth-success"?(window.removeEventListener("message",B),he.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),r(!1)):((W=Z.data)==null?void 0:W.type)==="canva-oauth-error"&&(window.removeEventListener("message",B),he.error("Canva connection failed: "+(Z.data.error||"Unknown error")),r(!1)))};window.addEventListener("message",B);const K=setInterval(()=>{O.closed&&(clearInterval(K),window.removeEventListener("message",B),s.invalidateQueries({queryKey:["canva-integration"]}),r(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(C){console.error("Canva connect error:",C);const A=(C==null?void 0:C.message)||"";A.includes("CANVA_CLIENT_ID")?he.error("Canva app credentials not configured yet."):he.error(A||"Failed to start Canva connection"),r(!1)}},y=Mt({mutationFn:async N=>{var O;const{data:C}=await U.auth.getSession(),A=(O=C==null?void 0:C.session)==null?void 0:O.access_token;if(!A)throw new Error("Not authenticated");const R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:N})}),F=await R.json();if(!R.ok||F!=null&&F.error)throw new Error((F==null?void 0:F.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),he.success("Canva disconnected")},onError:N=>{he.error(N.message||"Failed to disconnect Canva")}}),_=Mt({mutationFn:async N=>{const{error:C}=await U.from("canva_brokerage_folders").insert({brokerage_id:N.brokerage_id,folder_id:N.folder_id.trim(),folder_name:N.folder_name.trim(),folder_type:N.folder_type,description:N.description.trim()||null,sort_order:(f==null?void 0:f.length)||0});if(C)throw C},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),he.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>he.error("Failed to add folder")}),b=Mt({mutationFn:async N=>{const{error:C}=await U.from("canva_brokerage_folders").delete().eq("id",N);if(C)throw C},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),he.success("Folder removed")},onError:()=>he.error("Failed to remove folder")}),j=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Pt,{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(HKe,{})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["Canva Connect",j&&e.jsx(Xe,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Ur,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Pe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Ti,{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(Ti,{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(Ti,{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(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Canva?"}),e.jsx(Ho,{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(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{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(!n),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kf,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",f&&f.length>0&&e.jsx(Xe,{variant:"secondary",className:"text-xs",children:f.length})]}),n?e.jsx(pg,{className:"h-4 w-4"}):e.jsx(Co,{className:"h-4 w-4"})]}),n&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[f&&f.length>0?f.map(N=>{var C,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:N.folder_name}),e.jsx(Xe,{variant:"outline",className:"text-xs shrink-0",children:((C=GKe.find(E=>E.value===N.folder_type))==null?void 0:C.label)||N.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(A=N.brokerages)==null?void 0:A.name," · ID: ",e.jsx("span",{className:"font-mono",children:N.folder_id})]})]}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>b.mutate(N.id),children:e.jsx($r,{className:"h-3.5 w-3.5"})})]},N.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs(q,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(q,{className:"mt-4",onClick:x,disabled:t||u,children:[t?e.jsx(lo,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(HKe,{})}),"Connect Canva",e.jsx(ci,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{children:"Brokerage"}),e.jsxs(Ds,{value:o.brokerage_id,onValueChange:N=>c(C=>({...C,brokerage_id:N})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a brokerage…"})}),e.jsx(Ls,{children:m==null?void 0:m.map(N=>e.jsx(lt,{value:N.id,children:N.name},N.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Canva Folder ID"}),e.jsx(Ne,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:N=>c(C=>({...C,folder_id:N.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(ce,{children:"Folder Display Name"}),e.jsx(Ne,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:N=>c(C=>({...C,folder_name:N.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Folder Type"}),e.jsxs(Ds,{value:o.folder_type,onValueChange:N=>c(C=>({...C,folder_type:N})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:GKe.map(N=>e.jsx(lt,{value:N.value,children:N.label},N.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ce,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(Ne,{placeholder:"What's in this folder?",value:o.description,onChange:N=>c(C=>({...C,description:N.target.value}))})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(q,{onClick:()=>_.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||_.isPending,children:[_.isPending?e.jsx(lo,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function LWs(){const s=qr();return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Uh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(ke,{className:"p-6 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(Ec,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"User Social Connections"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"See which agents have connected Facebook, Instagram, LinkedIn, and Google."})]})]}),e.jsxs(q,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(ci,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(PWs,{}),e.jsx(rbt,{})]})})}const WKe=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(mh,{className:t}):s==="instagram"?e.jsx(gu,{className:t}):s==="linkedin"?e.jsx(Yf,{className:t}):s==="google"?e.jsx(Ks,{className:t}):null},DWs=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function RWs(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(""),[l,o]=k.useState("all");k.useEffect(()=>{(async()=>{n(!0);const{data:f,error:x}=await U.rpc("admin_get_social_connections");if(x){he.error(x.message),n(!1);return}t(f||[]),n(!1)})()},[]);const c=k.useMemo(()=>{const f=a.trim().toLowerCase();return s.filter(x=>l!=="all"&&x.platform!==l?!1:f?(x.user_name||"").toLowerCase().includes(f)||(x.user_email||"").toLowerCase().includes(f)||(x.page_name||"").toLowerCase().includes(f)||(x.platform_username||"").toLowerCase().includes(f):!0)},[s,a,l]),d=k.useMemo(()=>{const f=new Map;return s.forEach(x=>{const y=f.get(x.user_id)||{name:x.user_name,email:x.user_email,platforms:new Set,count:0};y.platforms.add(x.platform),y.count+=1,f.set(x.user_id,y)}),Array.from(f.entries()).map(([x,y])=>({user_id:x,...y}))},[s]),u=k.useMemo(()=>{const f=new Map;return s.forEach(x=>f.set(x.platform,(f.get(x.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(f.entries())}},[s,d]),m=f=>f&&new Date(f).getTime()e.jsxs(ke,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[WKe(f)," ",f]}),e.jsx("div",{className:"text-2xl font-bold",children:x})]},f))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(Ne,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:f=>i(f.target.value),className:"md:max-w-md"}),e.jsxs(Ds,{value:l,onValueChange:o,children:[e.jsx(Ps,{className:"md:w-48",children:e.jsx(Fs,{placeholder:"All platforms"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All platforms"}),e.jsx(lt,{value:"facebook",children:"Facebook"}),e.jsx(lt,{value:"instagram",children:"Instagram"}),e.jsx(lt,{value:"linkedin",children:"LinkedIn"}),e.jsx(lt,{value:"google",children:"Google"})]})]})]}),e.jsx(ke,{children:r?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(ls,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"User"}),e.jsx(At,{children:"Platform"}),e.jsx(At,{children:"Page / Account"}),e.jsx(At,{children:"Status"}),e.jsx(At,{children:"Connected"})]})}),e.jsx(ha,{children:c.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(f=>{const x=m(f.token_expires_at);return e.jsxs(Ws,{children:[e.jsxs(xt,{children:[e.jsx("div",{className:"font-medium",children:f.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:f.user_email})]}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[WKe(f.platform)," ",f.platform]})}),e.jsxs(xt,{children:[e.jsx("div",{className:"font-medium",children:f.page_name||f.platform_username||"—"}),f.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",f.instagram_business_id]})]}),e.jsx(xt,{children:f.is_active?x?e.jsxs(Xe,{variant:"destructive",className:"gap-1",children:[e.jsx(go,{className:"h-3 w-3"})," Expired"]}):e.jsx(Xe,{children:"Active"}):e.jsx(Xe,{variant:"secondary",children:"Inactive"})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:DWs(f.created_at)})]},f.id)})})]})})]})})}const OWs={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 gO(s,t=18,r=10){return s.length<=t+r+3?s:`${s.slice(0,t)}…${s.slice(-r)}`}function FWs(){var K,Z,Q,W,te;const s=is(),[t,r]=k.useState("Test Push"),[n,a]=k.useState("Testing web push notification"),[i,l]=k.useState("/community"),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[m,f]=k.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[x,y]=k.useState(null),[_,b]=k.useState(null),{data:j,isLoading:N}=pt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:ne,error:ae}=await U.from("push_notification_settings").select("*").order("setting_key");if(ae)throw ae;return ne}}),{data:C,isLoading:A}=pt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:ne,error:ae}=await U.from("push_subscriptions").select("*",{count:"exact",head:!0});if(ae)throw ae;return{totalSubscriptions:ne||0}}}),E=Mt({mutationFn:async({settingKey:ne,isEnabled:ae})=>{const{error:ue}=await U.from("push_notification_settings").update({is_enabled:ae}).eq("setting_key",ne);if(ue)throw ue},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),he.success("Notification setting updated")},onError:ne=>{he.error("Failed to update setting: "+ne.message)}}),D=k.useMemo(()=>{var ne,ae;return m.isSupported?`perm=${m.permission??"unknown"} · controller=${m.controllerPresent?"yes":"no"} · sw=${((ne=m.serviceWorker)==null?void 0:ne.activeState)??"unknown"} · sub=${(ae=m.subscription)!=null&&ae.endpoint?"yes":"no"}`:"Push not supported in this browser."},[m]);k.useEffect(()=>{let ne=!0;const ae=async()=>{var fe,je,xe,Ee,Me,Oe,Ie;const me="serviceWorker"in navigator&&"PushManager"in window,de={isSupported:me,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((fe=navigator.serviceWorker)!=null&&fe.controller)};if(!me){ne&&f(de);return}try{const{data:ze,error:Ve}=await U.functions.invoke("get-vapid-public-key",{body:{}});if(Ve)throw Ve;de.vapidPublicKey=ze==null?void 0:ze.vapidPublicKey;const $e=(await navigator.serviceWorker.getRegistrations()).find(ve=>{var we,nt,Se;return(((we=ve.active)==null?void 0:we.scriptURL)||((nt=ve.waiting)==null?void 0:nt.scriptURL)||((Se=ve.installing)==null?void 0:Se.scriptURL)||"").includes("/sw.js")});if($e){de.pushWorkerScriptUrl=((je=$e.active)==null?void 0:je.scriptURL)||((xe=$e.waiting)==null?void 0:xe.scriptURL)||((Ee=$e.installing)==null?void 0:Ee.scriptURL),de.serviceWorker={scope:$e.scope,activeState:(Me=$e.active)==null?void 0:Me.state};const ve=await $e.pushManager.getSubscription();if(ve){const Qe=ve.toJSON();de.subscription={endpoint:Qe.endpoint,p256dh:(Oe=Qe.keys)==null?void 0:Oe.p256dh,auth:(Ie=Qe.keys)==null?void 0:Ie.auth}}}}catch(ze){de.error=(ze==null?void 0:ze.message)||String(ze)}ne&&f(de)};ae();const ue=window.setInterval(ae,4e3);return()=>{ne=!1,window.clearInterval(ue)}},[]);const R=async()=>{if(typeof Notification>"u"){he.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){he.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),he.success("Triggered a local notification (not push).")}catch(ne){he.error(`Local notification failed: ${(ne==null?void 0:ne.message)||String(ne)}`)}},F=async()=>{c(!0),y(null);try{const{data:ne,error:ae}=await U.functions.invoke("send-push-notification",{body:{title:t,body:n,url:i}});if(ae)throw ae;y({sent:ne==null?void 0:ne.sent,failed:ne==null?void 0:ne.failed,expiredCleaned:ne==null?void 0:ne.expiredCleaned,vapidPublicKey:ne==null?void 0:ne.vapidPublicKey}),(ne==null?void 0:ne.sent)>0?he.success(`Test notification sent to ${ne.sent} subscriber(s)`):(ne==null?void 0:ne.failed)>0?he.warning(`Notification failed for ${ne.failed} subscriber(s). ${ne.expired||0} expired subscriptions cleaned up.`):he.info("No active subscriptions to send to")}catch(ne){console.error("Error sending test notification:",ne),y({error:(ne==null?void 0:ne.message)||String(ne)}),he.error("Failed to send test notification: "+(ne.message||"Unknown error"))}finally{c(!1)}},O=async()=>{u(!0),b(null);try{const{data:ne,error:ae}=await U.functions.invoke("generate-vapid-keys",{body:{}});if(ae)throw ae;const ue=ne==null?void 0:ne.publicKey,me=ne==null?void 0:ne.privateKey;if(!ue||!me)throw new Error("generate-vapid-keys did not return keys");b({publicKey:ue,privateKey:me}),he.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(ne){console.error("Error generating VAPID keys:",ne),he.error("Failed to generate VAPID keys: "+((ne==null?void 0:ne.message)||"Unknown error"))}finally{u(!1)}},B=Mt({mutationFn:async()=>{const{error:ne}=await U.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(ne)throw ne},onSuccess:()=>{he.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:ne=>{he.error("Failed to clear subscriptions: "+ne.message)}});return e.jsx(ws,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Ur,{children:"Current active push notification subscriptions"})]}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:A?"...":(C==null?void 0:C.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Ur,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Pe,{children:N?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(ne=>{const ae=OWs[ne.setting_key]||{label:ne.setting_key,icon:"🔔"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:ae.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ae.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:ne.description})]})]}),e.jsx(Rr,{checked:ne.is_enabled,onCheckedChange:ue=>E.mutate({settingKey:ne.setting_key,isEnabled:ue}),disabled:E.isPending})]},ne.id)})})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(ym,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Ur,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Client push debug"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:D}),m.error&&e.jsx("div",{className:"mt-2 text-destructive",children:m.error}),e.jsxs("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Backend VAPID public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:m.vapidPublicKey?gO(m.vapidPublicKey):"(not loaded)"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Service worker"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["scope: ",(K=m.serviceWorker)!=null&&K.scope?gO(m.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((Z=m.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: ",(Q=m.subscription)!=null&&Q.endpoint?gO(m.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(W=m.subscription)!=null&&W.p256dh?gO(m.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(te=m.subscription)!=null&&te.auth?gO(m.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(q,{variant:"outline",onClick:R,children:"Local notification test"}),e.jsx(q,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(Ne,{id:"test-title",value:t,onChange:ne=>r(ne.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(pr,{id:"test-body",value:n,onChange:ne=>a(ne.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(Ne,{id:"test-url",value:i,onChange:ne=>l(ne.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs(q,{onClick:F,disabled:o||!t||!n,className:"w-full sm:w-auto",children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),x&&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"}),x.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",x.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",x.sent??0," sent, ",x.failed??0," failed, ",x.expiredCleaned??0," expired cleaned"]}),x.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:x.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(zr,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Ur,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you've recently updated the VAPID keys, existing subscriptions will no longer work. Use this to clear all subscriptions so users can re-subscribe with the new keys."}),e.jsxs(q,{variant:"destructive",onClick:()=>B.mutate(),disabled:B.isPending,children:[e.jsx(zr,{className:"h-4 w-4 mr-2"}),B.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(q,{variant:"outline",onClick:O,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 zWs(){const{toast:s}=Ba(),[t,r]=k.useState([]),[n,a]=k.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=k.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=zB("presentation_count","desc"),m=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});k.useEffect(()=>{f()},[]);const f=async()=>{try{l(!0);const{data:y,error:_}=await U.rpc("get_admin_presentation_stats");if(_)throw _;if(!y||y.length===0){l(!1);return}const b=y.map(E=>E.owner_user_id),{data:j,error:N}=await U.from("profiles").select("id, name, email, avatar_url").in("id",b);if(N)throw N;const C=new Map((j==null?void 0:j.map(E=>[E.id,E]))||[]),A=y.map(E=>{const D=C.get(E.owner_user_id);return{owner_user_id:E.owner_user_id,name:(D==null?void 0:D.name)||"Unknown",email:(D==null?void 0:D.email)||"",avatar_url:(D==null?void 0:D.avatar_url)||null,presentation_count:Number(E.presentation_count),total_views:Number(E.total_views),total_leads:Number(E.total_leads),total_cta_clicks:Number(E.total_cta_clicks)}});r(A),r(A),a({totalPresentations:A.reduce((E,D)=>E+D.presentation_count,0),totalViews:A.reduce((E,D)=>E+D.total_views,0),totalLeads:A.reduce((E,D)=>E+D.total_leads,0),totalCtaClicks:A.reduce((E,D)=>E+D.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)}},x=[{label:"Agents Using",value:n.agentsUsing,icon:Dr,color:"text-blue-600"},{label:"Total Presentations",value:n.totalPresentations,icon:Jy,color:"text-violet-600"},{label:"Total Views",value:n.totalViews,icon:Nn,color:"text-emerald-600"},{label:"Total Leads",value:n.totalLeads,icon:xl,color:"text-amber-600"},{label:"CTA Clicks",value:n.totalCtaClicks,icon:Bc,color:"text-rose-600"}];return e.jsx(ws,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:x.map(y=>e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:y.label}),e.jsx(y.icon,{className:`h-4 w-4 ${y.color}`})]}),e.jsx(Pe,{children:i?e.jsx(dr,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:y.value.toLocaleString()})})]},y.label))}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Wo,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Pe,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((y,_)=>e.jsx(dr,{className:"h-12 w-full"},_))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(mc,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(mc,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(mc,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(mc,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(mc,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(mc,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(ha,{children:m.map(y=>{var b,j;const _=y.total_views>0?(y.total_leads/y.total_views*100).toFixed(1):"0.0";return e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children: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=(b=y.name)==null?void 0:b.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(xt,{className:"text-center font-medium",children:y.presentation_count}),e.jsx(xt,{className:"text-center",children:y.total_views.toLocaleString()}),e.jsx(xt,{className:"text-center",children:y.total_leads>0?e.jsx(Xe,{variant:"secondary",children:y.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-center",children:y.total_cta_clicks}),e.jsx(xt,{className:"text-center",children:e.jsxs("span",{className:Number(_)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[_,"%"]})})]},y.owner_user_id)})})]})})]})]})})}function BWs(){const{toast:s}=Ba(),[t,r]=k.useState([]),[n,a]=k.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=k.useState(!0);k.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await U.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const m=d.map(b=>b.agent_id),{data:f,error:x}=await U.from("profiles").select("id, name, email, avatar_url").in("id",m);if(x)throw x;const y=new Map((f==null?void 0:f.map(b=>[b.id,b]))||[]),_=d.map(b=>{const j=y.get(b.agent_id);return{agent_id:b.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(b.open_house_count),total_visitors:Number(b.total_visitors),total_leads:Number(b.total_leads),active_count:Number(b.active_count)}});_.sort((b,j)=>j.total_visitors-b.total_visitors),r(_),a({totalOpenHouses:_.reduce((b,j)=>b+j.open_house_count,0),totalVisitors:_.reduce((b,j)=>b+j.total_visitors,0),totalLeads:_.reduce((b,j)=>b+j.total_leads,0),activeOpenHouses:_.reduce((b,j)=>b+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:n.agentsUsing,icon:Dr,color:"text-blue-600"},{label:"Total Open Houses",value:n.totalOpenHouses,icon:Pn,color:"text-violet-600"},{label:"Active Now",value:n.activeOpenHouses,icon:Ti,color:"text-emerald-600"},{label:"Total Visitors",value:n.totalVisitors,icon:Nn,color:"text-amber-600"},{label:"Leads Created",value:n.totalLeads,icon:xl,color:"text-rose-600"}];return e.jsx(ws,{title:"Guest Book Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Guest Book Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track open house sign-in usage and lead generation across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:c.map(d=>e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Pe,{children:i?e.jsx(dr,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Wo,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Pe,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(dr,{className:"h-12 w-full"},u))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Agent"}),e.jsx(At,{className:"text-center",children:"Open Houses"}),e.jsx(At,{className:"text-center",children:"Active"}),e.jsx(At,{className:"text-center",children:"Visitors"}),e.jsx(At,{className:"text-center",children:"Leads"}),e.jsx(At,{className:"text-center",children:"Conversion"})]})}),e.jsx(ha,{children:t.map(d=>{var m,f;const u=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(Ws,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:d.avatar_url?e.jsx("img",{src:d.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((f=(m=d.name)==null?void 0:m.charAt(0))==null?void 0:f.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email})]})]})}),e.jsx(xt,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(xt,{className:"text-center",children:d.active_count>0?e.jsx(Xe,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(xt,{className:"text-center",children:d.total_leads>0?e.jsx(Xe,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-center",children:e.jsxs("span",{className:Number(u)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[u,"%"]})})]},d.agent_id)})})]})})]})]})})}function $Ws(){const[s]=ic(),t=qr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing connection...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Failed to connect: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("Failed to connect: No authorization code");return}try{const{data:m,error:f}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(f){let x=f.message||"Failed to connect accounts";try{const y=f.context;if(y&&typeof y.json=="function"){const _=await y.json();_!=null&&_.error&&(x=_.error)}}catch{}throw new Error(x)}if(m!=null&&m.success)n("success"),i(m.message||"Accounts connected successfully!"),he.success(m.message||"Social accounts connected!");else throw new Error((m==null?void 0:m.error)||"Failed to connect accounts")}catch(m){console.error("Callback error:",m),n("error"),i(m.message||"Failed to complete connection"),he.error(m.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin text-primary"}),r==="success"&&e.jsx(Ti,{className:"h-12 w-12 text-green-500"}),r==="error"&&e.jsx(ad,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Dt,{children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Ur,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:e.jsx(q,{onClick:()=>t("/admin/integrations"),children:r==="success"?"View Integrations":"Back to Integrations"})})]})})}function UWs(){const s=is(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState([]),o=k.useRef(null),{data:c,isLoading:d}=pt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:j}=await U.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(j)throw j;return b}}),u={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(b=>b.status==="sent").length)||0,converted:(c==null?void 0:c.filter(b=>b.status==="converted").length)||0,conversionRate:c!=null&&c.length?Math.round(c.filter(b=>b.status==="converted").length/c.length*100):0},m=Mt({mutationFn:async b=>{const{data:j,error:N}=await U.functions.invoke("send-prospect-email",{body:{emails:b}});if(N)throw N;return j},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),he.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),r(""),a(""),l([])},onError:b=>{he.error("Failed to send: "+b.message)}}),f=Mt({mutationFn:async()=>{var C,A;const{data:{user:b}}=await U.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:j,error:N}=await U.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(A=(C=b.user_metadata)==null?void 0:C.name)==null?void 0:A.split(" ")[0]}],test_mode:!0}});if(N)throw N;return j},onSuccess:()=>{he.success("Test email sent to your inbox!")},onError:b=>{he.error("Failed to send test: "+b.message)}}),x=()=>{if(!t.trim()){he.error("Please enter an email address");return}if(c==null?void 0:c.find(j=>j.email.toLowerCase()===t.trim().toLowerCase())){he.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:n.trim()||void 0}])},y=b=>{var C;const j=(C=b.target.files)==null?void 0:C[0];if(!j)return;const N=new FileReader;N.onload=A=>{var O,B;const D=((O=A.target)==null?void 0:O.result).split(` `).filter(K=>K.trim()),R=[],F=(B=D[0])!=null&&B.toLowerCase().includes("email")?1:0;for(let K=F;Kte.trim().replace(/"/g,"")),Q=Z[0],W=Z[1];Q&&Q.includes("@")&&R.push({email:Q,first_name:W||void 0})}l(R),he.success(`${R.length} entries loaded from CSV`)},N.readAsText(j),o.current&&(o.current.value="")},_=()=>{if(i.length===0){he.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(N=>N.email.toLowerCase()))||[]),j=i.filter(N=>!b.has(N.email.toLowerCase()));if(j.length===0){he.error("All emails have already been prospected");return}j.lengthf.mutate(),disabled:f.isPending,className:"gap-2 ml-4 shrink-0",children:[f.isPending?e.jsx(ls,{className:"h-3 w-3 animate-spin"}):e.jsx(Ks,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Pe,{children:e.jsxs(ta,{defaultValue:"single",children:[e.jsxs(ea,{className:"mb-4",children:[e.jsxs(rs,{value:"single",children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(rs,{value:"bulk",children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(fs,{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(ce,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(Ne,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:b=>r(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(ce,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(Ne,{id:"prospect-name",placeholder:"First name (optional)",value:n,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs(q,{onClick:x,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(fs,{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:y,className:"hidden"}),e.jsxs(q,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(En,{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(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(Dr,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx($r,{className:"h-4 w-4"}),"Clear"]})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-lg p-3 bg-muted/30 text-sm font-mono space-y-1",children:[i.slice(0,20).map((b,j)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},j)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(q,{onClick:_,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Ur,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Pe,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,j)=>e.jsx(dr,{className:"h-12 w-full"},j))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-foreground",children:b.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:As(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(Xe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),"Converted"]}):e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?As(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Hu,{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 u$(s){const t=is(),{toast:r}=Ba(),n=pt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await U.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=pt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,m=!0;for(;m;){const{data:f,error:x}=await U.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(x)throw x;d=d.concat(f),m=f.length===c,u+=c}return d},enabled:!!s}),i=Mt({mutationFn:async c=>{const{data:{user:d}}=await U.auth.getUser();if(!d)throw new Error("Not authenticated");const u={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:m,error:f}=await U.from("recruit_prospects").insert(u).select().single();if(f)throw f;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),r({title:"Prospect added"})},onError:c=>r({title:"Error",description:c.message,variant:"destructive"})}),l=Mt({mutationFn:async({id:c,...d})=>{const{data:u,error:m}=await U.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(m)throw m;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>r({title:"Error",description:c.message,variant:"destructive"})}),o=Mt({mutationFn:async c=>{const{error:d}=await U.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),r({title:"Prospect removed"})}});return{stages:n.data||[],prospects:a.data||[],isLoading:n.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function qWs(s){const t=is(),{toast:r}=Ba(),n=pt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await U.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=Mt({mutationFn:async i=>{const{data:{user:l}}=await U.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await U.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),r({title:"Activity logged"})},onError:i=>r({title:"Error",description:i.message,variant:"destructive"})});return{activities:n.data||[],isLoading:n.isLoading,addActivity:a}}const KKe=(s,t)=>{var r;return{first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",license_number:"",experience_years:"",annual_production:"",source:"manual",notes:"",stage_id:s||((r=t==null?void 0:t[0])==null?void 0:r.id)||"",address:"",city:"",state:"",zip_code:"",last_year_volume:"",last_year_transactions:"",avg_sale_price:"",specialties:"",linkedin_url:"",website_url:"",instagram_handle:"",facebook_url:"",birthday:"",spouse_name:"",interests:"",referred_by:""}};function dbt({open:s,onOpenChange:t,stages:r,defaultStageId:n,onSubmit:a,isSubmitting:i}){const[l,o]=k.useState(KKe(n,r)),c=u=>m=>o(f=>({...f,[u]:m.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(KKe(n,r)),t(!1)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(ta,{defaultValue:"basic",className:"w-full",children:[e.jsxs(ea,{className:"grid w-full grid-cols-4",children:[e.jsx(rs,{value:"basic",children:"Basic Info"}),e.jsx(rs,{value:"production",children:"Production"}),e.jsx(rs,{value:"social",children:"Social & Web"}),e.jsx(rs,{value:"personal",children:"Personal"})]}),e.jsxs(fs,{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(ce,{children:"First Name *"}),e.jsx(Ne,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Last Name"}),e.jsx(Ne,{value:l.last_name,onChange:c("last_name")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Email"}),e.jsx(Ne,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Phone"}),e.jsx(Ne,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Current Brokerage"}),e.jsx(Ne,{value:l.current_brokerage,onChange:c("current_brokerage")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"License #"}),e.jsx(Ne,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Experience (years)"}),e.jsx(Ne,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Address"}),e.jsx(Ne,{placeholder:"Street address",value:l.address,onChange:c("address")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"City"}),e.jsx(Ne,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"State"}),e.jsx(Ne,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Zip"}),e.jsx(Ne,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Pipeline Stage"}),e.jsxs(Ds,{value:l.stage_id,onValueChange:u=>o(m=>({...m,stage_id:u})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:r.map(u=>e.jsx(lt,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Referred By"}),e.jsx(Ne,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(fs,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Annual Production Volume"}),e.jsx(Ne,{placeholder:"e.g. $5M, 20 transactions",value:l.annual_production,onChange:c("annual_production")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Last Year Volume"}),e.jsx(Ne,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Last Year Transactions"}),e.jsx(Ne,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Avg Sale Price"}),e.jsx(Ne,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Specialties / Niche"}),e.jsx(Ne,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(fs,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"LinkedIn URL"}),e.jsx(Ne,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Website URL"}),e.jsx(Ne,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Instagram Handle"}),e.jsx(Ne,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Facebook URL"}),e.jsx(Ne,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(fs,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Birthday"}),e.jsx(Ne,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Spouse / Partner Name"}),e.jsx(Ne,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Interests / Hobbies"}),e.jsx(Ne,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Notes"}),e.jsx(pr,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function Kye(){const{user:s}=Cs();return pt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,r]=await Promise.all([U.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),U.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:r.data?{email:r.data.gmail_email}:null}}})}function gIe({value:s,onChange:t}){const{data:r,isLoading:n}=Kye();return e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Send from"}),e.jsxs(Ds,{value:s,onValueChange:a=>t(a),disabled:n,children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(lt,{value:"mass_email",disabled:!(r!=null&&r.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(n2,{className:"h-3.5 w-3.5"}),"Mass Email",r!=null&&r.massEmail?` (${r.massEmail.email})`:" — not configured"]})}),e.jsx(lt,{value:"gmail",disabled:!(r!=null&&r.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-3.5 w-3.5"}),"Gmail",r!=null&&r.gmail?` (${r.gmail.email})`:" — not connected"]})})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Mass Email and Gmail use your own verified sender. Configure them under Integrations."})]})}function ubt({open:s,onOpenChange:t,recruitVideoId:r,brokerageId:n,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState("default"),[_,b]=k.useState(!1),j=is(),{data:N}=Kye();k.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),f(o||""),y(N!=null&&N.massEmail?"mass_email":N!=null&&N.gmail?"gmail":"default"))},[s,c,o,N==null?void 0:N.massEmail,N==null?void 0:N.gmail]);const C=async()=>{var A,E;if(!i){he.error("This prospect has no email address on file.");return}b(!0);try{const{data:D,error:R}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[r],brokerage_id:n,subject_override:d.trim()||void 0,message_override:m.trim()||void 0,send_via:x}});if(R)throw R;if(((D==null?void 0:D.sent)??0)>0)he.success(`Email sent to ${i}`),j.invalidateQueries({queryKey:["recruit-videos"]}),j.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const O=((E=(A=D==null?void 0:D.results)==null?void 0:A[0])==null?void 0:E.error)||"Failed to send";he.error(O)}}catch(D){he.error((D==null?void 0:D.message)||"Failed to send email")}finally{b(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"To"}),e.jsx(Ne,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(gIe,{value:x,onChange:y}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Subject"}),e.jsx(Ne,{value:d,onChange:A=>u(A.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(pr,{value:m,onChange:A=>f(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(fn,{children:[e.jsx(q,{variant:"ghost",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsxs(q,{onClick:C,disabled:_||!i,children:[_?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function p_(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const zCe=[{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 VWs(s){return pt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function HWs(s){return pt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function hbt(){const s=is(),{toast:t}=Ba();return Mt({mutationFn:async r=>{const{data:{user:n}}=await U.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("recruit_videos").insert({prospect_id:r.prospect_id,video_id:r.video_id,brokerage_id:r.brokerage_id,message:r.message||null,created_by:n.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token)").single();if(i)throw i;return a},onSuccess:r=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",r.prospect_id]}),t({title:"Video linked to prospect"})},onError:r=>t({title:"Error",description:r.message,variant:"destructive"})})}function mbt(){const s=is();return Mt({mutationFn:async({id:t,sent_via:r})=>{const{error:n}=await U.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:r,updated_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function fbt(s){return pt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function GWs(){const s=is(),{toast:t}=Ba();return Mt({mutationFn:async r=>{const{data:{user:n}}=await U.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("recruit_video_scripts").insert({...r,created_by:n.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:r=>t({title:"Error",description:r.message,variant:"destructive"})})}function WWs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("recruit_video_scripts").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function KWs({prospectId:s,prospectName:t,prospectEmail:r,brokerageId:n}){var te;const{data:a=[],isLoading:i}=HWs(s),{data:l=[]}=fbt(n),o=hbt(),c=V2();mbt();const[d,u]=k.useState("idle"),[m,f]=k.useState(0),[x,y]=k.useState(0),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState(!1),[E,D]=k.useState(null),[R,F]=k.useState(null),[O,B]=k.useState(null),K=((te=l.find(ne=>ne.id===_))==null?void 0:te.script_text)||"",Z=()=>{u("idle"),f(0),y(0),b(""),N("")},Q=k.useCallback(async(ne,ae)=>{u("uploading");try{const ue=`Recruiting: ${t}`,{videoId:me,libraryId:de}=await dM(ue),{uploadUrl:fe,apiKey:je}=await uM(me),xe=new XMLHttpRequest;xe.upload.onprogress=$e=>{$e.lengthComputable&&f($e.loaded/$e.total*100)},await new Promise(($e,ve)=>{xe.onload=()=>xe.status>=200&&xe.status<300?$e():ve(new Error("Upload failed")),xe.onerror=()=>ve(new Error("Upload failed")),xe.open("PUT",fe),xe.setRequestHeader("AccessKey",je),xe.send(ne)}),u("processing");let Ee=0;const Me=Date.now(),Oe=9e4,Ie=`https://iframe.mediadelivery.net/embed/${de}/${me}`;for(;Ee<4&&(await new Promise(ve=>setTimeout(ve,3e3)),!(Date.now()-Me>Oe));){const $e=await W_(me);if(Ee=$e.status,y($e.encodeProgress||0),Ee===5||Ee===6)throw new Error("Video processing failed")}const ze=await W_(me),Ve=(ze.storageSize||ne.size)/(1024*1024),Le=await c.mutateAsync({bunny_video_id:me,playback_url:ze.directPlayUrl||Ie,thumbnail_url:ze.thumbnailUrl,preview_url:ze.previewUrl||null,duration_seconds:ze.length||ae,file_size_mb:Ve,title:ue,status:Ee>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Le.id,brokerage_id:n,message:j||void 0}),u("done"),he.success("Video recorded and linked to prospect!"),setTimeout(()=>{A(!1),Z()},1500)}catch(ue){he.error(ue.message||"Failed to upload video"),u("record")}},[s,t,n,j,c,o]),W=ne=>{ne&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${ne}`),he.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(bn,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(vs,{open:C,onOpenChange:ne=>{!ne&&(d==="uploading"||d==="processing")||(A(ne),ne||Z())},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsxs(bs,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(Ds,{value:_,onValueChange:b,children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Fs,{placeholder:"No script — speak freely"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"No script"}),l.map(ne=>{var ae;return e.jsx(lt,{value:ne.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[ne.title,e.jsx(Xe,{variant:"outline",className:"text-[9px] ml-1",children:(ae=zCe.find(ue=>ue.value===ne.category))==null?void 0:ae.label})]})},ne.id)})]})]}),K&&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:K})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(pr,{value:j,onChange:ne=>N(ne.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs(q,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(bn,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(pM,{maxDurationSeconds:600,onRecordingComplete:Q,teleprompterContent:K||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(ki,{value:m,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(m),"%"]})]}),d==="processing"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Processing video…"}),e.jsx(ki,{value:x,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(x),"%"]})]}),d==="done"&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Al,{className:"h-6 w-6 text-emerald-600"})}),e.jsx("p",{className:"font-medium text-emerald-600",children:"Video ready!"})]})]})]})]}),i?e.jsx("div",{className:"text-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto"})}):a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos sent yet"}):e.jsx("div",{className:"space-y-2",children:a.map(ne=>{var ae;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:p_(ne.video)?e.jsx("img",{src:p_(ne.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(bn,{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:((ae=ne.video)==null?void 0:ae.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[ne.view_count>0?e.jsxs(Xe,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(Nn,{className:"h-2.5 w-2.5 mr-0.5"}),ne.view_count]}):ne.sent_at?e.jsxs(Xe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(hn,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(Xe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(jn,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:As(new Date(ne.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>W(ne.share_token),title:"Copy link",children:e.jsx(si,{className:"h-3 w-3"})}),e.jsxs(q,{variant:ne.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!r,onClick:()=>{var ue;D(ne.id),F(((ue=ne.video)==null?void 0:ue.title)||null),B(ne.message||null)},title:r?"Email video to prospect":"No email on file",children:[e.jsx(Ks,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:ne.sent_at?"Resend":"Email"})]})]})]},ne.id)})}),E&&e.jsx(ubt,{open:!!E,onOpenChange:ne=>{ne||D(null)},recruitVideoId:E,brokerageId:n,prospectName:t,prospectEmail:r,videoTitle:R,defaultMessage:O})]})}function YWs({brokerageId:s,onSelect:t}){const{data:r=[],isLoading:n}=pt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=U.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=r.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(En,{className:"h-4 w-4"}),"Use Template",e.jsx(Co,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(Sd,{align:"end",className:"w-80 max-h-[420px] overflow-y-auto",children:n?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):r.length===0?e.jsx("div",{className:"px-3 py-4 text-xs text-muted-foreground text-center",children:"No templates available."}):Object.entries(a).map(([i,l],o)=>e.jsxs("div",{children:[o>0&&e.jsx(z_,{}),e.jsx(S9,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(ti,{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(Xe,{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 ZWs({open:s,onOpenChange:t,prospectId:r,brokerageId:n,prospectName:a,prospectEmail:i}){const{user:l}=Cs(),o=(a||"").split(" ")[0]||"there",[c,d]=k.useState(""),[u,m]=k.useState(""),[f,x]=k.useState("default"),[y,_]=k.useState(!1),[b,j]=k.useState(null),[N,C]=k.useState(!1),A=is(),{data:E}=Kye();k.useEffect(()=>{if(s){d(`Hi ${o}`),m("");const K=E!=null&&E.massEmail?"mass_email":E!=null&&E.gmail?"gmail":"default";x(K),j(null),C(!1)}},[s,o,E==null?void 0:E.massEmail,E==null?void 0:E.gmail]);const{data:D=[],isLoading:R}=pt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:K,error:Z}=await U.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Z)throw Z;return K??[]},enabled:s&&!!(l!=null&&l.id)}),F=D.find(K=>K.id===b)||null,O=async()=>{var K,Z;if(!i){he.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){he.error("Subject and message are required.");return}_(!0);try{if(b){const{data:Q}=await U.from("recruit_videos").select("id").eq("prospect_id",r).eq("video_id",b).maybeSingle();let W=Q==null?void 0:Q.id;if(!W){const{data:ue,error:me}=await U.from("recruit_videos").insert({prospect_id:r,video_id:b,brokerage_id:n,message:u.trim(),created_by:l.id}).select("id").single();if(me)throw me;W=ue.id}const{data:te,error:ne}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[W],brokerage_id:n,subject_override:c.trim(),message_override:u.trim(),send_via:f}});if(ne)throw ne;if(((te==null?void 0:te.sent)??0)>0)he.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-videos"]}),A.invalidateQueries({queryKey:["recruit-videos-prospect",r]}),A.invalidateQueries({queryKey:["recruit-activities",r]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const ue=((Z=(K=te==null?void 0:te.results)==null?void 0:K[0])==null?void 0:Z.error)||"Failed to send";he.error(ue)}}else{const{data:Q,error:W}=await U.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:r,brokerage_id:n,subject:c.trim(),message:u.trim(),send_via:f}});if(W)throw W;Q!=null&&Q.success?(he.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-activities",r]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):he.error((Q==null?void 0:Q.error)||"Failed to send")}}catch(Q){he.error((Q==null?void 0:Q.message)||"Failed to send email")}finally{_(!1)}},B=K=>{const Z=Q=>Q.replace(/\[First Name\]/gi,o);d(Z(K.subject)),m(Z(K.body)),he.success(`Loaded "${K.title}"`)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"To"}),e.jsx(Ne,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(gIe,{value:f,onChange:x}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ce,{className:"text-xs",children:"Subject"}),e.jsx(YWs,{brokerageId:n,onSelect:B})]}),e.jsx(Ne,{value:c,onChange:K=>d(K.target.value)}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Message"}),e.jsx(pr,{value:u,onChange:K=>m(K.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(ce,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(bn,{className:"h-3.5 w-3.5"})," Include a video"]}),F?e.jsxs(q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{j(null),C(!1)},children:[e.jsx($r,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(q,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>C(K=>!K),children:N?"Hide library":"Pick from library"})]}),F&&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:p_(F)?e.jsx("img",{src:p_(F),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(bn,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:F.title||"Untitled video"})]}),!F&&N&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:R?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):D.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."}):D.map(K=>e.jsxs("button",{type:"button",onClick:()=>{j(K.id),C(!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:p_(K)?e.jsx("img",{src:p_(K),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(bn,{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:K.title||"Untitled video"}),K.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(K.duration_seconds/60),":",String(Math.floor(K.duration_seconds%60)).padStart(2,"0")]})]})]},K.id))}),F&&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(fn,{children:[e.jsx(q,{variant:"ghost",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsxs(q,{onClick:O,disabled:y||!i,children:[y?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(hn,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function XWs(s){return pt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}const YKe=[{value:"call",label:"Phone Call",icon:Mn},{value:"email",label:"Email",icon:Ks},{value:"text",label:"Text Message",icon:Ui},{value:"meeting",label:"Meeting",icon:vn},{value:"note",label:"Note",icon:En},{value:"campaign_email",label:"Campaign Email",icon:hn}];function n0({label:s,value:t,icon:r}){return t?e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[r&&e.jsx(r,{className:"h-3 w-3"})," ",s]}),e.jsx("p",{className:"font-medium text-sm",children:t})]}):null}function LV({label:s,url:t,icon:r}){return t?e.jsxs("a",{href:t.startsWith("http")?t:`https://${t}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm text-primary hover:underline",children:[e.jsx(r,{className:"h-3.5 w-3.5"})," ",s," ",e.jsx(un,{className:"h-3 w-3 opacity-50"})]}):null}function vd({label:s,value:t,onChange:r,type:n="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:s}),e.jsx(Ne,{type:n,value:t,onChange:i=>r(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function pbt({prospect:s,stages:t,brokerageId:r,open:n,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=qWs((s==null?void 0:s.id)||null),{data:d=[]}=XWs((s==null?void 0:s.id)||null),[u,m]=k.useState({type:"note",title:"",description:""}),[f,x]=k.useState(!1),[y,_]=k.useState(!1),[b,j]=k.useState({}),[N,C]=k.useState(!1);if(!s)return null;const A=()=>{var W,te;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:((te=s.last_year_transactions)==null?void 0:te.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[te,ne]of Object.entries(b))te==="experience_years"||te==="last_year_transactions"?W[te]=ne?parseInt(ne):null:W[te]=ne||null;i(W),_(!1)},D=()=>_(!1),R=W=>te=>j(ne=>({...ne,[W]:te})),F=()=>{u.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:u.type,title:u.title,description:u.description||null}),m({type:"note",title:"",description:""}),x(!1))},O=t.find(W=>W.id===s.stage_id),B=s.address||s.city||s.state,K=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,Q=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(sw,{open:n,onOpenChange:W=>{W||_(!1),a(W)},children:[e.jsx(U1,{className:"w-full sm:max-w-lg p-0",children:e.jsx(ui,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(rw,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(nw,{className:"text-xl",children:[s.first_name," ",s.last_name]}),O&&e.jsx(Xe,{variant:"outline",style:{borderColor:O.color,color:O.color},className:"mt-1",children:O.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[y?e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:D,children:e.jsx($r,{className:"h-4 w-4"})}),e.jsx(q,{variant:"default",size:"icon",onClick:E,children:e.jsx(Ml,{className:"h-4 w-4"})})]}):e.jsx(q,{variant:"ghost",size:"icon",onClick:A,title:"Edit prospect",children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete prospect?"}),e.jsx(Ho,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{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(Ks,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs(q,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>C(!0),children:[e.jsx(Ks,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Mn,{className:"h-3.5 w-3.5"})," ",s.phone]}),B&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ma,{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(ce,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(Ds,{value:s.stage_id||"",onValueChange:W=>i({id:s.id,stage_id:W}),children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:t.map(W=>e.jsx(lt,{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(ta,{defaultValue:"details",className:"w-full",children:[e.jsxs(ea,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(rs,{value:"details",className:"text-xs",children:"Details"}),e.jsx(rs,{value:"production",className:"text-xs",children:"Production"}),e.jsx(rs,{value:"social",className:"text-xs",children:"Social"}),e.jsx(rs,{value:"personal",className:"text-xs",children:"Personal"})]}),y?e.jsxs(e.Fragment,{children:[e.jsxs(fs,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(vd,{label:"First Name",value:b.first_name,onChange:R("first_name")}),e.jsx(vd,{label:"Last Name",value:b.last_name,onChange:R("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(vd,{label:"Email",value:b.email,onChange:R("email"),type:"email"}),e.jsx(vd,{label:"Phone",value:b.phone,onChange:R("phone")})]}),e.jsx(vd,{label:"Current Brokerage",value:b.current_brokerage,onChange:R("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(vd,{label:"License #",value:b.license_number,onChange:R("license_number")}),e.jsx(vd,{label:"Experience (years)",value:b.experience_years,onChange:R("experience_years"),type:"number"})]}),e.jsx(vd,{label:"Address",value:b.address,onChange:R("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(vd,{label:"City",value:b.city,onChange:R("city")}),e.jsx(vd,{label:"State",value:b.state,onChange:R("state")}),e.jsx(vd,{label:"Zip",value:b.zip_code,onChange:R("zip_code")})]}),e.jsx(vd,{label:"Source",value:b.source,onChange:R("source")}),e.jsx(vd,{label:"Referred By",value:b.referred_by,onChange:R("referred_by")}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Notes"}),e.jsx(pr,{value:b.notes,onChange:W=>j(te=>({...te,notes:W.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(fs,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(vd,{label:"Annual Production",value:b.annual_production,onChange:R("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(vd,{label:"Last Year Volume",value:b.last_year_volume,onChange:R("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(vd,{label:"Last Year Transactions",value:b.last_year_transactions,onChange:R("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(vd,{label:"Avg Sale Price",value:b.avg_sale_price,onChange:R("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(vd,{label:"Specialties / Niche",value:b.specialties,onChange:R("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(fs,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(vd,{label:"LinkedIn URL",value:b.linkedin_url,onChange:R("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(vd,{label:"Website URL",value:b.website_url,onChange:R("website_url"),type:"url",placeholder:"https://..."}),e.jsx(vd,{label:"Instagram Handle",value:b.instagram_handle,onChange:R("instagram_handle"),placeholder:"@handle"}),e.jsx(vd,{label:"Facebook URL",value:b.facebook_url,onChange:R("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(fs,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(vd,{label:"Birthday",value:b.birthday,onChange:R("birthday"),type:"date"}),e.jsx(vd,{label:"Spouse / Partner",value:b.spouse_name,onChange:R("spouse_name")}),e.jsx(vd,{label:"Interests / Hobbies",value:b.interests,onChange:R("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fs,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(n0,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(n0,{label:"License #",value:s.license_number}),e.jsx(n0,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(n0,{label:"Referred By",value:s.referred_by}),e.jsx(n0,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(fs,{value:"production",className:"mt-3",children:K?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(n0,{label:"Annual Production",value:s.annual_production}),e.jsx(n0,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(n0,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(n0,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(n0,{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(fs,{value:"social",className:"mt-3",children:Z?e.jsxs("div",{className:"space-y-2",children:[e.jsx(LV,{label:"LinkedIn",url:s.linkedin_url,icon:Yf}),e.jsx(LV,{label:"Website",url:s.website_url,icon:Ql}),s.instagram_handle&&e.jsx(LV,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:gu}),e.jsx(LV,{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(fs,{value:"personal",className:"mt-3",children:Q?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(n0,{label:"Birthday",value:s.birthday?As(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Di}),e.jsx(n0,{label:"Spouse / Partner",value:s.spouse_name,icon:yi}),e.jsx("div",{className:"col-span-2",children:e.jsx(n0,{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(KWs,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:r}),e.jsx(cl,{}),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(q,{size:"sm",variant:"outline",onClick:()=>x(!f),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),f&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(Ds,{value:u.type,onValueChange:W=>m(te=>({...te,type:W})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:YKe.map(W=>e.jsx(lt,{value:W.value,children:W.label},W.value))})]}),e.jsx(Ne,{placeholder:"Subject / Title",value:u.title,onChange:W=>m(te=>({...te,title:W.target.value}))}),e.jsx(pr,{placeholder:"Details (optional)",value:u.description,onChange:W=>m(te=>({...te,description:W.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>x(!1),children:"Cancel"}),e.jsx(q,{size:"sm",onClick:F,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const W=[...o.map(te=>({type:"manual",data:te,date:te.created_at})),...d.map(te=>({type:"campaign_email",data:te,date:te.sent_at||te.created_at}))].sort((te,ne)=>new Date(ne.date).getTime()-new Date(te.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(te=>{if(te.type==="manual"){const ae=te.data,ue=YKe.find(de=>de.value===ae.activity_type),me=(ue==null?void 0:ue.icon)||En;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(me,{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:ae.title}),ae.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ae.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:As(new Date(ae.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${ae.id}`)}const ne=te.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(hn,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium",children:["Campaign Email #",ne.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ne.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[ne.status==="failed"?e.jsx(Xe,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(hn,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),ne.opened_at?e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(Nn,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",As(new Date(ne.opened_at),"MMM d, h:mm a")]}):ne.status!=="failed"?e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,ne.clicked_at&&e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(dm,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",As(new Date(ne.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:As(new Date(ne.sent_at||ne.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${ne.id}`)})})()})]})]})})}),e.jsx(ZWs,{open:N,onOpenChange:C,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const QWs=["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 xbt({open:s,onOpenChange:t,brokerageId:r,stages:n}){var B;const{toast:a}=Ba(),i=is(),l=k.useRef(null),[o,c]=k.useState([]),[d,u]=k.useState([]),[m,f]=k.useState({}),[x,y]=k.useState(((B=n[0])==null?void 0:B.id)||""),[_,b]=k.useState(!1),[j,N]=k.useState("upload"),[C,A]=k.useState(0),E=()=>{c([]),u([]),f({}),N("upload"),A(0)},D=K=>{var W;const Z=(W=K.target.files)==null?void 0:W[0];if(!Z)return;const Q=new FileReader;Q.onload=te=>{var je;const ae=((je=te.target)==null?void 0:je.result).split(/\r?\n/).filter(xe=>xe.trim());if(ae.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const ue=R(ae[0]);u(ue);const me={},de=new Set;ue.forEach((xe,Ee)=>{const Me=xe.toLowerCase().replace(/[^a-z0-9]/g,"");let Oe=null;/^firstname$/.test(Me)||Me==="first"?Oe="first_name":/^lastname$/.test(Me)||Me==="last"?Oe="last_name":/^email$/.test(Me)||Me==="emailaddress"?Oe="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(Me)?Oe="phone":/officename|currentbrokerage|brokerage|company/.test(Me)?Oe="current_brokerage":/membernumber|licensenumber|license/.test(Me)?Oe="license_number":/experienceyears|yearsexperience/.test(Me)?Oe="experience_years":/^totalvolume$|annualproduction/.test(Me)?Oe="annual_production":/^address$/.test(Me)?Oe="address":/^city$/.test(Me)?Oe="city":/^state$/.test(Me)?Oe="state":/^postalcode$|^zip$|^zipcode$/.test(Me)?Oe="zip_code":/listsidevolume|lastyearvolume/.test(Me)?Oe="last_year_volume":/^totalcount$|lastyeartransactions/.test(Me)?Oe="last_year_transactions":/avgsaleprice|averageprice/.test(Me)?Oe="avg_sale_price":/linkedin/.test(Me)?Oe="linkedin_url":/website/.test(Me)?Oe="website_url":/specialt/.test(Me)?Oe="specialties":/referr/.test(Me)?Oe="referred_by":/^notes$|^note$/.test(Me)&&(Oe="notes"),Oe&&!de.has(Oe)&&(me[String(Ee)]=Oe,de.add(Oe))}),f(me);const fe=ae.slice(1).map(xe=>{const Ee=R(xe),Me={};return ue.forEach((Oe,Ie)=>{Me[String(Ie)]=Ee[Ie]||""}),Me});c(fe),N("map")},Q.readAsText(Z)},R=K=>{const Z=[];let Q="",W=!1;for(const te of K)te==='"'?W=!W:te===","&&!W?(Z.push(Q.trim()),Q=""):Q+=te;return Z.push(Q.trim()),Z},F=async()=>{b(!0);try{const{data:{user:K}}=await U.auth.getUser();if(!K)throw new Error("Not authenticated");const Z=o.map(W=>{const te={brokerage_id:r,created_by:K.id,stage_id:x,source:"csv_import",first_name:"Unknown"},ne=te;return Object.entries(m).forEach(([ae,ue])=>{var de;const me=(de=W[ae])==null?void 0:de.trim();me&&(ue==="experience_years"||ue==="last_year_transactions"?ne[ue]=parseInt(me.replace(/[^0-9.-]/g,""))||null:ue==="annual_production"||ue==="last_year_volume"||ue==="avg_sale_price"?ne[ue]=me.replace(/[^0-9.$,.-]/g,""):ne[ue]=me)}),te});let Q=0;for(let W=0;W{const K=`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([K],{type:"text/csv"}),Q=URL.createObjectURL(Z),W=document.createElement("a");W.href=Q,W.download="recruit-prospects-template.csv",W.click(),URL.revokeObjectURL(Q)};return e.jsx(vs,{open:s,onOpenChange:K=>{K||E(),t(K)},children:e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{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(s2,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Upload a CSV file with prospect data"}),e.jsx("input",{ref:l,type:"file",accept:".csv",className:"hidden",onChange:D}),e.jsxs(q,{onClick:()=>{var K;return(K=l.current)==null?void 0:K.click()},children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(q,{variant:"link",className:"text-xs",onClick:O,children:"Download CSV template"})]}),j==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(Ds,{value:x,onValueChange:y,children:[e.jsx(Ps,{className:"w-[180px]",children:e.jsx(Fs,{})}),e.jsx(Ls,{children:n.map(K=>e.jsx(lt,{value:K.id,children:K.name},K.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-[140px]",children:"CSV Column"}),e.jsx(At,{className:"w-[160px]",children:"Map To"}),e.jsx(At,{children:"Preview"})]})}),e.jsx(ha,{children:d.map((K,Z)=>{var Q;return e.jsxs(Ws,{children:[e.jsx(xt,{className:"font-medium text-xs",children:K}),e.jsx(xt,{children:e.jsxs(Ds,{value:m[String(Z)]||"skip",onValueChange:W=>f(te=>({...te,[String(Z)]:W==="skip"?"":W})),children:[e.jsx(Ps,{className:"h-8 text-xs",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"skip",children:"— Skip —"}),QWs.map(W=>e.jsx(lt,{value:W,children:W.replace(/_/g," ")},W))]})]})}),e.jsx(xt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((Q=o[0])==null?void 0:Q[String(Z)])||"—"})]},Z)})})]})}),!Object.values(m).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(go,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{variant:"outline",onClick:()=>{E()},children:"Back"}),e.jsx(q,{onClick:F,disabled:_||!Object.values(m).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(la,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[C," prospects imported successfully!"]}),e.jsx(q,{onClick:()=>{E(),t(!1)},children:"Close"})]})]})})}function gbt({brokerageId:s}){const{stages:t,prospects:r,isLoading:n,addProspect:a,updateProspect:i,deleteProspect:l}=u$(s),[o,c]=k.useState(!1),[d,u]=k.useState(),[m,f]=k.useState(null),[x,y]=k.useState(!1),[_,b]=k.useState(!1),[j,N]=k.useState(null);if(n)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const C=O=>r.filter(B=>B.stage_id===O),A=(O,B)=>{N(B),O.dataTransfer.effectAllowed="move"},E=O=>{O.preventDefault(),O.dataTransfer.dropEffect="move"},D=(O,B)=>{O.preventDefault(),j&&(i.mutate({id:j,stage_id:B}),N(null))},R=O=>{u(O),c(!0)},F=O=>{f(O),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:[r.length," prospect",r.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{variant:"outline",onClick:()=>b(!0),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(q,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(ui,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(O=>{const B=C(O.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:E,onDrop:K=>D(K,O.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:O.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:O.name}),e.jsx(Xe,{variant:"secondary",className:"text-xs h-5 px-1.5",children:B.length})]}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>R(O.id),children:e.jsx(Ys,{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:B.map(K=>e.jsx(ke,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:O.color},draggable:!0,onDragStart:Z=>A(Z,K.id),onClick:()=>F(K),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Vu,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[K.first_name," ",K.last_name]})]}),K.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ga,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:K.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[K.email&&e.jsx(Ks,{className:"h-3 w-3 text-muted-foreground"}),K.phone&&e.jsx(Mn,{className:"h-3 w-3 text-muted-foreground"}),K.experience_years!=null&&e.jsxs(Xe,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[K.experience_years,"yr"]})]})]})]})},K.id))})]},O.id)})}),e.jsx(gge,{orientation:"horizontal"})]}),e.jsx(dbt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:O=>a.mutate(O),isSubmitting:a.isPending}),e.jsx(pbt,{prospect:m,stages:t,brokerageId:s,open:x,onOpenChange:y,onUpdate:O=>{i.mutate(O),f(B=>B?{...B,...O}:null)},onDelete:O=>l.mutate(O)}),e.jsx(xbt,{open:_,onOpenChange:b,brokerageId:s,stages:t})]})}function Hpe({brokerageId:s}){const{stages:t,prospects:r,isLoading:n,addProspect:a,updateProspect:i,deleteProspect:l}=u$(s),{user:o}=Cs(),c=is(),[d,u]=k.useState(!1),[m,f]=k.useState(null),[x,y]=k.useState(!1),[_,b]=k.useState(!1),[j,N]=k.useState(""),[C,A]=k.useState("all"),[E,D]=k.useState("all"),[R,F]=k.useState("all"),[O,B]=k.useState(null),[K,Z]=k.useState("asc"),[Q,W]=k.useState(new Set),[te,ne]=k.useState(!1),[ae,ue]=k.useState(""),me=k.useMemo(()=>{const ve=new Set;return r.forEach(Qe=>{Qe.current_brokerage&&ve.add(Qe.current_brokerage)}),Array.from(ve).sort()},[r]),{data:de=[]}=pt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:ve,error:Qe}=await U.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Qe)throw Qe;return ve}}),{data:fe=[]}=pt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Qe=[],we=0;for(;;){const{data:nt,error:Se}=await U.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(we,we+1e3-1);if(Se)throw Se;if(Qe=Qe.concat(nt??[]),!nt||nt.length<1e3)break;we+=1e3}return Qe}}),je=k.useMemo(()=>{const ve=new Map;return fe.forEach(Qe=>{ve.has(Qe.prospect_id)||ve.set(Qe.prospect_id,new Set),ve.get(Qe.prospect_id).add(Qe.campaign_id)}),ve},[fe]),xe=ve=>{O===ve?Z(Qe=>Qe==="asc"?"desc":"asc"):(B(ve),Z("asc"))},Ee=({column:ve})=>O!==ve?e.jsx(Uu,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):K==="asc"?e.jsx(qu,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(gm,{className:"h-3.5 w-3.5 ml-1 text-primary"}),Me=ve=>t.find(Qe=>Qe.id===ve),Oe=k.useMemo(()=>{let ve=r.filter(Qe=>{var We,Ce,qe;const we=!j||`${Qe.first_name} ${Qe.last_name}`.toLowerCase().includes(j.toLowerCase())||((We=Qe.email)==null?void 0:We.toLowerCase().includes(j.toLowerCase()))||((Ce=Qe.current_brokerage)==null?void 0:Ce.toLowerCase().includes(j.toLowerCase())),nt=C==="all"||Qe.stage_id===C,Se=E==="all"||Qe.current_brokerage===E;let Ge=!0;return R==="in_campaign"?Ge=je.has(Qe.id):R==="not_in_campaign"?Ge=!je.has(Qe.id):R!=="all"&&(Ge=((qe=je.get(Qe.id))==null?void 0:qe.has(R))??!1),we&&nt&&Se&&Ge});return O&&(ve=[...ve].sort((Qe,we)=>{var We,Ce;let nt=null,Se=null;switch(O){case"name":nt=`${Qe.first_name} ${Qe.last_name||""}`.toLowerCase(),Se=`${we.first_name} ${we.last_name||""}`.toLowerCase();break;case"stage":nt=((We=Me(Qe.stage_id))==null?void 0:We.sort_order)??999,Se=((Ce=Me(we.stage_id))==null?void 0:Ce.sort_order)??999;break;case"brokerage":nt=(Qe.current_brokerage||"").toLowerCase(),Se=(we.current_brokerage||"").toLowerCase();break;case"experience":nt=Qe.experience_years??-1,Se=we.experience_years??-1;break;case"production":nt=(Qe.annual_production||"").toLowerCase(),Se=(we.annual_production||"").toLowerCase();break;case"source":nt=(Qe.source||"").toLowerCase(),Se=(we.source||"").toLowerCase();break;default:return 0}if(nt===Se)return 0;if(nt==null)return 1;if(Se==null)return-1;const Ge=nt0&&Oe.every(ve=>Q.has(ve.id)),ze=Oe.some(ve=>Q.has(ve.id)),Ve=()=>{W(Ie?new Set:new Set(Oe.map(ve=>ve.id)))},Le=ve=>{W(Qe=>{const we=new Set(Qe);return we.has(ve)?we.delete(ve):we.add(ve),we})},$e=Mt({mutationFn:async()=>{if(!ae||!(o!=null&&o.id))throw new Error("Select a campaign");const ve=new Set(fe.filter(nt=>nt.campaign_id===ae).map(nt=>nt.prospect_id)),Qe=Array.from(Q).filter(nt=>!ve.has(nt)).map(nt=>({prospect_id:nt,campaign_id:ae,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Qe.length===0)throw new Error("All selected prospects are already in this campaign");const{error:we}=await U.from("recruit_campaign_assignments").insert(Qe);if(we)throw we;return Qe.length},onSuccess:ve=>{he.success(`${ve} prospect(s) added to campaign`),ne(!1),W(new Set),ue(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:ve=>he.error(ve.message)});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm min-w-[200px]",children:[e.jsx(_n,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search prospects...",value:j,onChange:ve=>N(ve.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[Q.size>0&&e.jsxs(q,{variant:"secondary",onClick:()=>ne(!0),className:"gap-1.5",children:[e.jsx(hn,{className:"h-4 w-4"})," Add ",Q.size," to Campaign"]}),e.jsxs(q,{variant:"outline",onClick:()=>b(!0),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(q,{onClick:()=>u(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(C1,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(Ds,{value:C,onValueChange:A,children:[e.jsx(Ps,{className:"w-[160px] h-8 text-xs",children:e.jsx(Fs,{placeholder:"All stages"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All stages"}),t.map(ve=>e.jsx(lt,{value:ve.id,children:ve.name},ve.id))]})]}),e.jsxs(Ds,{value:E,onValueChange:D,children:[e.jsxs(Ps,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Ga,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(Fs,{placeholder:"All brokerages"})]}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All brokerages"}),me.map(ve=>e.jsx(lt,{value:ve,children:ve},ve))]})]}),e.jsxs(Ds,{value:R,onValueChange:F,children:[e.jsxs(Ps,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(Fs,{placeholder:"Campaign status"})]}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All contacts"}),e.jsx(lt,{value:"in_campaign",children:"In any campaign"}),e.jsx(lt,{value:"not_in_campaign",children:"Not in any campaign"}),de.map(ve=>e.jsxs(lt,{value:ve.id,children:["In: ",ve.name]},ve.id))]})]}),(C!=="all"||E!=="all"||R!=="all")&&e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{A("all"),D("all"),F("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{className:"w-[40px]",children:e.jsx(Ri,{checked:Ie,onCheckedChange:Ve,"aria-label":"Select all",...ze&&!Ie?{"data-state":"indeterminate"}:{}})}),e.jsx(At,{className:"cursor-pointer select-none",onClick:()=>xe("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(Ee,{column:"name"})]})}),e.jsx(At,{className:"cursor-pointer select-none",onClick:()=>xe("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(Ee,{column:"stage"})]})}),e.jsx(At,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>xe("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(Ee,{column:"brokerage"})]})}),e.jsx(At,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(At,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>xe("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(Ee,{column:"experience"})]})}),e.jsx(At,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>xe("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(Ee,{column:"production"})]})}),e.jsx(At,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(At,{className:"w-[50px]"})]})}),e.jsx(ha,{children:Oe.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):Oe.map(ve=>{const Qe=Me(ve.stage_id),we=je.get(ve.id),nt=(we==null?void 0:we.size)??0;return e.jsxs(Ws,{className:"cursor-pointer",onClick:()=>{f(ve),y(!0)},children:[e.jsx(xt,{onClick:Se=>Se.stopPropagation(),children:e.jsx(Ri,{checked:Q.has(ve.id),onCheckedChange:()=>Le(ve.id),"aria-label":`Select ${ve.first_name}`})}),e.jsxs(xt,{className:"font-medium",children:[ve.first_name," ",ve.last_name]}),e.jsx(xt,{children:Qe?e.jsxs(Xe,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Qe.color,color:Qe.color,backgroundColor:`${Qe.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Qe.color}}),Qe.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(xt,{className:"hidden md:table-cell",children:ve.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Ga,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:ve.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(xt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ve.email&&e.jsx(Ks,{className:"h-3.5 w-3.5 text-muted-foreground"}),ve.phone&&e.jsx(Mn,{className:"h-3.5 w-3.5 text-muted-foreground"}),!ve.email&&!ve.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(xt,{className:"hidden lg:table-cell",children:ve.experience_years!=null?`${ve.experience_years} yr`:"—"}),e.jsx(xt,{className:"hidden lg:table-cell",children:ve.annual_production||"—"}),e.jsx(xt,{className:"hidden lg:table-cell",children:nt>0?e.jsxs(Xe,{variant:"secondary",className:"text-xs",children:[nt," campaign",nt>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(xt,{children:e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Se=>{Se.stopPropagation(),l.mutate(ve.id)},children:e.jsx(zr,{className:"h-3.5 w-3.5"})})})]},ve.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Q.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[Q.size," selected · "]}),Oe.length," of ",r.length," prospects"]}),e.jsx(vs,{open:te,onOpenChange:ne,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(_s,{children:e.jsx(bs,{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:Q.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Campaign"}),e.jsxs(Ds,{value:ae,onValueChange:ue,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a campaign..."})}),e.jsx(Ls,{children:de.map(ve=>e.jsxs(lt,{value:ve.id,children:[ve.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",ve.warmth_level,")"]})]},ve.id))})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx(q,{onClick:()=>$e.mutate(),disabled:!ae||$e.isPending,children:$e.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(dbt,{open:d,onOpenChange:u,stages:t,onSubmit:ve=>a.mutate(ve),isSubmitting:a.isPending}),e.jsx(pbt,{prospect:m,stages:t,brokerageId:s,open:x,onOpenChange:y,onUpdate:ve=>{i.mutate(ve),f(Qe=>Qe?{...Qe,...ve}:null)},onDelete:ve=>l.mutate(ve)}),e.jsx(xbt,{open:_,onOpenChange:b,brokerageId:s,stages:t})]})}function ybt({brokerageId:s}){const{stages:t,prospects:r,isLoading:n}=u$(s),a=k.useMemo(()=>{if(!t.length||!r.length)return null;const i=r.length,l=t.find(j=>j.name==="Signed"),o=t.find(j=>j.name==="Onboarded"),c=r.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,m=i>0?Math.round(r.reduce((j,N)=>j+lv(u,new Date(N.created_at)),0)/i):0,f=t.map(j=>({...j,count:r.filter(N=>N.stage_id===j.id).length})),x={};r.forEach(j=>{const N=j.source||"unknown";x[N]=(x[N]||0)+1});const y=Object.entries(x).sort((j,N)=>N[1]-j[1]),_=new Date;_.setDate(_.getDate()-30);const b=r.filter(j=>new Date(j.created_at)>=_).length;return{total:i,signed:c,conversionRate:d,avgDays:m,byStage:f,bySrc:y,recentCount:b}},[t,r]);return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(Dr,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Prospects"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-green-500/10 flex items-center justify-center",children:e.jsx(Wo,{className:"h-5 w-5 text-green-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.conversionRate,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversion Rate"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center",children:e.jsx(jn,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.avgDays,"d"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Days in Pipeline"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-violet-500/10 flex items-center justify-center",children:e.jsx(Hu,{className:"h-5 w-5 text-violet-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.recentCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Added (30 days)"})]})]})})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Pe,{className:"space-y-3",children:a.byStage.map(i=>{const l=a.total>0?i.count/a.total*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:i.color}}),e.jsx("span",{children:i.name})]}),e.jsx("span",{className:"font-medium",children:i.count})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${l}%`,backgroundColor:i.color}})})]},i.id)})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Pe,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Xe,{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 JWs=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function vbt({brokerageId:s}){const{toast:t}=Ba(),{user:r}=Cs(),n=is(),[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,m]=k.useState(null),{data:f=[],isLoading:x}=pt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:A,error:E}=await U.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(E)throw E;return A}}),y=Mt({mutationFn:async A=>{if(A.id){const{error:E}=await U.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 U.from("recruit_email_templates").insert({brokerage_id:s,category:A.category||"Outreach",title:A.title,subject:A.subject,body:A.body,created_by:r==null?void 0:r.id,sort_order:100});if(E)throw E}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),n.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),m(null)},onError:A=>t({title:"Save failed",description:A.message,variant:"destructive"})}),_=Mt({mutationFn:async A=>{const{error:E}=await U.from("recruit_email_templates").delete().eq("id",A);if(E)throw E},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),n.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:A=>t({title:"Delete failed",description:A.message,variant:"destructive"})}),b=(A,E)=>{navigator.clipboard.writeText(A),i(E),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},j=()=>{m({category:"Outreach",title:"",subject:"",body:""}),d(!0)},N=A=>{m(A),d(!0)},C=Array.from(new Set(f.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(q,{onClick:j,size:"sm",className:"gap-1.5",children:[e.jsx(Ys,{className:"h-4 w-4"})," New Template"]})]}),x?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ls,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):C.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(Ks,{className:"h-4 w-4"})," ",A]}),f.filter(E=>E.category===A).map(E=>{const D=E.brokerage_id!==null;return e.jsxs(ke,{className:`transition-all ${l===E.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Pt,{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(Dt,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:E.title}),!D&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),D&&e.jsx(Xe,{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(Xe,{variant:"outline",className:"text-[10px] shrink-0",children:E.category})]})}),l===E.id&&e.jsxs(Pe,{className:"pt-0 space-y-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"text-sm mb-3",children: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(q,{size:"sm",variant:"outline",onClick:()=>b(E.subject,E.id+"-s"),children:[a===E.id+"-s"?e.jsx(la,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>b(E.body,E.id+"-b"),children:[a===E.id+"-b"?e.jsx(la,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>N(E),children:[e.jsx(Ua,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(q,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&_.mutate(E.id)},children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},E.id)})]},A)),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsx(_s,{children:e.jsx(bs,{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(ce,{className:"text-xs",children:"Title"}),e.jsx(Ne,{value:(u==null?void 0:u.title)||"",onChange:A=>m(E=>({...E,title:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:A=>m(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:JWs.map(A=>e.jsx("option",{value:A,children:A},A))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Subject"}),e.jsx(Ne,{value:(u==null?void 0:u.subject)||"",onChange:A=>m(E=>({...E,subject:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Body"}),e.jsx(pr,{value:(u==null?void 0:u.body)||"",onChange:A=>m(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(fn,{children:[e.jsx(q,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(q,{onClick:()=>y.mutate(u||{}),disabled:y.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[y.isPending&&e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const ZKe={call:Mn,email:Ks,text:Ui,meeting:vn,note:En};function bbt({brokerageId:s}){const{data:t,isLoading:r}=pt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:n,error:a}=await U.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(n==null?void 0:n.map(x=>x.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await U.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...n.map(x=>x.created_by),...(l||[]).map(x=>x.created_by)])],{data:d}=await U.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(x=>[x.id,x])),m=zue(new Date,30);return{recruiters:c.map(x=>{var N,C;const y=(l||[]).filter(A=>A.created_by===x),_=y.filter(A=>new Date(A.created_at)>=m),b={};_.forEach(A=>{b[A.activity_type]=(b[A.activity_type]||0)+1});const j=n.filter(A=>A.created_by===x).length;return{id:x,name:((N=u[x])==null?void 0:N.name)||"Unknown",email:((C=u[x])==null?void 0:C.email)||"",totalActivities:y.length,recentActivities:_.length,byType:b,prospectsCreated:j}}).sort((x,y)=>y.recentActivities-x.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Pe,{className:"space-y-4",children:t.recruiters.map((n,a)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-muted/30",children:[e.jsx("div",{className:"flex items-center justify-center h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-sm",children:a+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:n.name})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(n.byType).map(([i,l])=>{const o=ZKe[i]||En;return e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:n.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:n.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},n.id))})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Recent Activity"})}),e.jsx(Pe,{className:"space-y-3",children:t.recentActivities.map(n=>{const a=ZKe[n.activity_type]||En;return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(a,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:n.title}),n.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:As(new Date(n.created_at),"MMM d, h:mm a")})]})]},n.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function _bt({brokerageId:s}){const{toast:t}=Ba(),r=is(),[n,a]=k.useState(!1),[i,l]=k.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=pt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:b,error:j}=await U.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(j)throw j;return b}}),d=[...new Set(o.map(b=>b.referred_by))],{data:u=[]}=pt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:b}=await U.from("profiles").select("id, name, email").in("id",d);return b||[]},enabled:d.length>0}),m=Object.fromEntries(u.map(b=>[b.id,b])),f=Mt({mutationFn:async b=>{const{data:{user:j}}=await U.auth.getUser();if(!j)throw new Error("Not authenticated");const{error:N}=await U.from("recruit_referrals").insert({brokerage_id:s,referred_by:j.id,referee_first_name:b.first_name,referee_last_name:b.last_name||null,referee_email:b.email||null,referee_phone:b.phone||null,referee_current_brokerage:b.current_brokerage||null,notes:b.notes||null});if(N)throw N},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:b=>t({title:"Error",description:b.message,variant:"destructive"})}),x=Mt({mutationFn:async({id:b,status:j,incentive_status:N})=>{const C={updated_at:new Date().toISOString()};j&&(C.status=j),N&&(C.incentive_status=N);const{error:A}=await U.from("recruit_referrals").update(C).eq("id",b);if(A)throw A},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-referrals",s]})}),y=b=>b==="approved"||b==="signed"?e.jsx(la,{className:"h-3 w-3"}):b==="rejected"?e.jsx(ad,{className:"h-3 w-3"}):e.jsx(jn,{className:"h-3 w-3"}),_=b=>b==="approved"||b==="signed"||b==="paid"?"bg-green-500/10 text-green-600 border-green-200":b==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs(q,{onClick:()=>a(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(ke,{className:"py-12 text-center",children:[e.jsx(xl,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(b=>{var j;return e.jsx(ke,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[b.referee_first_name," ",b.referee_last_name]}),e.jsxs(Xe,{variant:"outline",className:_(b.status),children:[y(b.status)," ",b.status]}),b.incentive_status&&e.jsxs(Xe,{variant:"outline",className:_(b.incentive_status),children:[e.jsx(Di,{className:"h-3 w-3 mr-1"})," ",b.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[b.referee_email&&e.jsx("p",{children:b.referee_email}),b.referee_phone&&e.jsx("p",{children:b.referee_phone}),b.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",b.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((j=m[b.referred_by])==null?void 0:j.name)||"Unknown"," • ",As(new Date(b.created_at),"MMM d, yyyy")]})]}),b.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:b.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(Ds,{value:b.status,onValueChange:N=>x.mutate({id:b.id,status:N}),children:[e.jsx(Ps,{className:"h-7 text-xs w-[110px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"pending",children:"Pending"}),e.jsx(lt,{value:"contacted",children:"Contacted"}),e.jsx(lt,{value:"approved",children:"Approved"}),e.jsx(lt,{value:"signed",children:"Signed"}),e.jsx(lt,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(Ds,{value:b.incentive_status||"pending",onValueChange:N=>x.mutate({id:b.id,incentive_status:N}),children:[e.jsx(Ps,{className:"h-7 text-xs w-[100px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"pending",children:"Unpaid"}),e.jsx(lt,{value:"paid",children:"Paid"}),e.jsx(lt,{value:"n/a",children:"N/A"})]})]})]})]})},b.id)})}),e.jsx(vs,{open:n,onOpenChange:a,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),f.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"First Name *"}),e.jsx(Ne,{required:!0,value:i.first_name,onChange:b=>l(j=>({...j,first_name:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Last Name"}),e.jsx(Ne,{value:i.last_name,onChange:b=>l(j=>({...j,last_name:b.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Email"}),e.jsx(Ne,{type:"email",value:i.email,onChange:b=>l(j=>({...j,email:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Phone"}),e.jsx(Ne,{value:i.phone,onChange:b=>l(j=>({...j,phone:b.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Current Brokerage"}),e.jsx(Ne,{value:i.current_brokerage,onChange:b=>l(j=>({...j,current_brokerage:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Notes"}),e.jsx(pr,{value:i.notes,onChange:b=>l(j=>({...j,notes:b.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:f.isPending,children:"Submit"})]})]})]})})]})}function wbt({brokerageId:s}){const{toast:t}=Ba(),r=is(),[n,a]=k.useState(!1),{data:i}=pt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:f,error:x}=await U.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(x)throw x;return f}}),{data:l=[]}=pt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:f,error:x}=await U.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(x)throw x;return f}}),o=Mt({mutationFn:async f=>{const{error:x}=await U.from("brokerages").update({recruit_form_enabled:f}).eq("id",s);if(x)throw x},onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=Mt({mutationFn:async({id:f,status:x})=>{const{error:y}=await U.from("recruit_interest_submissions").update({status:x}).eq("id",f);if(y)throw y},onSuccess:()=>r.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)},m=f=>f==="contacted"||f==="converted"?"bg-green-500/10 text-green-600":f==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:f=>o.mutate(f)})]}),(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(q,{size:"sm",variant:"outline",onClick:u,children:n?e.jsx(la,{className:"h-3.5 w-3.5"}):e.jsx(si,{className:"h-3.5 w-3.5"})}),e.jsx(q,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(un,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Pe,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(xl,{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(f=>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:[f.first_name," ",f.last_name]}),e.jsx(Xe,{variant:"outline",className:m(f.status),children:f.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[f.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ks,{className:"h-3 w-3"}),f.email]}),f.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"}),f.phone]}),f.current_brokerage&&e.jsxs("span",{children:["From: ",f.current_brokerage]}),f.experience_years&&e.jsxs("span",{children:[f.experience_years,"yr exp"]})]}),f.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',f.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:As(new Date(f.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Ds,{value:f.status,onValueChange:x=>c.mutate({id:f.id,status:x}),children:[e.jsx(Ps,{className:"h-7 text-xs w-[110px]",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"new",children:"New"}),e.jsx(lt,{value:"contacted",children:"Contacted"}),e.jsx(lt,{value:"converted",children:"Converted"}),e.jsx(lt,{value:"dismissed",children:"Dismissed"})]})]})]},f.id))})})]})]})}function jbt({brokerageId:s}){const{toast:t}=Ba(),r=is(),[n,a]=k.useState(!1),[i,l]=k.useState({prospect_id:"",title:"",description:"",due_date:As(Dc(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=k.useState("pending"),{data:d=[]}=pt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:E,error:D}=await U.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(D)throw D;return E}}),{data:u=[],isLoading:m}=pt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const E=d.map(F=>F.id);if(!E.length)return[];const{data:D,error:R}=await U.from("recruit_follow_ups").select("*").in("prospect_id",E).order("due_date");if(R)throw R;return D},enabled:d.length>0}),f=Object.fromEntries(d.map(E=>[E.id,E])),x=Mt({mutationFn:async E=>{const{data:{user:D}}=await U.auth.getUser();if(!D)throw new Error("Not authenticated");const{error:R}=await U.from("recruit_follow_ups").insert({prospect_id:E.prospect_id,assigned_to:D.id,title:E.title,description:E.description||null,due_date:new Date(E.due_date).toISOString()});if(R)throw R},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:As(Dc(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:E=>t({title:"Error",description:E.message,variant:"destructive"})}),y=Mt({mutationFn:async({id:E,completed:D})=>{const{error:R}=await U.from("recruit_follow_ups").update({completed_at:D?new Date().toISOString():null}).eq("id",E);if(R)throw R},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),_=u.filter(E=>o==="pending"?!E.completed_at:o==="completed"?!!E.completed_at:!0),b=_.filter(E=>!E.completed_at&&M_(new Date(E.due_date))&&!um(new Date(E.due_date))),j=_.filter(E=>!E.completed_at&&um(new Date(E.due_date))),N=_.filter(E=>!E.completed_at&&!M_(new Date(E.due_date))&&!um(new Date(E.due_date))),C=_.filter(E=>!!E.completed_at),A=E=>{const D=f[E.prospect_id],R=!E.completed_at&&M_(new Date(E.due_date))&&!um(new Date(E.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Ri,{checked:!!E.completed_at,onCheckedChange:F=>y.mutate({id:E.id,completed:F}),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:[D&&e.jsxs(Xe,{variant:"secondary",className:"text-[10px]",children:[D.first_name," ",D.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${R?"text-destructive font-medium":""}`,children:[R?e.jsx(go,{className:"h-3 w-3"}):e.jsx(vn,{className:"h-3 w-3"}),As(new Date(E.due_date),"MMM d, h:mm a")]}),E.is_automated&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},E.id)};return m?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex gap-2",children:["pending","completed","all"].map(E=>e.jsxs(q,{size:"sm",variant:o===E?"default":"outline",onClick:()=>c(E),className:"capitalize text-xs",children:[E," ",E==="pending"&&b.length+j.length+N.length>0&&`(${b.length+j.length+N.length})`]},E))}),e.jsxs(q,{size:"sm",onClick:()=>a(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-destructive flex items-center gap-1",children:[e.jsx(go,{className:"h-3.5 w-3.5"})," Overdue (",b.length,")"]}),b.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(jn,{className:"h-3.5 w-3.5"})," Today (",j.length,")"]}),j.map(A)]}),o!=="completed"&&N.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(vn,{className:"h-3.5 w-3.5"})," Upcoming (",N.length,")"]}),N.map(A)]}),o!=="pending"&&C.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(la,{className:"h-3.5 w-3.5"})," Completed (",C.length,")"]}),C.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(vs,{open:n,onOpenChange:a,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:E=>{E.preventDefault(),x.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{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(D=>({...D,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(ce,{children:"Task *"}),e.jsx(Ne,{required:!0,value:i.title,onChange:E=>l(D=>({...D,title:E.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Details"}),e.jsx(pr,{value:i.description,onChange:E=>l(D=>({...D,description:E.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Due Date *"}),e.jsx(Ne,{type:"datetime-local",required:!0,value:i.due_date,onChange:E=>l(D=>({...D,due_date:E.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(q,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:x.isPending,children:"Schedule"})]})]})]})})]})}const eKs=[{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 Nbt({brokerageId:s}){const{toast:t}=Ba(),r=is(),[n,a]=k.useState(null),{data:i,isLoading:l}=pt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:b,error:j}=await U.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(j)throw j;return b}}),[o,c]=k.useState({brokerage_id:s,hero_headline:"Join Our Team",hero_subtext:"Take your real estate career to the next level.",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",benefits:eKs,testimonials:[],gallery_images:[],calculator_enabled:!1,calculator_config:{headline:"See What You Could Earn With Us",subtext:"Confidential 60-second calculator — no signup required.",commission_split_pct:80,cap_amount:16e3,post_cap_split_pct:100,monthly_fee:99,transaction_fee:0,show_email_capture:!0,email_capture_label:"Want the full breakdown? Enter your email."},lead_magnet_enabled:!1,lead_magnet_config:{title:"Get the Full Comp Plan PDF",description:"See exactly how splits, caps, and fees work — no call required.",button_text:"Email Me the PDF",pdf_url:null},form_style:"classic",confidential_messaging:!0});k.useEffect(()=>{i&&c({id:i.id,brokerage_id:i.brokerage_id,hero_headline:i.hero_headline,hero_subtext:i.hero_subtext||"",hero_image_url:i.hero_image_url,logo_url:i.logo_url,primary_color:i.primary_color,accent_color:i.accent_color,benefits:i.benefits||[],testimonials:i.testimonials||[],gallery_images:i.gallery_images||[],calculator_enabled:i.calculator_enabled??!1,calculator_config:i.calculator_config||{},lead_magnet_enabled:i.lead_magnet_enabled??!1,lead_magnet_config:i.lead_magnet_config||{},form_style:i.form_style||"classic",confidential_messaging:i.confidential_messaging??!0})},[i]);const d=Mt({mutationFn:async()=>{const b={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:j}=await U.from("recruit_landing_page_settings").update(b).eq("id",o.id);if(j)throw j}else{const{error:j}=await U.from("recruit_landing_page_settings").insert(b);if(j)throw j}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:b=>t({title:"Error",description:b.message,variant:"destructive"})}),u=async(b,j)=>{const N=b.name.split(".").pop(),C=`${s}/${j}-${Date.now()}.${N}`,{error:A}=await U.storage.from("recruit-landing").upload(C,b);if(A)throw A;const{data:{publicUrl:E}}=U.storage.from("recruit-landing").getPublicUrl(C);return E},m=async(b,j)=>{var C;const N=(C=b.target.files)==null?void 0:C[0];if(N){a(j);try{const A=await u(N,j);c(E=>({...E,[j]:A})),t({title:"Image uploaded!"})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},f=async b=>{var N;const j=(N=b.target.files)==null?void 0:N[0];if(j){a("gallery");try{const C=await u(j,"gallery");c(A=>({...A,gallery_images:[...A.gallery_images,C]})),t({title:"Gallery image added!"})}catch(C){t({title:"Upload failed",description:C.message,variant:"destructive"})}finally{a(null)}}},x=async(b,j)=>{var C;const N=(C=b.target.files)==null?void 0:C[0];if(N){a(`testimonial-${j}`);try{const A=await u(N,`testimonial-${j}`);c(E=>{const D=[...E.testimonials];return D[j]={...D[j],photo_url:A},{...E,testimonials:D}})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},{data:y}=pt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:b,error:j}=await U.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(j)throw j;return b}}),_=`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(q,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Branding"})}),e.jsx(Pe,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{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(q,{variant:"outline",size:"sm",asChild:!0,disabled:n==="logo_url",children:e.jsxs("span",{children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"}),n==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:b=>m(b,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.primary_color,onChange:b=>c(j=>({...j,primary_color:b.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Ne,{value:o.primary_color,onChange:b=>c(j=>({...j,primary_color:b.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.accent_color,onChange:b=>c(j=>({...j,accent_color:b.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Ne,{value:o.accent_color,onChange:b=>c(j=>({...j,accent_color:b.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Headline"}),e.jsx(Ne,{value:o.hero_headline,onChange:b=>c(j=>({...j,hero_headline:b.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Subtext"}),e.jsx(pr,{value:o.hero_subtext,onChange:b=>c(j=>({...j,hero_subtext:b.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(ce,{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(q,{variant:"outline",size:"sm",asChild:!0,disabled:n==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"}),n==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:b=>m(b,"hero_image_url")})]}),o.hero_image_url&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,hero_image_url:null})),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>c(b=>({...b,benefits:[...b.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Pe,{className:"space-y-3",children:[o.benefits.map((b,j)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Vu,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(Ne,{value:b.icon,onChange:N=>{const C=[...o.benefits];C[j]={...b,icon:N.target.value},c(A=>({...A,benefits:C}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ne,{value:b.title,onChange:N=>{const C=[...o.benefits];C[j]={...b,title:N.target.value},c(A=>({...A,benefits:C}))},placeholder:"Benefit title"}),e.jsx(Ne,{value:b.description,onChange:N=>{const C=[...o.benefits];C[j]={...b,description:N.target.value},c(A=>({...A,benefits:C}))},placeholder:"Short description"})]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>c(N=>({...N,benefits:N.benefits.filter((C,A)=>A!==j)})),children:e.jsx(zr,{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(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{className:"text-base",children:"Testimonials"}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>c(b=>({...b,testimonials:[...b.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Pe,{className:"space-y-3",children:[o.testimonials.map((b,j)=>{var N;return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[b.photo_url?e.jsx("img",{src:b.photo_url,alt:b.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((N=b.name)==null?void 0:N[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:n===`testimonial-${j}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:C=>x(C,j)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ne,{value:b.name,onChange:C=>{const A=[...o.testimonials];A[j]={...b,name:C.target.value},c(E=>({...E,testimonials:A}))},placeholder:"Name"}),e.jsx(Ne,{value:b.role,onChange:C=>{const A=[...o.testimonials];A[j]={...b,role:C.target.value},c(E=>({...E,testimonials:A}))},placeholder:"Role / Title"})]}),e.jsx(pr,{value:b.quote,onChange:C=>{const A=[...o.testimonials];A[j]={...b,quote:C.target.value},c(E=>({...E,testimonials:A}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>c(C=>({...C,testimonials:C.testimonials.filter((A,E)=>E!==j)})),children:e.jsx(zr,{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(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(q,{size:"sm",variant:"outline",asChild:!0,disabled:n==="gallery",children:e.jsxs("span",{children:[e.jsx(zo,{className:"h-3.5 w-3.5 mr-1"}),n==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f})]})]}),e.jsx(Pe,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((b,j)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b,alt:`Gallery ${j+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(q,{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(N=>({...N,gallery_images:N.gallery_images.filter((C,A)=>A!==j)})),children:e.jsx(zr,{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(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ir,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Application Form Style"}),e.jsxs(Ds,{value:o.form_style,onValueChange:b=>c(j=>({...j,form_style:b})),children:[e.jsx(Ps,{className:"mt-1.5",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(lt,{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(ce,{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(Rr,{checked:o.confidential_messaging,onCheckedChange:b=>c(j=>({...j,confidential_messaging:b}))})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(__,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(Rr,{checked:o.calculator_enabled,onCheckedChange:b=>c(j=>({...j,calculator_enabled:b}))})]}),o.calculator_enabled&&e.jsxs(Pe,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highest-converting recruiting tool. Agents enter their GCI and instantly see what they'd earn at your brokerage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Calculator Headline"}),e.jsx(Ne,{value:o.calculator_config.headline||"",onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,headline:b.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Subtext"}),e.jsx(Ne,{value:o.calculator_config.subtext||"",onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,subtext:b.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,commission_split_pct:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,cap_amount:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,post_cap_split_pct:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,monthly_fee:parseFloat(b.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,transaction_fee:parseFloat(b.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(ce,{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(Rr,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:b=>c(j=>({...j,calculator_config:{...j.calculator_config,show_email_capture:b}}))})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(ME,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(Rr,{checked:o.lead_magnet_enabled,onCheckedChange:b=>c(j=>({...j,lead_magnet_enabled:b}))})]}),o.lead_magnet_enabled&&e.jsxs(Pe,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Captures emails from agents not ready to talk. Offer a comp plan PDF, recruiting deck, or guide."}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Title"}),e.jsx(Ne,{value:o.lead_magnet_config.title||"",onChange:b=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,title:b.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Description"}),e.jsx(pr,{rows:2,value:o.lead_magnet_config.description||"",onChange:b=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,description:b.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Button Text"}),e.jsx(Ne,{value:o.lead_magnet_config.button_text||"",onChange:b=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,button_text:b.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ne,{value:o.lead_magnet_config.pdf_url||"",onChange:b=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,pdf_url:b.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(q,{variant:"outline",size:"sm",asChild:!0,disabled:n==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"}),n==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async b=>{var N;const j=(N=b.target.files)==null?void 0:N[0];if(j){a("lead_magnet_pdf");try{const C=await u(j,"lead-magnet");c(A=>({...A,lead_magnet_config:{...A.lead_magnet_config,pdf_url:C}})),t({title:"PDF uploaded!"})}catch(C){t({title:"Upload failed",description:C.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(tKs,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(q,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function tKs({brokerageId:s}){const{data:t=[]}=pt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:r,error:n}=await U.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(n)throw n;return r}});return t.length===0?null:e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(li,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:t.map(r=>e.jsx("div",{className:"flex items-center justify-between gap-3 p-2.5 border rounded-lg text-sm",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[r.first_name||"—"," · ",r.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[As(new Date(r.created_at),"MMM d, yyyy h:mm a")," · via ",r.source]})]})},r.id))})})]})}function kbt({brokerageId:s,trigger:t,initialProspectId:r,open:n,onOpenChange:a}){const[i,l]=k.useState(!1),o=n??i,c=a??l,[d,u]=k.useState("pick-recipients"),[m,f]=k.useState(new Set(r?[r]:[])),[x,y]=k.useState("all"),[_,b]=k.useState(""),[j,N]=k.useState(null),[C,A]=k.useState(""),[E,D]=k.useState(0),[R,F]=k.useState(0),[O,B]=k.useState(""),[K,Z]=k.useState(""),{data:Q}=Kye(),[W,te]=k.useState("default");k.useEffect(()=>{te(Q!=null&&Q.massEmail?"mass_email":Q!=null&&Q.gmail?"gmail":"default")},[Q==null?void 0:Q.massEmail,Q==null?void 0:Q.gmail]);const[ne,ae]=k.useState(null),{prospects:ue,stages:me}=u$(s),de=hbt(),fe=V2(),{data:je=[]}=pt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:ve,error:Qe}=await U.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Qe)throw Qe;return ve??[]},enabled:o&&d==="pick-video"}),xe=k.useCallback(()=>{u("pick-recipients"),f(new Set(r?[r]:[])),y("all"),b(""),N(null),A(""),D(0),F(0),B(""),Z(""),te("default"),ae(null)},[r]),Ee=ve=>{!ve&&(d==="uploading"||d==="processing"||d==="sending")||(c(ve),ve||setTimeout(xe,200))},Me=k.useMemo(()=>ue.filter(ve=>{if(!ve.email||x!=="all"&&ve.stage_id!==x)return!1;if(_){const Qe=_.toLowerCase();if(!`${ve.first_name} ${ve.last_name??""}`.toLowerCase().includes(Qe)&&!ve.email.toLowerCase().includes(Qe))return!1}return!0}),[ue,x,_]),Oe=ve=>{f(Qe=>{const we=new Set(Qe);return we.has(ve)?we.delete(ve):we.add(ve),we})},Ie=()=>{m.size===Me.length?f(new Set):f(new Set(Me.map(ve=>ve.id)))},ze=k.useCallback(async(ve,Qe)=>{u("uploading");try{const we=`Recruiting blast (${m.size} recipients)`,{videoId:nt,libraryId:Se}=await dM(we),{uploadUrl:Ge,apiKey:We}=await uM(nt),Ce=new XMLHttpRequest;Ce.upload.onprogress=St=>{St.lengthComputable&&D(St.loaded/St.total*100)},await new Promise((St,Yt)=>{Ce.onload=()=>Ce.status>=200&&Ce.status<300?St():Yt(new Error("Upload failed")),Ce.onerror=()=>Yt(new Error("Upload failed")),Ce.open("PUT",Ge),Ce.setRequestHeader("AccessKey",We),Ce.send(ve)}),u("processing");const qe=`https://iframe.mediadelivery.net/embed/${Se}/${nt}`;let et=0;const Ze=Date.now(),rt=9e4;for(;et<4&&(await new Promise(Yt=>setTimeout(Yt,3e3)),!(Date.now()-Ze>rt));){const St=await W_(nt);if(et=St.status,F(St.encodeProgress||0),et===5||et===6)throw new Error("Video processing failed")}const ct=await W_(nt),vt=(ct.storageSize||ve.size)/(1024*1024),kt=await fe.mutateAsync({bunny_video_id:nt,playback_url:ct.directPlayUrl||qe,thumbnail_url:ct.thumbnailUrl,preview_url:ct.previewUrl||null,duration_seconds:ct.length||Qe,file_size_mb:vt,title:we,status:et>=4?"ready":"processing",touch_type:"recruiting"});N(kt.id),A(we),u("compose")}catch(we){he.error((we==null?void 0:we.message)||"Failed to upload video"),u("pick-video")}},[m.size,fe]),Ve=k.useCallback(async()=>{if(!(!j||m.size===0)){u("sending");try{const ve=[];for(const nt of m){const Se=await de.mutateAsync({prospect_id:nt,video_id:j,brokerage_id:s,message:K||void 0});ve.push(Se.id)}const{data:Qe,error:we}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:ve,brokerage_id:s,subject_override:O||void 0,message_override:K||void 0,send_via:W}});if(we)throw new Error(we.message);ae({sent:(Qe==null?void 0:Qe.sent)??0,total:(Qe==null?void 0:Qe.total)??ve.length}),u("done"),he.success(`Sent ${(Qe==null?void 0:Qe.sent)??0} of ${(Qe==null?void 0:Qe.total)??ve.length} videos`)}catch(ve){he.error((ve==null?void 0:ve.message)||"Failed to send"),u("compose")}}},[j,m,s,K,O,W,de]),Le=m.size,$e=ue.filter(ve=>!ve.email).length;return e.jsxs(vs,{open:o,onOpenChange:Ee,children:[t&&e.jsx(Yi,{asChild:!0,children:t}),e.jsxs(ys,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(bn,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Le>0&&e.jsxs(Xe,{variant:"secondary",className:"ml-2",children:[e.jsx(Dr,{className:"h-3 w-3 mr-1"}),Le," ",Le===1?"recipient":"recipients"]})]})}),d==="pick-recipients"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search prospects...",value:_,onChange:ve=>b(ve.target.value),className:"pl-9"})]}),e.jsxs(Ds,{value:x,onValueChange:y,children:[e.jsx(Ps,{className:"w-48",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All stages"}),me.map(ve=>e.jsx(lt,{value:ve.id,children:ve.name},ve.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:Ie,className:"hover:underline",children:[m.size===Me.length&&Me.length>0?"Deselect all":"Select all"," ","(",Me.length,")"]}),$e>0&&e.jsxs("span",{children:[$e," prospect(s) hidden — no email on file"]})]}),e.jsx(ui,{className:"flex-1 border rounded-md",children:Me.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No prospects match. Make sure prospects have email addresses."}):e.jsx("div",{className:"divide-y",children:Me.map(ve=>{const Qe=m.has(ve.id),we=me.find(nt=>nt.id===ve.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(Ri,{checked:Qe,onCheckedChange:()=>Oe(ve.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:[ve.first_name," ",ve.last_name]}),we&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",style:{borderColor:we.color,color:we.color},children:we.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ve.email," ",ve.current_brokerage&&`· ${ve.current_brokerage}`]})]})]},ve.id)})})}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>Ee(!1),children:"Cancel"}),e.jsx(q,{disabled:Le===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(ta,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ea,{className:"self-start",children:[e.jsxs(rs,{value:"record",children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(rs,{value:"library",children:[e.jsx(nS,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(fs,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(rf,{className:"h-12 w-12 mx-auto text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a fresh video"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Same video sent to all ",Le," ",Le===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(q,{onClick:()=>u("record"),children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(fs,{value:"library",className:"flex-1 overflow-auto",children:je.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:je.map(ve=>e.jsxs("button",{onClick:()=>{N(ve.id),A(ve.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:p_(ve)?e.jsx("img",{src:p_(ve),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(bn,{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:ve.title||"Untitled"})})]},ve.id))})})]}),e.jsx(fn,{children:e.jsx(q,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(pM,{maxDurationSeconds:600,onRecordingComplete:ze}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(q,{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(ls,{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(ki,{value:d==="uploading"?E:R,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?E:R),"%"]})]}),d==="compose"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4",children:[e.jsxs("div",{className:"rounded-md border p-3 bg-muted/30 flex items-center gap-3",children:[e.jsx(qn,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:C})," selected · sending to ",e.jsx("strong",{children:Le})," recipient",Le===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(Ne,{value:O,onChange:ve=>B(ve.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(ce,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(pr,{value:K,onChange:ve=>Z(ve.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(gIe,{value:W,onChange:te}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(q,{onClick:Ve,disabled:!j||Le===0,children:[e.jsx(hn,{className:"h-4 w-4 mr-2"})," Send to ",Le," ",Le===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(ls,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Le," recipient",Le===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&ne&&e.jsxs("div",{className:"py-12 text-center space-y-4",children:[e.jsx("div",{className:`h-16 w-16 rounded-full mx-auto flex items-center justify-center ${ne.sent===ne.total?"bg-primary/10":"bg-muted"}`,children:ne.sent===ne.total?e.jsx(qn,{className:"h-8 w-8 text-primary"}):e.jsx(go,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[ne.sent," of ",ne.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(q,{onClick:()=>Ee(!1),children:"Done"})]})]})]})}function sKs(s){if(!s)return"—";const t=Math.floor(s/60),r=s%60;return t>0?`${t}m ${r}s`:`${r}s`}function rKs({video:s}){return s.cta_clicked_at?e.jsx(Xe,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(Xe,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(Xe,{variant:"secondary",children:[e.jsx(hn,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(Xe,{variant:"outline",children:[e.jsx(jn,{className:"h-3 w-3 mr-1"}),"Draft"]})}function Sbt({brokerageId:s}){var C,A,E,D;const{data:t=[],isLoading:r}=VWs(s),{data:n=[]}=fbt(s),a=GWs(),i=WWs(),l=mbt(),[o,c]=k.useState(""),[d,u]=k.useState(!1),[m,f]=k.useState({title:"",script_text:"",category:"general"}),[x,y]=k.useState(null),_=t.filter(R=>{var O,B,K,Z;return o?`${((O=R.prospect)==null?void 0:O.first_name)||""} ${((B=R.prospect)==null?void 0:B.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((Z=(K=R.video)==null?void 0:K.title)==null?void 0:Z.toLowerCase().includes(o.toLowerCase())):!0}),b={total:t.length,sent:t.filter(R=>R.sent_at).length,viewed:t.filter(R=>R.view_count>0).length,ctaClicked:t.filter(R=>R.cta_clicked_at).length},j=k.useCallback(R=>{if(!R)return;const F=`${window.location.origin}/recruit-video/${R}`;navigator.clipboard.writeText(F),he.success("Share link copied")},[]);k.useCallback((R,F)=>{l.mutate({id:R,sent_via:F})},[l]);const N=()=>{!m.title.trim()||!m.script_text.trim()||a.mutate({brokerage_id:s,...m},{onSuccess:()=>{f({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:b.total,icon:bn,color:"text-primary"},{label:"Sent",value:b.sent,icon:hn,color:"text-blue-500"},{label:"Viewed",value:b.viewed,icon:Nn,color:"text-amber-500"},{label:"CTA Clicked",value:b.ctaClicked,icon:qn,color:"text-emerald-500"}].map(R=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:`h-10 w-10 rounded-lg bg-muted flex items-center justify-center ${R.color}`,children:e.jsx(R.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:R.label})]})]})},R.label))}),e.jsxs(ta,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"videos",children:[e.jsx(bn,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(rs,{value:"scripts",children:[e.jsx(En,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(rs,{value:"analytics",children:[e.jsx(Mo,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(fs,{value:"videos",children:e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Dt,{className:"text-lg",children:"Video Outreach"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or title...",value:o,onChange:R=>c(R.target.value),className:"pl-9"})]}),e.jsx(kbt,{brokerageId:s,trigger:e.jsxs(q,{size:"sm",className:"gap-1.5",children:[e.jsx(Ks,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Pe,{children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):_.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(bn,{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(R=>{var F,O,B,K,Z,Q,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:[p_(R.video)?e.jsx("img",{src:p_(R.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(bn,{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:sKs(((F=R.video)==null?void 0:F.duration_seconds)??null)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium truncate",children:[(O=R.prospect)==null?void 0:O.first_name," ",(B=R.prospect)==null?void 0:B.last_name]}),e.jsx(rKs,{video:R})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((K=R.video)==null?void 0:K.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[As(new Date(R.created_at),"MMM d, yyyy"),((Z=R.prospect)==null?void 0:Z.current_brokerage)&&` · ${R.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>j(R.share_token),title:"Copy share link",children:e.jsx(si,{className:"h-4 w-4"})}),e.jsxs(q,{variant:R.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>y(R),disabled:!((Q=R.prospect)!=null&&Q.email),title:(W=R.prospect)!=null&&W.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(Ks,{className:"h-4 w-4"}),R.sent_at?"Resend":"Email"]}),R.share_token&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${R.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(un,{className:"h-4 w-4"})})]})]},R.id)})})})]})}),e.jsx(fs,{value:"scripts",children:e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Dt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(vs,{open:d,onOpenChange:u,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{size:"sm",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Title"}),e.jsx(Ne,{value:m.title,onChange:R=>f(F=>({...F,title:R.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Category"}),e.jsxs(Ds,{value:m.category,onValueChange:R=>f(F=>({...F,category:R})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:zCe.map(R=>e.jsx(lt,{value:R.value,children:R.label},R.value))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Script"}),e.jsx(pr,{value:m.script_text,onChange:R=>f(F=>({...F,script_text:R.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(q,{onClick:N,disabled:!m.title.trim()||!m.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Pe,{children:n.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(En,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No scripts yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create teleprompter scripts for common recruiting conversations"})]}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:n.map(R=>{var O;const F=((O=zCe.find(B=>B.value===R.category))==null?void 0:O.label)||R.category;return e.jsx(ke,{className:"relative group",children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Xe,{variant:"outline",className:"text-[10px] mb-2",children:F}),e.jsx("h4",{className:"font-medium text-sm",children:R.title})]}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(R.id),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:R.script_text}),R.is_global&&e.jsx(Xe,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},R.id)})})})]})}),e.jsx(fs,{value:"analytics",children:e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Pe,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:b.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:b.sent,pct:b.total?Math.round(b.sent/b.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:b.viewed,pct:b.sent?Math.round(b.viewed/b.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:b.ctaClicked,pct:b.viewed?Math.round(b.ctaClicked/b.viewed*100):0,color:"bg-emerald-500"}].map(R=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:R.label}),e.jsxs("span",{className:"font-medium",children:[R.count," (",R.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${R.color} rounded-full transition-all`,style:{width:`${R.pct}%`}})})]},R.label))}),t.filter(R=>R.view_count>0).length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h4",{className:"font-medium text-sm mb-3",children:"Most Engaged Prospects"}),e.jsx("div",{className:"space-y-2",children:t.filter(R=>R.view_count>0).sort((R,F)=>F.view_count-R.view_count).slice(0,5).map(R=>{var F,O;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:[(F=R.prospect)==null?void 0:F.first_name," ",(O=R.prospect)==null?void 0:O.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(Nn,{className:"h-3.5 w-3.5"})," ",R.view_count]}),R.cta_clicked_at&&e.jsx(qn,{className:"h-4 w-4 text-emerald-500"})]})]},R.id)})})]})]})]})})]}),x&&e.jsx(ubt,{open:!!x,onOpenChange:R=>{R||y(null)},recruitVideoId:x.id,brokerageId:s,prospectName:`${((C=x.prospect)==null?void 0:C.first_name)||""} ${((A=x.prospect)==null?void 0:A.last_name)||""}`.trim(),prospectEmail:(E=x.prospect)==null?void 0:E.email,videoTitle:(D=x.video)==null?void 0:D.title,defaultMessage:x.message})]})}function Cbt({brokerageId:s}){const{toast:t}=Ba(),r=is(),{stages:n,prospects:a}=u$(s),[i,l]=k.useState(!1),[o,c]=k.useState({title:"",target_count:"10",target_stage_id:"",period_start:As(new Date,"yyyy-MM-dd"),period_end:As(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=pt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:y,error:_}=await U.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(_)throw _;return y}}),m=Mt({mutationFn:async y=>{const{data:{user:_}}=await U.auth.getUser();if(!_)throw new Error("Not authenticated");const{error:b}=await U.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(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),f=Mt({mutationFn:async y=>{const{error:_}=await U.from("recruit_goals").delete().eq("id",y);if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),x=y=>{const _=n.find(j=>j.id===y.target_stage_id);return{count:a.filter(j=>d1(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(q,{size:"sm",onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(ke,{className:"py-12 text-center",children:[e.jsx(Hu,{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:b}=x(y),j=Math.min(100,_/y.target_count*100),N=d1(new Date,{start:new Date(y.period_start),end:new Date(y.period_end)});return e.jsxs(ke,{className:N?"":"opacity-60",children:[e.jsx(Pt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{className:"text-sm",children:y.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[As(new Date(y.period_start),"MMM d")," – ",As(new Date(y.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[N?e.jsx(Xe,{className:"text-[10px]",children:"Active"}):e.jsx(Xe,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>f.mutate(y.id),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Pe,{className:"space-y-2",children:[b&&e.jsxs(Xe,{variant:"outline",className:"text-[10px]",style:{borderColor:b.color,color:b.color},children:["Stage: ",b.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:_}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",y.target_count]})]}),e.jsx(ki,{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(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault(),m.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Goal Title *"}),e.jsx(Ne,{required:!0,value:o.title,onChange:y=>c(_=>({..._,title:y.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Target Count *"}),e.jsx(Ne,{type:"number",min:"1",required:!0,value:o.target_count,onChange:y=>c(_=>({..._,target_count:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{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)"}),n.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(ce,{children:"Start Date"}),e.jsx(Ne,{type:"date",required:!0,value:o.period_start,onChange:y=>c(_=>({..._,period_start:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"End Date"}),e.jsx(Ne,{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(q,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(q,{type:"submit",disabled:m.isPending,children:"Create Goal"})]})]})]})})]})}const nKs={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function Tbt({email:s,mergeValues:t=nKs,selectedSubjectIndex:r,onClose:n}){var c;const a=d=>d.replace(/\{\{first_name\}\}/g,t.first_name).replace(/\{\{brokerage_name\}\}/g,t.brokerage_name).replace(/\{\{city\}\}/g,t.city).replace(/\{\{sender_name\}\}/g,t.sender_name).replace(/\{\{landing_page_link\}\}/g,"https://bestbrokerage.relevelup.com/join-brokerage/your-slug"),i=((c=s.subject_line_options)==null?void 0:c.length)>0?s.subject_line_options:[s.subject_line],l=r??0,o=i[l]||s.subject_line;return e.jsx(vs,{open:!0,onOpenChange:()=>n(),children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(_s,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(bs,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(Xe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(Xe,{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 yIe({brokerageId:s}){const t=is(),{user:r}=Cs(),[n,a]=k.useState(""),[i,l]=k.useState(!1),[o,c]=k.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=pt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:y,error:_}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(_)throw _;return y}}),{data:u}=pt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:y,error:_}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(_)throw _;return y}});k.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]),k.useEffect(()=>{r!=null&&r.id&&U.from("profiles").select("recruit_cta_url").eq("id",r.id).single().then(({data:y})=>a((y==null?void 0:y.recruit_cta_url)||""))},[r==null?void 0:r.id]);const m=async()=>{if(!(r!=null&&r.id))return;l(!0);const{error:y}=await U.from("profiles").update({recruit_cta_url:n.trim()||null}).eq("id",r.id);l(!1),y?he.error(y.message):he.success("Scheduling link saved!")},f=Mt({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 U.from("brokerage_recruit_settings").update(y).eq("id",d.id);if(_)throw _}else{const{error:_}=await U.from("brokerage_recruit_settings").insert(y);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),he.success("Recruiting email settings saved!")},onError:y=>he.error(y.message)}),x=(y,_)=>{c(b=>({...b,merge_fields:{...b.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(vn,{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(Ne,{value:n,onChange:y=>a(y.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(q,{onClick:m,disabled:i,size:"sm",children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save"]})]}),!n&&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(ce,{className:"text-xs",children:"Sender Display Name"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"Sender Email Address"}),e.jsx(Ne,{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(ce,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(Ne,{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(A1,{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(nbt,{brokerageId:s,onVerifiedSelect:y=>{c(_=>({..._,sender_email:y})),he.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(ce,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(Ne,{value:o.merge_fields.brokerage_name||"",onChange:y=>x("brokerage_name",y.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs",children:"{{city}}"}),e.jsx(Ne,{value:o.merge_fields.city||"",onChange:y=>x("city",y.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(Ne,{value:o.merge_fields.sender_name||"",onChange:y=>x("sender_name",y.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(q,{onClick:()=>f.mutate(),disabled:f.isPending,className:"w-full",children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const aKs=F1.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",Yd(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()}}}),XKe=[{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 Mf({onClick:s,active:t,disabled:r,icon:n,tooltip:a}){return e.jsxs(Oc,{children:[e.jsx(Fc,{asChild:!0,children:e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:r,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(n,{className:"h-4 w-4"})})}),e.jsx(Sc,{side:"bottom",className:"text-xs",children:a})]})}function iKs({content:s,onChange:t}){const r=QEe({extensions:[eAe.configure({heading:{levels:[1,2,3]}}),aKs,dAe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),uAe.configure({types:["heading","paragraph"]}),hAe,O0t],content:s,editorProps:{attributes:{class:"prose prose-sm max-w-none focus:outline-none min-h-[350px] px-5 py-4",style:"font-size: 15px; line-height: 1.75; color: #1a1a1a;"}},onUpdate:({editor:i})=>{t(i.getHTML())}});k.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const n=k.useCallback(()=>{if(!r)return;const i=r.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[r]),a=k.useCallback(i=>{r&&r.chain().focus().insertContent(`{{${i}}}`).run()},[r]);return r?e.jsx(J_,{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(Mf,{onClick:()=>r.chain().focus().toggleBold().run(),active:r.isActive("bold"),icon:Jk,tooltip:"Bold"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleItalic().run(),active:r.isActive("italic"),icon:rS,tooltip:"Italic"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleUnderline().run(),active:r.isActive("underline"),icon:cP,tooltip:"Underline"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleStrike().run(),active:r.isActive("strike"),icon:XF,tooltip:"Strikethrough"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleHeading({level:1}).run(),active:r.isActive("heading",{level:1}),icon:KI,tooltip:"Heading 1"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleHeading({level:2}).run(),active:r.isActive("heading",{level:2}),icon:YI,tooltip:"Heading 2"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleHeading({level:3}).run(),active:r.isActive("heading",{level:3}),icon:EF,tooltip:"Heading 3"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleBulletList().run(),active:r.isActive("bulletList"),icon:Zf,tooltip:"Bullet List"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleOrderedList().run(),active:r.isActive("orderedList"),icon:T1,tooltip:"Numbered List"}),e.jsx(Mf,{onClick:()=>r.chain().focus().toggleBlockquote().run(),active:r.isActive("blockquote"),icon:u2,tooltip:"Blockquote"}),e.jsx(Mf,{onClick:()=>r.chain().focus().setHorizontalRule().run(),icon:N_,tooltip:"Divider"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Mf,{onClick:()=>r.chain().focus().setTextAlign("left").run(),active:r.isActive({textAlign:"left"}),icon:NE,tooltip:"Align Left"}),e.jsx(Mf,{onClick:()=>r.chain().focus().setTextAlign("center").run(),active:r.isActive({textAlign:"center"}),icon:jE,tooltip:"Align Center"}),e.jsx(Mf,{onClick:()=>r.chain().focus().setTextAlign("right").run(),active:r.isActive({textAlign:"right"}),icon:kE,tooltip:"Align Right"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Mf,{onClick:n,active:r.isActive("link"),icon:tl,tooltip:"Insert Link"}),e.jsx(cl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Mf,{onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),icon:hS,tooltip:"Undo"}),e.jsx(Mf,{onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),icon:cS,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(q,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{r&&r.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs(q,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(dP,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Sd,{align:"end",className:"w-56",children:XKe.map(i=>e.jsxs(ti,{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(ZEe,{editor:r,className:"[&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[350px] [&_.ProseMirror_p]:my-3 [&_.ProseMirror_ul]:my-3 [&_.ProseMirror_ol]:my-3 [&_.ProseMirror_blockquote]:my-3 [&_.ProseMirror_h1]:my-4 [&_.ProseMirror_h2]:my-3 [&_.ProseMirror_h3]:my-2"})}),e.jsx("div",{className:"border-t px-4 py-2.5 bg-muted/20",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Tags:"}),XKe.map(i=>e.jsx(Xe,{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 oKs({open:s,onClose:t,campaignName:r,stat:n}){return e.jsx(vs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(ys,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Wo,{className:"h-5 w-5 text-primary"}),r," — Engagement Stats"]}),e.jsx(an,{children:"Per-email breakdown of sends, opens, and clicks for this campaign at your brokerage."})]}),!n||n.sent===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(hn,{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(DV,{icon:Ks,color:"text-blue-500",label:"Total Sent",value:n.sent.toLocaleString()}),e.jsx(DV,{icon:Nn,color:"text-amber-500",label:"Opens",value:`${n.opened.toLocaleString()}`,sub:`${n.openRate.toFixed(1)}% open rate`}),e.jsx(DV,{icon:Bc,color:"text-green-500",label:"Clicks",value:`${n.clicked.toLocaleString()}`,sub:`${n.clickRate.toFixed(1)}% click rate`}),e.jsx(DV,{icon:du,color:"text-destructive",label:"Failed",value:n.failed.toLocaleString()})]}),n.lastSentAt&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(jn,{className:"h-3 w-3"})," Last sent: ",As(new Date(n.lastSentAt),"MMM d, yyyy h:mm a")]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 mt-4",children:"Per-Email Performance"}),e.jsx("div",{className:"space-y-2",children:n.byEmail.map(a=>{const i=a.sent_count>0?a.opened_count/a.sent_count*100:0,l=a.sent_count>0?a.clicked_count/a.sent_count*100:0;return e.jsx(ke,{className:"overflow-hidden",children:e.jsxs(Pe,{className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-xs flex items-center justify-center shrink-0",children:["#",a.email_number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.title}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1",children:[e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Ks,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(Nn,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(Bc,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(du,{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 DV({icon:s,color:t,label:r,value:n,sub:a}){return e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-3",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(s,{className:`h-6 w-6 ${t}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xl font-bold leading-none",children:n}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:r}),a&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a})]})]})})})}function Ebt(s){return pt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:r}=await U.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(r)throw r;const n=t??[],a={};for(const i of n){a[i.campaign_id]||(a[i.campaign_id]={campaign_id:i.campaign_id,sent:0,opened:0,clicked:0,failed:0,openRate:0,clickRate:0,byEmail:[],lastSentAt:null});const l=a[i.campaign_id];l.sent+=i.sent_count,l.opened+=i.opened_count,l.clicked+=i.clicked_count,l.failed+=i.failed_count,l.byEmail.push(i),i.last_sent_at&&(!l.lastSentAt||i.last_sent_at>l.lastSentAt)&&(l.lastSentAt=i.last_sent_at)}return Object.values(a).forEach(i=>{i.openRate=i.sent>0?i.opened/i.sent*100:0,i.clickRate=i.sent>0?i.clicked/i.sent*100:0,i.byEmail.sort((l,o)=>l.email_number-o.email_number)}),a}})}const QKe={cold:{icon:_1,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:f2,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:ld,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function Abt({brokerageId:s}){var Ie,ze,Ve,Le;const{user:t}=Cs(),r=is(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,u]=k.useState(!1),[m,f]=k.useState(!1),[x,y]=k.useState("editor"),[_,b]=k.useState(null),[j,N]=k.useState(null),{data:C={}}=Ebt(s),[A,E]=k.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:D}=pt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:$e,error:ve}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(ve)throw ve;return $e}}),{data:R}=pt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:$e,error:ve}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ve)throw ve;return $e}}),F={first_name:"Sarah",brokerage_name:((Ie=R==null?void 0:R.merge_fields)==null?void 0:Ie.brokerage_name)||(D==null?void 0:D.name)||"Your Brokerage",city:((ze=R==null?void 0:R.merge_fields)==null?void 0:ze.city)||(D==null?void 0:D.city)||"Your City",sender_name:((Ve=R==null?void 0:R.merge_fields)==null?void 0:Ve.sender_name)||(R==null?void 0:R.sender_name)||"Your Name"},O=$e=>$e.replace(/\{\{first_name\}\}/g,F.first_name).replace(/\{\{brokerage_name\}\}/g,F.brokerage_name).replace(/\{\{city\}\}/g,F.city).replace(/\{\{sender_name\}\}/g,F.sender_name),{data:B=[],isLoading:K}=pt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:$e,error:ve}=await U.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(ve)throw ve;return $e}}),{data:Z={}}=pt({queryKey:["recruit-campaign-emails",s],enabled:B.length>0,queryFn:async()=>{const $e=B.map(nt=>nt.id),{data:ve,error:Qe}=await U.from("recruit_campaign_emails").select("*").in("campaign_id",$e).order("email_number");if(Qe)throw Qe;const we={};return ve.forEach(nt=>{we[nt.campaign_id]||(we[nt.campaign_id]=[]),we[nt.campaign_id].push(nt)}),we}}),Q=Object.values(Z).flat().map($e=>$e.id),{data:W=[]}=pt({queryKey:["recruit-subject-overrides",s],enabled:Q.length>0,queryFn:async()=>{const{data:$e,error:ve}=await U.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ve)throw ve;return $e}}),te={};W.forEach($e=>{te[$e.campaign_email_id]=$e.selected_subject_index});const ne=Mt({mutationFn:async({campaignEmailId:$e,selectedIndex:ve})=>{const{error:Qe}=await U.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:$e,selected_subject_index:ve,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Qe)throw Qe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),he.success("Subject line updated for your brokerage")},onError:$e=>he.error($e.message)}),ae=Mt({mutationFn:async $e=>{const{error:ve}=await U.from("recruit_campaign_emails").update({title:$e.title,subject_line:$e.subject_line,subject_line_options:$e.subject_line_options,body_html:$e.body_html,body_text:$e.body_text,delay_days:$e.delay_days,updated_at:new Date().toISOString()}).eq("id",$e.id);if(ve)throw ve},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Email template saved!"),l(null)},onError:$e=>he.error($e.message)}),ue=Mt({mutationFn:async()=>{const $e=A.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:ve,error:Qe}=await U.from("recruit_campaigns").insert({name:A.name,slug:$e,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:B.length+1}).select().single();if(Qe)throw Qe;const we=[{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:nt}=await U.from("recruit_campaign_emails").insert(we.map(Se=>({campaign_id:ve.id,...Se,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(nt)throw nt;return ve},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Campaign created with 4 starter emails!"),f(!1),E({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:$e=>he.error($e.message)}),me=Mt({mutationFn:async $e=>{const{error:ve}=await U.from("recruit_campaigns").update({name:$e.name,description:$e.description,theme:$e.theme,goal:$e.goal,primary_cta:$e.primary_cta,warmth_level:$e.warmth_level,sender_name:$e.sender_name,sender_email:$e.sender_email,reply_to_email:$e.reply_to_email,updated_at:new Date().toISOString()}).eq("id",$e.id);if(ve)throw ve},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),he.success("Campaign settings saved!"),b(null)},onError:$e=>he.error($e.message)}),de=Mt({mutationFn:async $e=>{var Ge,We;const{data:ve}=await U.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",$e).order("email_number",{ascending:!1}).limit(1),Qe=((Ge=ve==null?void 0:ve[0])==null?void 0:Ge.email_number)??0,we=((We=ve==null?void 0:ve[0])==null?void 0:We.delay_days)??0,nt=Qe+1,{error:Se}=await U.from("recruit_campaign_emails").insert({campaign_id:$e,email_number:nt,title:`Email ${nt}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:we+7,is_active:!0});if(Se)throw Se},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Email added to campaign!")},onError:$e=>he.error($e.message)}),fe=Mt({mutationFn:async $e=>{const{error:ve}=await U.from("recruit_campaigns").delete().eq("id",$e);if(ve)throw ve},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Campaign deleted")},onError:$e=>he.error($e.message)}),je=Mt({mutationFn:async $e=>{const{error:ve}=await U.from("recruit_campaign_emails").delete().eq("id",$e);if(ve)throw ve},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Email removed from campaign")},onError:$e=>he.error($e.message)}),xe=Mt({mutationFn:async({emailId:$e,delay_days:ve})=>{const{error:Qe}=await U.from("recruit_campaign_emails").update({delay_days:ve,updated_at:new Date().toISOString()}).eq("id",$e);if(Qe)throw Qe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),he.success("Send delay updated")},onError:$e=>he.error($e.message)});if(K)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 Ee=B.filter($e=>!$e.brokerage_id),Me=B.filter($e=>$e.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(q,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(Bo,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(q,{size:"sm",onClick:()=>f(!0),className:"gap-1.5",children:[e.jsx(Ys,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(ke,{className:"border-primary/20 bg-primary/5",children:e.jsx(Pe,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ir,{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(Bo,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),Me.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(PF,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Me.map($e=>Oe($e,!0))})]}),Ee.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(Ir,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Ee.map($e=>Oe($e,!1))})]}),B.length===0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Ks,{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(q,{className:"mt-4",onClick:()=>f(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(oKs,{open:!!j,onClose:()=>N(null),campaignName:(j==null?void 0:j.name)||"",stat:j&&C[j.id]||null}),o&&e.jsx(Tbt,{email:o,mergeValues:F,selectedSubjectIndex:te[o.id],onClose:()=>c(null)}),e.jsx(vs,{open:!!i,onOpenChange:$e=>!$e&&l(null),children:e.jsxs(ys,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(_s,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(sS,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(an,{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(ce,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(Ne,{value:i.title,onChange:$e=>l({...i,title:$e.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(Ne,{type:"number",min:0,max:90,value:i.delay_days,onChange:$e=>l({...i,delay_days:parseInt($e.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(Ne,{value:i.subject_line,onChange:$e=>l({...i,subject_line:$e.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ce,{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(pr,{value:((Le=i.subject_line_options)==null?void 0:Le.join(` `))||"",onChange:$e=>l({...i,subject_line_options:$e.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(ce,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(ta,{value:x,onValueChange:$e=>y($e),children:e.jsxs(ea,{className:"h-7",children:[e.jsx(rs,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(rs,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),x==="editor"?e.jsx(iKs,{content:i.body_html,onChange:$e=>l({...i,body_html:$e})}):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:[F.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:[F.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:O(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:O(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(q,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(q,{size:"sm",onClick:()=>ae.mutate(i),disabled:ae.isPending,className:"gap-1.5",children:[e.jsx(Ml,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(vs,{open:m,onOpenChange:f,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(an,{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(ce,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(Ne,{value:A.name,onChange:$e=>E({...A,name:$e.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(ce,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Ds,{value:A.warmth_level,onValueChange:$e=>E({...A,warmth_level:$e}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(lt,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(lt,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(Ne,{value:A.primary_cta,onChange:$e=>E({...A,primary_cta:$e.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-medium",children:"Description"}),e.jsx(pr,{value:A.description,onChange:$e=>E({...A,description:$e.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-medium",children:"Goal"}),e.jsx(Ne,{value:A.goal,onChange:$e=>E({...A,goal:$e.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(E0,{children:[e.jsx(A0,{asChild:!0,children:e.jsxs(q,{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(Ks,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(Co,{className:"h-3.5 w-3.5"})]})}),e.jsxs(M0,{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(ce,{className:"text-xs",children:"Sender Name"}),e.jsx(Ne,{value:A.sender_name,onChange:$e=>E({...A,sender_name:$e.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs",children:"Sender Email"}),e.jsx(Ne,{value:A.sender_email,onChange:$e=>E({...A,sender_email:$e.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(ce,{className:"text-xs",children:"Reply-To Email"}),e.jsx(Ne,{value:A.reply_to_email,onChange:$e=>E({...A,reply_to_email:$e.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(q,{className:"w-full",disabled:!A.name.trim()||ue.isPending,onClick:()=>ue.mutate(),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(vs,{open:!!_,onOpenChange:$e=>!$e&&b(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(an,{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(ce,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(Ne,{value:_.name,onChange:$e=>b({..._,name:$e.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Ds,{value:_.warmth_level,onValueChange:$e=>b({..._,warmth_level:$e}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"cold",children:"❄️ Cold"}),e.jsx(lt,{value:"warm",children:"☀️ Warm"}),e.jsx(lt,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-medium",children:"Goal"}),e.jsx(Ne,{value:_.goal||"",onChange:$e=>b({..._,goal:$e.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(Ks,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs",children:"Sender Name"}),e.jsx(Ne,{value:_.sender_name||"",onChange:$e=>b({..._,sender_name:$e.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs",children:"Sender Email"}),e.jsx(Ne,{value:_.sender_email||"",onChange:$e=>b({..._,sender_email:$e.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(ce,{className:"text-xs",children:"Reply-To Email"}),e.jsx(Ne,{value:_.reply_to_email||"",onChange:$e=>b({..._,reply_to_email:$e.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(q,{className:"w-full",onClick:()=>me.mutate(_),disabled:me.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(vs,{open:d,onOpenChange:u,children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Default Recruiting Email Settings"}),e.jsx(an,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(yIe,{brokerageId:s})]})})]});function Oe($e,ve){const Qe=QKe[$e.warmth_level]||QKe.cold,we=Qe.icon,nt=Z[$e.id]||[],Se=n===$e.id,Ge=!!($e.sender_name||$e.sender_email||$e.reply_to_email),We=C[$e.id];return e.jsxs(ke,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Pt,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Se?null:$e.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 ${Qe.bg} flex items-center justify-center`,children:e.jsx(we,{className:`h-5 w-5 ${Qe.color}`})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[$e.name,e.jsx(Xe,{variant:$e.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:$e.is_active?"Active":"Draft"}),ve&&e.jsx(Xe,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Ge&&e.jsxs(Xe,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(Ks,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Ur,{className:"text-xs mt-0.5",children:$e.theme||$e.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ce=>{Ce.stopPropagation(),b({...$e})},children:e.jsx(Bo,{className:"h-4 w-4 text-muted-foreground"})}),ve&&e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:Ce=>{Ce.stopPropagation(),confirm("Delete this campaign and all its emails? This cannot be undone.")&&fe.mutate($e.id)},children:e.jsx(zr,{className:"h-4 w-4"})}),We&&We.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(Ks,{className:"h-2.5 w-2.5"})," ",We.sent.toLocaleString()]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${We.openRate.toFixed(1)}% open rate`,children:[e.jsx(Nn,{className:"h-2.5 w-2.5"})," ",We.opened.toLocaleString()," (",We.openRate.toFixed(0),"%)"]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${We.clickRate.toFixed(1)}% click rate`,children:[e.jsx(Bc,{className:"h-2.5 w-2.5"})," ",We.clicked.toLocaleString()," (",We.clickRate.toFixed(1),"%)"]})]}),e.jsxs(q,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ce=>{Ce.stopPropagation(),N($e)},title:"View detailed engagement stats",children:[e.jsx(Mo,{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(Ks,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[nt.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Se?e.jsx(pg,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Co,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Se&&e.jsxs(Pe,{className:"pt-0 pb-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-3 rounded-lg bg-muted/40 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Goal"}),e.jsx("p",{className:"mt-0.5",children:$e.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:$e.primary_cta||"—"})]})]}),Ge&&e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-sm",children:[e.jsxs("p",{className:"text-xs font-semibold text-primary mb-1 flex items-center gap-1",children:[e.jsx(Ks,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[$e.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",$e.sender_name]}),$e.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",$e.sender_email]}),$e.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",$e.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:nt.map((Ce,qe)=>{var et,Ze;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[qert.stopPropagation(),onBlur:rt=>{const ct=parseInt(rt.target.value)||0;ct!==Ce.delay_days&&xe.mutate({emailId:Ce.id,delay_days:ct})},onKeyDown:rt=>{rt.key==="Enter"&&rt.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),Ce.email_number===1?"Sent immediately":`Day ${Ce.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",O(((et=Ce.subject_line_options)==null?void 0:et.length)>0&&Ce.subject_line_options[te[Ce.id]??0]||Ce.subject_line)]})]}),((Ze=Ce.subject_line_options)==null?void 0:Ze.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(Ds,{value:String(te[Ce.id]??0),onValueChange:rt=>ne.mutate({campaignEmailId:Ce.id,selectedIndex:parseInt(rt)}),children:[e.jsx(Ps,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(Fs,{placeholder:"Choose subject line"})}),e.jsx(Ls,{children:Ce.subject_line_options.map((rt,ct)=>e.jsxs(lt,{value:String(ct),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[ct===0?"Primary":`Alt ${ct}`,":"]}),O(rt)]},ct))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Ce),children:e.jsx(Nn,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ce}),y("editor")},children:e.jsx(Ua,{className:"h-4 w-4"})}),ve&&nt.length>1&&e.jsx(q,{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?")&&je.mutate(Ce.id)},children:e.jsx(zr,{className:"h-4 w-4"})})]})]})})]},Ce.id)})}),ve&&e.jsxs(q,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>de.mutate($e.id),disabled:de.isPending,children:[e.jsx(Ys,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},$e.id)}}const JKe={active:{icon:Al,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:Xf,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Ti,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:ad,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},eYe={sent:{icon:Ks,color:"text-blue-500"},opened:{icon:Nn,color:"text-amber-500"},clicked:{icon:Bc,color:"text-green-500"},failed:{icon:du,color:"text-destructive"}};function Mbt({brokerageId:s}){var Le,$e,ve,Qe,we;const{user:t}=Cs(),r=is(),[n,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(new Set),[d,u]=k.useState("assignments"),[m,f]=k.useState(null),[x,y]=k.useState(""),[_,b]=k.useState("all"),[j,N]=k.useState("all"),[C,A]=k.useState(!1),{data:E}=pye(),{data:D={}}=pt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:nt,error:Se}=await U.from("recruit_campaign_emails").select("*").order("email_number");if(Se)throw Se;const Ge={};return(nt??[]).forEach(We=>{Ge[We.campaign_id]||(Ge[We.campaign_id]=[]),Ge[We.campaign_id].push(We)}),Ge}}),{data:R}=pt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:nt,error:Se}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(Se)throw Se;return nt}}),{data:F}=pt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:nt,error:Se}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Se)throw Se;return nt}}),{data:O=[]}=pt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:nt,error:Se}=await U.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Se)throw Se;return nt}}),B={};O.forEach(nt=>{B[nt.campaign_email_id]=nt.selected_subject_index});const K={first_name:((Le=m==null?void 0:m.prospect)==null?void 0:Le.first_name)||"Sarah",brokerage_name:(($e=F==null?void 0:F.merge_fields)==null?void 0:$e.brokerage_name)||(R==null?void 0:R.name)||"Your Brokerage",city:((ve=F==null?void 0:F.merge_fields)==null?void 0:ve.city)||(R==null?void 0:R.city)||"Your City",sender_name:((Qe=F==null?void 0:F.merge_fields)==null?void 0:Qe.sender_name)||(F==null?void 0:F.sender_name)||"Your Name"},Z=nt=>{const Se=D[nt.campaign_id]||[],Ge=nt.current_email_number+1;return Se.find(We=>We.email_number===Ge)||null},{data:Q=[],isLoading:W}=pt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Se=[],Ge=0;for(;;){const{data:We,error:Ce}=await U.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(Ge,Ge+1e3-1);if(Ce)throw Ce;if(Se=Se.concat(We??[]),!We||We.length<1e3)break;Ge+=1e3}return Se}}),{data:te=[]}=pt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:nt,error:Se}=await U.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(Se)throw Se;return nt}}),{data:ne=[]}=pt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:nt,error:Se}=await U.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Se)throw Se;return nt}}),{data:ae=[]}=pt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Se=[],Ge=0;for(;;){const{data:We,error:Ce}=await U.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(Ge,Ge+1e3-1);if(Ce)throw Ce;if(Se=Se.concat(We??[]),!We||We.length<1e3)break;Ge+=1e3}return Se}}),ue=new Set(Q.map(nt=>`${nt.prospect_id}-${nt.campaign_id}`)),me=Mt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const nt=new Date,Se=Array.from(o).filter(We=>!ue.has(`${We}-${i}`)).map(We=>({prospect_id:We,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:nt.toISOString(),started_at:nt.toISOString()}));if(Se.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:Ge}=await U.from("recruit_campaign_assignments").insert(Se);if(Ge)throw Ge},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),he.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:nt=>he.error(nt.message)}),de=Mt({mutationFn:async({id:nt,newStatus:Se})=>{const{error:Ge}=await U.from("recruit_campaign_assignments").update({status:Se,updated_at:new Date().toISOString()}).eq("id",nt);if(Ge)throw Ge},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),he.success("Assignment updated")}}),fe=Mt({mutationFn:async()=>{const{data:nt,error:Se}=await U.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Se)throw Se;return nt},onSuccess:nt=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),r.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),he.success(`Wave sent! ${nt.sent} emails delivered, ${nt.skipped} skipped, ${nt.failed} failed`)},onError:nt=>he.error(`Send failed: ${nt.message}`)}),je=Q.filter(nt=>nt.status==="active").length;Q.filter(nt=>nt.status==="completed").length;const xe=Q.filter(nt=>nt.status==="active"&&nt.next_send_at&&new Date(nt.next_send_at)<=new Date).length,{data:Ee={}}=Ebt(s),Me=Q.reduce((nt,Se)=>nt+Math.max(0,Se.current_email_number||0),0),Oe=Object.values(Ee).reduce((nt,Se)=>nt+Se.opened,0),Ie=Object.values(Ee).reduce((nt,Se)=>nt+Se.clicked,0);Object.values(Ee).reduce((nt,Se)=>nt+Se.failed,0);const ze=Me>0?Math.round(Oe/Me*100):0,Ve=Me>0?Ie/Me*100:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Campaign Assignments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign recruiting campaigns to prospects — emails auto-send weekly via SES"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[xe>0&&e.jsxs(q,{variant:"outline",onClick:()=>{fe.mutate()},disabled:fe.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(zh,{className:"h-4 w-4 mr-1"}),fe.isPending?"Sending...":`Send Next Wave (${xe})`]}),e.jsxs(q,{onClick:()=>a(!0),children:[e.jsx(hn,{className:"h-4 w-4 mr-1"})," Assign Campaign"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Dr,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:Q.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Al,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:je}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ks,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:Me.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Nn,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[ze,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",Oe.toLocaleString(),")"]})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Bc,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ve.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Ie.toLocaleString(),")"]})]})]})})]}),e.jsxs(ta,{value:d,onValueChange:u,children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"assignments",children:["Active Drips (",je,")"]}),e.jsxs(rs,{value:"history",children:["Send History (",Me.toLocaleString(),")"]})]}),e.jsx(fs,{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"})}):Q.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(hn,{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:Q.map(nt=>{var et,Ze,rt,ct;const Se=JKe[nt.status]||JKe.active,Ge=Se.icon,Ce=(D[nt.campaign_id]||[]).length||4,qe=Z(nt);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(Xe,{className:`text-xs ${Se.color} border-0`,children:[e.jsx(Ge,{className:"h-3 w-3 mr-1"}),Se.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(et=nt.prospect)==null?void 0:et.first_name," ",(Ze=nt.prospect)==null?void 0:Ze.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(rt=nt.prospect)==null?void 0:rt.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(ct=nt.campaign)==null?void 0:ct.name," · Email ",nt.current_email_number,"/",Ce,nt.next_send_at&&nt.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(jn,{className:"h-3 w-3 inline"})," Next: ",As(new Date(nt.next_send_at),"MMM d, h:mm a"),new Date(nt.next_send_at)<=new Date&&e.jsx(Xe,{variant:"outline",className:"ml-1 text-[10px] px-1 py-0 border-amber-500 text-amber-600",children:"DUE"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[qe&&e.jsx(q,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>f(nt),children:e.jsx(Nn,{className:"h-3.5 w-3.5"})}),nt.status==="active"&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>de.mutate({id:nt.id,newStatus:"paused"}),children:e.jsx(Xf,{className:"h-3.5 w-3.5"})}),nt.status==="paused"&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>de.mutate({id:nt.id,newStatus:"active"}),children:e.jsx(Al,{className:"h-3.5 w-3.5"})}),(nt.status==="active"||nt.status==="paused")&&e.jsx(q,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>de.mutate({id:nt.id,newStatus:"cancelled"}),children:e.jsx(ad,{className:"h-3.5 w-3.5"})})]})]},nt.id)})})}),e.jsxs(fs,{value:"history",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Filter:"}),e.jsxs(Ds,{value:_,onValueChange:b,children:[e.jsx(Ps,{className:"w-[220px] h-8 text-xs",children:e.jsx(Fs,{placeholder:"All campaigns"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All campaigns"}),ne.map(nt=>e.jsx(lt,{value:nt.id,children:nt.name},nt.id))]})]}),e.jsxs(Ds,{value:j,onValueChange:N,children:[e.jsx(Ps,{className:"w-[160px] h-8 text-xs",children:e.jsx(Fs,{placeholder:"All statuses"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"all",children:"All statuses"}),e.jsx(lt,{value:"sent",children:"Sent (no engagement)"}),e.jsx(lt,{value:"opened",children:"Opened"}),e.jsx(lt,{value:"clicked",children:"Clicked"})]})]}),(_!=="all"||j!=="all")&&e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{b("all"),N("all")},children:"Clear"})]}),(()=>{var Se;const nt=te.filter(Ge=>{var We;return!(_!=="all"&&((We=Ge.campaign_email)==null?void 0:We.campaign_id)!==_||j==="opened"&&!Ge.opened_at||j==="clicked"&&!Ge.clicked_at||j==="sent"&&(Ge.opened_at||Ge.clicked_at))});return nt.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Ks,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:te.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:te.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 ",nt.length," of ",te.length," recent sends",_!=="all"&&` · ${(Se=ne.find(Ge=>Ge.id===_))==null?void 0:Se.name}`]}),e.jsx("div",{className:"space-y-1",children:nt.map(Ge=>{var et,Ze,rt;const We=eYe[Ge.status]||eYe.sent,Ce=We.icon,qe=(et=ne.find(ct=>{var vt;return ct.id===((vt=Ge.campaign_email)==null?void 0:vt.campaign_id)}))==null?void 0:et.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(Ce,{className:`h-4 w-4 flex-shrink-0 ${We.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(Ze=Ge.prospect)==null?void 0:Ze.first_name," ",(rt=Ge.prospect)==null?void 0:rt.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",Ge.email_number]}),qe&&e.jsx(Xe,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:qe})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ge.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[Ge.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(Nn,{className:"h-3 w-3"})," ",As(new Date(Ge.opened_at),"MMM d")]}),Ge.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(Bc,{className:"h-3 w-3"})," ",As(new Date(Ge.clicked_at),"MMM d")]}),e.jsx("span",{children:As(new Date(Ge.sent_at),"MMM d, h:mm a")})]})]},Ge.id)})})]})})()]})]}),e.jsx(vs,{open:n,onOpenChange:nt=>{a(nt),nt||(y(""),c(new Set),l(""))},children:e.jsxs(ys,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(_s,{className:"px-6 pt-6 pb-4",children:[e.jsx(bs,{children:"Assign Campaign to Prospects"}),e.jsx(an,{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(ce,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(Ds,{value:i,onValueChange:l,children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Choose a campaign..."})}),e.jsx(Ls,{children:ne.map(nt=>e.jsx(lt,{value:nt.id,children:nt.name},nt.id))})]})]}),i&&(()=>{const nt=x.toLowerCase(),Se=ae.filter(Ce=>`${Ce.first_name} ${Ce.last_name}`.toLowerCase().includes(nt)||Ce.email.toLowerCase().includes(nt)),Ge=Se.filter(Ce=>!ue.has(`${Ce.id}-${i}`)),We=Ge.length>0&&Ge.every(Ce=>o.has(Ce.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{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(_n,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:x,onChange:Ce=>y(Ce.target.value),className:"pl-9 h-9"})]}),e.jsxs(q,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(We){const Ce=new Set(o);Ge.forEach(qe=>Ce.delete(qe.id)),c(Ce)}else{const Ce=new Set(o);Ge.forEach(qe=>Ce.add(qe.id)),c(Ce)}},children:[e.jsx(vF,{className:"h-3.5 w-3.5 mr-1"}),We?"Deselect All":`Select All (${Ge.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:Se.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:x?"No prospects match your search":"No prospects found for this brokerage"}):Se.map(Ce=>{const qe=ue.has(`${Ce.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${qe?"opacity-40":""}`,children:[e.jsx(Ri,{checked:o.has(Ce.id),disabled:qe,onCheckedChange:et=>{const Ze=new Set(o);et?Ze.add(Ce.id):Ze.delete(Ce.id),c(Ze)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ce.first_name," ",Ce.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ce.email})]}),qe&&e.jsx(Xe,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ce.id)})}),Se.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Se.length," of ",ae.length," prospects",Ge.length0&&e.jsx(ke,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Pe,{className:"pt-3 pb-2 text-sm space-y-1",children:[e.jsxs("p",{className:"font-medium text-primary",children:["✅ Ready to assign ",o.size," prospect",o.size>1?"s":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["• Campaign: ",e.jsx("strong",{children:(we=ne.find(nt=>nt.id===i))==null?void 0:we.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(fn,{className:"px-6 py-4 border-t",children:[e.jsx(q,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(q,{onClick:()=>{me.mutate()},disabled:me.isPending||!i||o.size===0,children:[e.jsx(hn,{className:"h-4 w-4 mr-1"}),me.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),m&&(()=>{const nt=Z(m);return nt?e.jsx(Tbt,{email:nt,mergeValues:K,selectedSubjectIndex:B[nt.id],onClose:()=>f(null)}):null})(),e.jsx(xye,{open:C,onOpenChange:A,hasPending:E==null?void 0:E.hasPendingSes,pendingEmails:E==null?void 0:E.pendingEmails})]})}function Ibt({brokerageId:s}){const t=is(),[r,n]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=k.useRef(!1),{data:d,isLoading:u}=pt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:b,error:j}=await U.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(j)throw j;return b},enabled:!!s});k.useEffect(()=>{if(d){if(c.current){c.current=!1;return}n(d.map(b=>({id:b.id,name:b.name,color:b.color,sort_order:b.sort_order}))),i([]),o(!1)}},[d]);const m=Mt({mutationFn:async()=>{for(const N of a){const{error:C}=await U.from("recruit_pipeline_stages").delete().eq("id",N);if(C)throw C}const b=r.filter(N=>N.id&&!N.isNew),j=r.filter(N=>!N.id||N.isNew);for(const N of b){const{error:C}=await U.from("recruit_pipeline_stages").update({name:N.name,color:N.color,sort_order:N.sort_order}).eq("id",N.id);if(C)throw C}if(j.length>0){const{error:N}=await U.from("recruit_pipeline_stages").insert(j.map(C=>({brokerage_id:s,name:C.name,color:C.color,sort_order:C.sort_order})));if(N)throw N}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),he.success("Pipeline stages saved!"),o(!1)},onError:b=>he.error(b.message)}),f=(b,j,N)=>{n(C=>C.map((A,E)=>E===b?{...A,[j]:N}:A)),o(!0)},x=()=>{const b=r.length>0?Math.max(...r.map(j=>j.sort_order)):0;n(j=>[...j,{name:"",color:"#6366f1",sort_order:b+1,isNew:!0}]),o(!0)},y=b=>{const j=r[b];j.id&&!j.isNew&&i(N=>[...N,j.id]),n(N=>N.filter((C,A)=>A!==b)),o(!0)},_=(b,j)=>{const N=b+j;if(N<0||N>=r.length)return;const C=[...r];[C[b],C[N]]=[C[N],C[b]],C.forEach((A,E)=>A.sort_order=E+1),n(C),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:r.map((b,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===r.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Vu,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:b.color,onChange:N=>f(j,"color",N.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(Ne,{value:b.name,onChange:N=>f(j,"name",N.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(q,{variant:"ghost",size:"icon",onClick:()=>y(j),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(zr,{className:"h-4 w-4"})})]},b.id||`new-${j}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:x,className:"gap-1",children:[e.jsx(Ys,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(q,{size:"sm",onClick:()=>m.mutate(),disabled:m.isPending,className:"gap-1",children:[e.jsx(Ml,{className:"h-4 w-4"})," Save Changes"]})]}),r.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No stages configured. Add stages to build your recruiting pipeline."})]})}function lKs({brokerageId:s}){const{data:t=[],isLoading:r}=pt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:n,error:a}=await U.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return n||[]},enabled:!!s});return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(VE,{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(Xe,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(VE,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No prospects have unsubscribed. Nice work!"})]})}):e.jsx("div",{className:"grid gap-3",children:t.map(n=>e.jsxs(ke,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-base",children:[n.first_name," ",n.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ks,{className:"h-3 w-3"}),n.email]}),n.current_brokerage&&e.jsxs("span",{children:["· ",n.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(vn,{className:"h-3 w-3"}),n.unsubscribed_at&&As(new Date(n.unsubscribed_at),"MMM d, yyyy")]})]})}),n.unsubscribe_reason&&e.jsx(Pe,{className:"pt-0",children:e.jsxs("div",{className:"text-sm bg-muted/40 rounded-md px-3 py-2 italic text-muted-foreground",children:['"',n.unsubscribe_reason,'"']})})]},n.id))})]})}function cKs(){var o;const[s,t]=k.useState(""),[r,n]=k.useState("board"),{data:a=[],isLoading:i}=pt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await U.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(ws,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsx(ws,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[a.length>1?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(Ds,{value:l,onValueChange:t,children:[e.jsxs(Ps,{className:"w-[280px]",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),e.jsx(Fs,{placeholder:"Select brokerage"})]}),e.jsx(Ls,{children:a.map(c=>e.jsx(lt,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(kbt,{brokerageId:l,trigger:e.jsxs(q,{size:"sm",className:"gap-1.5",children:[e.jsx(bn,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(ta,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(ea,{className:"flex-wrap h-auto gap-1",children:[e.jsx(rs,{value:"pipeline",children:"Pipeline"}),e.jsxs(rs,{value:"contacts",children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(rs,{value:"video-outreach",children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(rs,{value:"follow-ups",children:"Follow-ups"}),e.jsx(rs,{value:"referrals",children:"Referrals"}),e.jsx(rs,{value:"interest",children:"Interest Form"}),e.jsx(rs,{value:"landing-page",children:"Landing Page"}),e.jsx(rs,{value:"goals",children:"Goals"}),e.jsx(rs,{value:"metrics",children:"Metrics"}),e.jsx(rs,{value:"templates",children:"Email Templates"}),e.jsxs(rs,{value:"campaigns",children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(rs,{value:"drip-assignments",children:[e.jsx(hn,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(rs,{value:"activity",children:"Recruiter Activity"}),e.jsxs(rs,{value:"email-settings",children:[e.jsx(Bo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(rs,{value:"pipeline-stages",children:[e.jsx(dS,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(rs,{value:"unsubscribed",children:[e.jsx(VE,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(fs,{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(q,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>n("board"),children:[e.jsx(Ep,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(q,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>n("table"),children:[e.jsx(oP,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(gbt,{brokerageId:l}):e.jsx(Hpe,{brokerageId:l})]}),e.jsx(fs,{value:"contacts",children:e.jsx(Hpe,{brokerageId:l})}),e.jsx(fs,{value:"video-outreach",children:e.jsx(Sbt,{brokerageId:l})}),e.jsx(fs,{value:"follow-ups",children:e.jsx(jbt,{brokerageId:l})}),e.jsx(fs,{value:"referrals",children:e.jsx(_bt,{brokerageId:l})}),e.jsx(fs,{value:"interest",children:e.jsx(wbt,{brokerageId:l})}),e.jsx(fs,{value:"landing-page",children:e.jsx(Nbt,{brokerageId:l})}),e.jsx(fs,{value:"goals",children:e.jsx(Cbt,{brokerageId:l})}),e.jsx(fs,{value:"metrics",children:e.jsx(ybt,{brokerageId:l})}),e.jsx(fs,{value:"templates",children:e.jsx(vbt,{brokerageId:l})}),e.jsx(fs,{value:"campaigns",children:e.jsx(Abt,{brokerageId:l})}),e.jsx(fs,{value:"drip-assignments",children:e.jsx(Mbt,{brokerageId:l})}),e.jsx(fs,{value:"activity",children:e.jsx(bbt,{brokerageId:l})}),e.jsx(fs,{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(yIe,{brokerageId:l})]})}),e.jsx(fs,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(Ibt,{brokerageId:l})})}),e.jsx(fs,{value:"unsubscribed",children:e.jsx(lKs,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ga,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function dKs({brokerageId:s}){const[t,r]=k.useState(""),[n,a]=k.useState("all"),{data:i,isLoading:l}=pt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var b;const{data:d,error:u}=await U.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const m=new Map((d||[]).map(j=>[j.id,j]));if(Array.from(m.keys()).length===0)return[];const{data:x}=await U.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:y}=await U.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),_=[];for(const j of x||[]){const N=m.get(j.prospect_id);N&&_.push({id:`v-${j.id}`,kind:"video",prospect_id:j.prospect_id,prospect_name:`${N.first_name||""} ${N.last_name||""}`.trim()||"—",prospect_email:N.email,subject:(b=j.video)!=null&&b.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 N=m.get(j.prospect_id);N&&_.push({id:`c-${j.id}`,kind:"campaign",prospect_id:j.prospect_id,prospect_name:`${N.first_name||""} ${N.last_name||""}`.trim()||"—",prospect_email:N.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,N)=>new Date(N.sent_at).getTime()-new Date(j.sent_at).getTime()),_}}),o=k.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=k.useMemo(()=>(i||[]).filter(u=>{if(n!=="all"&&u.kind!==n)return!1;if(!t)return!0;const m=t.toLowerCase();return u.prospect_name.toLowerCase().includes(m)||(u.prospect_email||"").toLowerCase().includes(m)||u.subject.toLowerCase().includes(m)}),[i,t,n]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Total Sent",value:o.total,icon:hn,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:bn,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:Ks,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:Nn,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:Bc,color:"text-emerald-500"}].map(d=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-3 flex items-center gap-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${d.color}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold leading-tight",children:d.value}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.label})]})]})},d.label))}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Dt,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{value:n,onValueChange:d=>a(d),children:e.jsxs(ea,{className:"h-8",children:[e.jsx(rs,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(rs,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(rs,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search recruit, subject...",value:t,onChange:d=>r(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Pe,{children:l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):c.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ks,{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(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(bn,{className:"h-3 w-3"}),"Video"]}):e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(Ks,{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(Xe,{variant:"destructive",className:"gap-1",children:[e.jsx(go,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(Xe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Bc,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(Xe,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(Xe,{variant:"secondary",className:"gap-1",children:[e.jsx(hn,{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:[As(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:As(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(Nn,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx(q,{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(un,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function uKs(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:r}=Cs(),[n,a]=k.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(ws,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ga,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(ws,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[s.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(Ds,{value:i,onValueChange:r,children:[e.jsxs(Ps,{className:"w-[280px]",children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),e.jsx(Fs,{placeholder:"Select brokerage"})]}),e.jsx(Ls,{children:s.map(o=>e.jsx(lt,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(ta,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(ea,{className:"flex-wrap h-auto gap-1",children:[e.jsx(rs,{value:"pipeline",children:"Pipeline"}),e.jsxs(rs,{value:"contacts",children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(rs,{value:"video-outreach",children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(rs,{value:"follow-ups",children:"Follow-ups"}),e.jsx(rs,{value:"referrals",children:"Referrals"}),e.jsx(rs,{value:"interest",children:"Interest Form"}),e.jsx(rs,{value:"landing-page",children:"Landing Page"}),e.jsx(rs,{value:"goals",children:"Goals"}),e.jsx(rs,{value:"metrics",children:"Metrics"}),e.jsx(rs,{value:"templates",children:"Email Templates"}),e.jsxs(rs,{value:"campaigns",children:[e.jsx(Ks,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(rs,{value:"drip-assignments",children:[e.jsx(hn,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(rs,{value:"sent-emails",children:[e.jsx(n2,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(rs,{value:"activity",children:"Recruiter Activity"}),e.jsxs(rs,{value:"email-settings",children:[e.jsx(Bo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(rs,{value:"pipeline-stages",children:[e.jsx(dS,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(fs,{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(q,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(Ep,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(q,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(oP,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(gbt,{brokerageId:i}):e.jsx(Hpe,{brokerageId:i})]}),e.jsx(fs,{value:"contacts",children:e.jsx(Hpe,{brokerageId:i})}),e.jsx(fs,{value:"video-outreach",children:e.jsx(Sbt,{brokerageId:i})}),e.jsx(fs,{value:"follow-ups",children:e.jsx(jbt,{brokerageId:i})}),e.jsx(fs,{value:"referrals",children:e.jsx(_bt,{brokerageId:i})}),e.jsx(fs,{value:"interest",children:e.jsx(wbt,{brokerageId:i})}),e.jsx(fs,{value:"landing-page",children:e.jsx(Nbt,{brokerageId:i})}),e.jsx(fs,{value:"goals",children:e.jsx(Cbt,{brokerageId:i})}),e.jsx(fs,{value:"metrics",children:e.jsx(ybt,{brokerageId:i})}),e.jsx(fs,{value:"templates",children:e.jsx(vbt,{brokerageId:i})}),e.jsx(fs,{value:"campaigns",children:e.jsx(Abt,{brokerageId:i})}),e.jsx(fs,{value:"drip-assignments",children:e.jsx(Mbt,{brokerageId:i})}),e.jsx(fs,{value:"sent-emails",children:e.jsx(dKs,{brokerageId:i})}),e.jsx(fs,{value:"activity",children:e.jsx(bbt,{brokerageId:i})}),e.jsx(fs,{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(yIe,{brokerageId:i})]})}),e.jsx(fs,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(Ibt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ga,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function hKs(){const[s,t]=k.useState(""),{data:r,isLoading:n}=pt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await U.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await U.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await U.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],m=d||[],f=o.map(x=>{const y=u.filter(j=>j.brokerage_id===x.id),_=m.filter(j=>j.brokerage_id===x.id),b=y.length>0?y.reduce((j,N)=>N.created_at>j?N.created_at:j,y[0].created_at):null;return{brokerage_id:x.id,brokerage_name:x.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:b,categories:_.length}});return f.sort((x,y)=>y.total_items-x.total_items),f}}),a=(r||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(ws,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uh,{title:"Brokerage Content Activity",description:"See which brokerages are creating custom content for their agents"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with content uploaded"})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"across all brokerages"})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"registered"})]})]})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(da,{children:[e.jsx(ua,{children:e.jsxs(Ws,{children:[e.jsx(At,{children:"Brokerage"}),e.jsx(At,{className:"text-center",children:"Total"}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(bn,{className:"h-3 w-3"})," Videos"]})}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(En,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Ul,{className:"h-3 w-3"})," Links"]})}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(xu,{className:"h-3 w-3"})," Events"]})}),e.jsx(At,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(zo,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(At,{className:"text-center",children:"Categories"}),e.jsx(At,{children:"Last Upload"})]})}),e.jsx(ha,{children:n?e.jsx(Ws,{children:e.jsx(xt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(Ws,{children:e.jsx(xt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(Ws,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(xt,{className:"text-center",children:o.total_items>0?e.jsx(Xe,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-center",children:o.videos||"–"}),e.jsx(xt,{className:"text-center",children:o.pdfs||"–"}),e.jsx(xt,{className:"text-center",children:o.links||"–"}),e.jsx(xt,{className:"text-center",children:o.events||"–"}),e.jsx(xt,{className:"text-center",children:o.graphics||"–"}),e.jsx(xt,{className:"text-center",children:o.categories||"–"}),e.jsx(xt,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:As(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const mKs=[{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:"📉"}],tYe=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(gu,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(gu,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(mh,{className:"h-4 w-4"})}],fKs=[{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:"📰"}],sYe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),rYe={"luxury-dark":RAe,"modern-clean":OAe,"bold-colorful":FAe,editorial:zAe};function pKs(){const[s,t]=k.useState(""),[r,n]=k.useState("address"),[a,i]=k.useState(!1),[l,o]=k.useState([]),[c,d]=k.useState(null),[u,m]=k.useState(0),[f,x]=k.useState("just-listed"),[y,_]=k.useState(["instagram-square"]),[b,j]=k.useState("luxury-dark"),[N,C]=k.useState(!1),[A,E]=k.useState(""),[D,R]=k.useState(""),[F,O]=k.useState(""),[B,K]=k.useState(!1),[Z,Q]=k.useState(!1),[W,te]=k.useState([]),[ne,ae]=k.useState("search"),ue=k.useRef({});k.useEffect(()=>{(async()=>{const{data:{user:ze}}=await U.auth.getUser();if(!ze)return;const{data:Ve}=await U.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",ze.id).single();if(Ve){E(Ve.name||""),O(Ve.avatar_url||"");const Le=Ve.brokerages;R((Le==null?void 0:Le.name)||"")}})()},[]);const me=async()=>{var Ie;if(s.trim()){i(!0),o([]);try{const{data:ze,error:Ve}=await U.functions.invoke("repliers-mls-search",{body:{searchType:r,query:s.trim()}});if(Ve)throw Ve;if(ze.error)throw new Error(ze.error);o(ze.listings||[]),((Ie=ze.listings)==null?void 0:Ie.length)===0&&he.info("No listings found. Try a different search.")}catch(ze){he.error(ze.message||"Search failed")}finally{i(!1)}}},de=Ie=>{var ze;d(Ie),m(0),ae("customize"),Ie.soldDate||(ze=Ie.status)!=null&&ze.toLowerCase().includes("sold")?x("just-sold"):x("just-listed")},fe=Ie=>{_(ze=>ze.includes(Ie)?ze.filter(Ve=>Ve!==Ie):[...ze,Ie])},je=k.useCallback(async()=>{if(!(!c||y.length===0)){K(!0),te([]),ae("generate");try{await new Promise(ze=>setTimeout(ze,500));const Ie=[];for(const ze of y){const Ve=`${b}-${ze}`,Le=ue.current[Ve];if(!Le)continue;const $e=Uk[ze],ve=await DAe(Le,{width:$e.width,height:$e.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ie.push({format:ze,imageUrl:ve})}te(Ie),he.success(`Generated ${Ie.length} social post${Ie.length>1?"s":""}!`)}catch(Ie){he.error(Ie.message||"Generation failed")}finally{K(!1)}}},[c,y,b,u,N,A,D,F,f]),xe=async()=>{if(!(!c||y.length===0)){K(!0),te([]),ae("generate");try{const Ie={...c,photos:c.photos.length>0?[c.photos[u]]:[]},ze=[];for(const Ve of y){const{data:Le,error:$e}=await U.functions.invoke("generate-listing-social-post",{body:{listing:Ie,postType:f,format:Ve,branding:N?{enabled:!0,agentName:A,brokerage:D}:{enabled:!1}}});if($e)throw $e;if(Le.error)throw new Error(Le.error);ze.push({format:Ve,imageUrl:Le.imageUrl})}te(ze),he.success(`Generated ${ze.length} AI post${ze.length>1?"s":""}!`)}catch(Ie){he.error(Ie.message||"AI generation failed")}finally{K(!1)}}},Ee=()=>Z?xe():je(),Me=(Ie,ze)=>{var Le;const Ve=document.createElement("a");Ve.href=Ie,Ve.download=`${((Le=c==null?void 0:c.address)==null?void 0:Le.replace(/\s+/g,"-"))||"listing"}-${f}-${ze}.png`,document.body.appendChild(Ve),Ve.click(),document.body.removeChild(Ve)},Oe=c?{listing:c,postType:f,format:"instagram-square",branding:N?{enabled:!0,agentName:A,brokerage:D,agentPhotoUrl:F||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Uh,{title:"Social Post Generator",description:"Search MLS listings and generate stunning social media posts"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsxs("button",{onClick:()=>ae("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ne==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(_n,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&ae("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ne==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(Ir,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full ${ne==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(zo,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),ne==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(_n,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx($ct,{})]}),e.jsx(Ur,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx(ta,{value:r,onValueChange:Ie=>n(Ie),children:e.jsxs(ea,{children:[e.jsxs(rs,{value:"address",children:[e.jsx(Ma,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(rs,{value:"mls",children:[e.jsx(Fh,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:s,onChange:Ie=>t(Ie.target.value),placeholder:r==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ie=>Ie.key==="Enter"&&me()}),e.jsxs(q,{onClick:me,disabled:a||!s.trim(),children:[a?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(_n,{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((Ie,ze)=>{var Ve;return e.jsx(ke,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>de(Ie),children:e.jsx(Pe,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-32 h-28 flex-shrink-0 bg-muted rounded-l-lg overflow-hidden",children:(Ve=Ie.photos)!=null&&Ve[0]?e.jsx("img",{src:Ie.photos[0],alt:Ie.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Pn,{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:sYe(Ie.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ie.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ie.city,", ",Ie.state," ",Ie.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ie.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(e2,{className:"h-3 w-3"})," ",Ie.bedrooms]}),Ie.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(of,{className:"h-3 w-3"})," ",Ie.bathrooms]}),Ie.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(zE,{className:"h-3 w-3"})," ",Ie.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:Ie.mlsNumber}),e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:Ie.status})]})]})]})})},Ie.mlsNumber||ze)})})]})]}),ne==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(ke,{className:"lg:col-span-1",children:[e.jsx(Pt,{className:"pb-3",children:e.jsx(Dt,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Pe,{className:"space-y-3",children:[c.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.photos[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(q,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>m(Ie=>Math.max(0,Ie-1)),disabled:u===0,children:e.jsx(jl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx(q,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>m(Ie=>Math.min(c.photos.length-1,Ie+1)),disabled:u===c.photos.length-1,children:e.jsx(Ia,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:sYe(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(q,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ae("search"),d(null)},children:[e.jsx(ev,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(ke,{className:"lg:col-span-2",children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Ur,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dl,{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(Rr,{checked:Z,onCheckedChange:Q}),Z&&e.jsx(p0,{className:"h-4 w-4 text-purple-500"})]})]}),!Z&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(dl,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:fKs.map(Ie=>e.jsxs("button",{onClick:()=>j(Ie.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${b===Ie.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ie.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ie.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ie.description})]},Ie.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:mKs.map(Ie=>e.jsxs("button",{onClick:()=>x(Ie.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${f===Ie.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ie.icon})," ",Ie.label]},Ie.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:tYe.map(Ie=>e.jsxs("button",{onClick:()=>fe(Ie.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${y.includes(Ie.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ie.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:Ie.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ie.dimensions})]})]},Ie.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ce,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(qi,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(Rr,{checked:N,onCheckedChange:C})]}),N&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[F&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:F,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(ce,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(Ne,{value:A,onChange:Ie=>E(Ie.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(Ne,{value:D,onChange:Ie=>R(Ie.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!Z&&Oe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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*(Uk[y[0]||"instagram-square"].height/Uk[y[0]||"instagram-square"].width)},children:(()=>{const Ie=rYe[b],ze=y[0]||"instagram-square";return e.jsx(Ie,{...Oe,format:ze})})()})})]}),e.jsx(q,{onClick:Ee,disabled:y.length===0||B,size:"lg",className:"w-full gap-2",children:B?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-5 w-5 animate-spin"})," Generating ",y.length," post",y.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[Z?e.jsx(p0,{className:"h-5 w-5"}):e.jsx(Ir,{className:"h-5 w-5"}),"Generate ",y.length," Social Post",y.length>1?"s":"",Z&&e.jsx(Xe,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),ne==="generate"&&e.jsxs("div",{className:"space-y-4",children:[B&&e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ls,{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(q,{variant:"outline",size:"sm",onClick:()=>ae("customize"),children:[e.jsx(ev,{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((Ie,ze)=>{const Ve=tYe.find(Le=>Le.value===Ie.format);return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ie.imageUrl,alt:`${Ie.format} social post`,className:"w-full rounded"})}),e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ve==null?void 0:Ve.icon,e.jsx("span",{className:"text-sm font-medium",children:Ve==null?void 0:Ve.label})]}),e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:Ve==null?void 0:Ve.dimensions})]}),e.jsxs(q,{size:"sm",className:"w-full gap-1.5",onClick:()=>Me(Ie.imageUrl,Ie.format),children:[e.jsx(li,{className:"h-3.5 w-3.5"})," Download"]})]})]},ze)})})]})]}),ne==="generate"&&!Z&&c&&Oe&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:y.map(Ie=>{const ze=rYe[b],Ve=Uk[Ie];return e.jsx("div",{style:{width:Ve.width,height:Ve.height},children:e.jsx(ze,{ref:Le=>{ue.current[`${b}-${Ie}`]=Le},...Oe,format:Ie})},`${b}-${Ie}`)})})]})})}function xKs(){return pt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await U.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function gKs(s){return pt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(r)throw r;return t!=null&&t.modules&&(t.modules.sort((n,a)=>n.sort_order-a.sort_order),t.modules.forEach(n=>{n.resources&&n.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function yKs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("lms_courses").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function Pbt(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("lms_courses").update({...r,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function vKs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("lms_courses").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function bKs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("lms_modules").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function _Ks(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("lms_modules").update({...r,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function wKs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("lms_modules").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function jKs(){const s=is();return Mt({mutationFn:async t=>{const{data:r,error:n}=await U.from("lms_module_resources").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function NKs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("lms_module_resources").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function kKs(){const s=is();return Mt({mutationFn:async({courseId:t,accessRules:r})=>{const{error:n}=await U.from("lms_course_access").delete().eq("course_id",t);if(n)throw n;if(r.length>0){const a=r.map(l=>({...l,course_id:t})),{error:i}=await U.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function SKs(){return pt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await U.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function CKs(s){return pt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(r)throw r;return t!=null&&t.modules&&(t.modules.sort((n,a)=>n.sort_order-a.sort_order),t.modules.forEach(n=>{n.resources&&n.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function Lbt(s){return pt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("lms_progress").select("*").eq("course_id",s);if(r)throw r;return t},enabled:!!s})}function TKs(){const s=is();return Mt({mutationFn:async({courseId:t,moduleId:r,userId:n})=>{const{data:a,error:i}=await U.from("lms_progress").upsert({user_id:n,course_id:t,module_id:r,completed:!0,completed_at:new Date().toISOString()},{onConflict:"user_id,module_id"}).select().single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["lms-progress"]})})}function EKs(){const{user:s}=Cs(),t=qr(),{data:r,isLoading:n}=xKs(),a=yKs(),i=Pbt(),l=vKs(),[o,c]=k.useState(!1),[d,u]=k.useState(""),[m,f]=k.useState(""),[x,y]=k.useState(!0),_=async()=>{if(!(!d.trim()||!s))try{const N=await a.mutateAsync({title:d.trim(),description:m.trim()||void 0,is_sequential:x,created_by:s.id});he.success("Course created"),c(!1),u(""),f(""),y(!0),t(`/admin/lms/${N.id}`)}catch{he.error("Failed to create course")}},b=async N=>{try{await i.mutateAsync({id:N.id,is_published:!N.is_published}),he.success(N.is_published?"Course unpublished":"Course published")}catch{he.error("Failed to update course")}},j=async N=>{if(confirm("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(N),he.success("Course deleted")}catch{he.error("Failed to delete")}};return e.jsxs(ws,{title:"LevelUp U - Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(ch,{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(q,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(Mo,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(q,{onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),n?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(N=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Pt,{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"})]})},N))}):r!=null&&r.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(N=>{var D,R;const C=((R=(D=N.modules)==null?void 0:D[0])==null?void 0:R.count)??0,A=N.access||[],E=A.length===0?"No access set":A.some(F=>F.access_type==="all")?"All agents":`${A.length} rule(s)`;return e.jsxs(ke,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${N.id}`),children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Dt,{className:"text-base truncate",children:N.title}),N.description&&e.jsx(Ur,{className:"mt-1 line-clamp-2",children:N.description})]}),e.jsx(Xe,{variant:N.is_published?"default":"secondary",className:"ml-2 shrink-0",children:N.is_published?"Published":"Draft"})]})}),e.jsxs(Pe,{className:"pt-0",children:[e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vm,{className:"h-3.5 w-3.5"}),C," module",C!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[N.is_sequential?e.jsx(T1,{className:"h-3.5 w-3.5"}):e.jsx(HE,{className:"h-3.5 w-3.5"}),N.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Dr,{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(q,{size:"sm",variant:"ghost",onClick:F=>{F.stopPropagation(),b(N)},children:[N.is_published?e.jsx(Wf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1"}),N.is_published?"Unpublish":"Publish"]}),e.jsx(q,{size:"sm",variant:"ghost",className:"text-destructive",onClick:F=>{F.stopPropagation(),j(N.id)},children:e.jsx(zr,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(ci,{className:"h-4 w-4 text-muted-foreground"})]})]})]},N.id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(vm,{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(q,{onClick:()=>c(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create New Course"}),e.jsx(an,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Course Title"}),e.jsx(Ne,{value:d,onChange:N=>u(N.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{value:m,onChange:N=>f(N.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(Rr,{checked:x,onCheckedChange:y})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(q,{onClick:_,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function AKs(){const{courseId:s}=xo(),t=qr(),{data:r,isLoading:n}=gKs(s),a=Pbt(),i=bKs(),l=_Ks(),o=wKs(),c=jKs(),d=NKs(),u=kKs(),{data:m}=pt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:Ze}=await U.from("brokerages").select("id, name").order("name");return Ze||[]}}),[f,x]=k.useState(null),[y,_]=k.useState(!1),[b,j]=k.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[N,C]=k.useState(null),[A,E]=k.useState({title:"",resource_type:"link",url:""}),[D,R]=k.useState(new Set),[F,O]=k.useState(null),[B,K]=k.useState(0),[Z,Q]=k.useState(!1),W=k.useRef(null),te=k.useRef(null),[ne,ae]=k.useState(!1),[ue,me]=k.useState(""),[de,fe]=k.useState(""),[je,xe]=k.useState(""),[Ee,Me]=k.useState(!1);if(n)return e.jsx(ws,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!r)return e.jsx(ws,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(q,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const Oe=r.modules||[],Ie=r.access||[],ze=Ie.some(Ze=>Ze.access_type==="all"),Ve=Ie.filter(Ze=>Ze.access_type==="brokerage").map(Ze=>Ze.brokerage_id),Le=(m||[]).filter(Ze=>Ze.name.toLowerCase().includes(ue.toLowerCase())),$e=Ze=>{const rt=new Set(D);rt.has(Ze)?rt.delete(Ze):rt.add(Ze),R(rt)},ve=async()=>{if(!F)return null;Q(!0),K(0);try{const{data:Ze,error:rt}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:F.name}});if(rt)throw new Error(rt.message);const{videoId:ct,libraryId:vt}=Ze,{data:kt,error:St}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ct,libraryId:vt}});if(St)throw new Error(St.message);const Yt=new XMLHttpRequest;return await new Promise((es,zs)=>{Yt.upload.onprogress=sr=>{sr.lengthComputable&&K(Math.round(sr.loaded/sr.total*100))},Yt.onload=()=>Yt.status>=200&&Yt.status<300?es():zs(new Error(`Upload failed: ${Yt.status}`)),Yt.onerror=()=>zs(new Error("Upload failed")),Yt.open("PUT",kt.uploadUrl),Yt.setRequestHeader("AccessKey",kt.apiKey),Yt.send(F)}),`https://iframe.mediadelivery.net/embed/${vt}/${ct}`}catch(Ze){return console.error("Bunny upload error:",Ze),he.error("Video upload failed"),null}finally{Q(!1),K(0)}},Qe=async()=>{if(b.title.trim())try{let Ze=b.video_url.trim()||void 0;if(F){const rt=await ve();if(!rt)return;Ze=rt}await i.mutateAsync({course_id:r.id,title:b.title.trim(),description:b.description.trim()||void 0,video_url:Ze,text_content:b.text_content.trim()||void 0,duration_minutes:b.duration_minutes?parseInt(b.duration_minutes):void 0,sort_order:Oe.length}),he.success("Module added"),_(!1),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),O(null)}catch{he.error("Failed to add module")}},we=async()=>{if(f)try{let Ze=b.video_url.trim()||null;if(F){const rt=await ve();if(!rt)return;Ze=rt}await l.mutateAsync({id:f.id,title:b.title.trim(),description:b.description.trim()||null,video_url:Ze,text_content:b.text_content.trim()||null,duration_minutes:b.duration_minutes?parseInt(b.duration_minutes):null}),he.success("Module updated"),x(null),O(null)}catch{he.error("Failed to update")}},nt=async Ze=>{if(confirm("Delete this module?"))try{await o.mutateAsync(Ze),he.success("Module deleted")}catch{he.error("Failed to delete")}},Se=async Ze=>{if(A.title.trim())try{await c.mutateAsync({module_id:Ze,title:A.title.trim(),resource_type:A.resource_type,url:A.url.trim()||void 0}),he.success("Resource added"),C(null),E({title:"",resource_type:"link",url:""})}catch{he.error("Failed to add resource")}},Ge=async()=>{try{await u.mutateAsync({courseId:r.id,accessRules:[{access_type:"all"}]}),he.success("Access updated: All brokerages / all agents")}catch{he.error("Failed to update access")}},We=async Ze=>{const rt=Ie.filter(St=>St.access_type==="brokerage").map(St=>St.brokerage_id),ct=rt.includes(Ze);let vt;ct?vt=rt.filter(St=>St!==Ze):vt=[...rt,Ze];const kt=vt.map(St=>({access_type:"brokerage",brokerage_id:St}));try{await u.mutateAsync({courseId:r.id,accessRules:kt}),he.success(ct?"Brokerage removed":"Brokerage added")}catch{he.error("Failed to update access")}},Ce=async()=>{try{await u.mutateAsync({courseId:r.id,accessRules:[]}),he.success("Access cleared")}catch{he.error("Failed")}},qe=async(Ze,rt)=>{const ct=rt==="up"?Ze-1:Ze+1;if(!(ct<0||ct>=Oe.length))try{await Promise.all([l.mutateAsync({id:Oe[Ze].id,sort_order:ct}),l.mutateAsync({id:Oe[ct].id,sort_order:Ze})])}catch{he.error("Failed to reorder")}},et=async()=>{try{await a.mutateAsync({id:r.id,title:de,description:je||null}),he.success("Course updated"),Me(!1)}catch{he.error("Failed to update")}};return e.jsxs(ws,{title:r.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:r.title}),e.jsx(Xe,{variant:r.is_published?"default":"secondary",children:r.is_published?"Published":"Draft"})]}),r.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:r.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[r.is_sequential?e.jsx(T1,{className:"h-3.5 w-3.5"}):e.jsx(HE,{className:"h-3.5 w-3.5"}),r.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[Oe.length," module",Oe.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>{fe(r.title),xe(r.description||""),Me(!0)},children:[e.jsx(Ua,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(q,{variant:r.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:r.id,is_published:!r.is_published}).then(()=>he.success(r.is_published?"Unpublished":"Published")),children:[r.is_published?e.jsx(Wf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1"}),r.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(ta,{defaultValue:"modules",className:"w-full",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"modules",children:"Modules"}),e.jsx(rs,{value:"access",children:"Access & Permissions"}),e.jsx(rs,{value:"settings",children:"Settings"})]}),e.jsxs(fs,{value:"modules",className:"mt-6 space-y-4",children:[Oe.map((Ze,rt)=>e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>$e(Ze.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:ct=>{ct.stopPropagation(),qe(rt,"up")},disabled:rt===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(pg,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:ct=>{ct.stopPropagation(),qe(rt,"down")},disabled:rt===Oe.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Co,{className:"h-3.5 w-3.5"})})]})}),e.jsx(Xe,{variant:"outline",className:"shrink-0 font-mono text-xs",children:rt+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:Ze.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[Ze.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(bn,{className:"h-3 w-3"})," Video"]}),Ze.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(En,{className:"h-3 w-3"})," Text"]}),Ze.duration_minutes&&e.jsxs("span",{children:[Ze.duration_minutes," min"]}),Ze.resources&&Ze.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Ul,{className:"h-3 w-3"})," ",Ze.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{size:"sm",variant:"ghost",onClick:ct=>{var vt;ct.stopPropagation(),x(Ze),j({title:Ze.title,description:Ze.description||"",video_url:Ze.video_url||"",text_content:Ze.text_content||"",duration_minutes:((vt=Ze.duration_minutes)==null?void 0:vt.toString())||""})},children:e.jsx(Ua,{className:"h-3.5 w-3.5"})}),e.jsx(q,{size:"sm",variant:"ghost",className:"text-destructive",onClick:ct=>{ct.stopPropagation(),nt(Ze.id)},children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]}),D.has(Ze.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[Ze.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Ze.description}),Ze.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:Ze.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:Ze.video_url})]}),Ze.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:Ze.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(q,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{C(Ze.id),E({title:"",resource_type:"link",url:""})},children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),Ze.resources&&Ze.resources.length>0?e.jsx("div",{className:"space-y-1",children:Ze.resources.map(ct=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:ct.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:ct.title}),ct.url&&e.jsx("a",{href:ct.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(q,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(ct.id),children:e.jsx($r,{className:"h-3 w-3"})})]},ct.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},Ze.id)),e.jsxs(q,{variant:"outline",className:"w-full border-dashed",onClick:()=>{_(!0),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(fs,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Pe,{className:"space-y-5",children:[e.jsxs("div",{className:zt("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",ze?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Ge,children:[e.jsx("div",{className:zt("h-10 w-10 rounded-full flex items-center justify-center shrink-0",ze?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(Ql,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"All Brokerages / All Agents"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every agent on the platform can access this course"})]}),e.jsx(Rr,{checked:ze,onCheckedChange:Ge})]}),!ze&&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:Ve.length===0?"No brokerages selected — agents won't see this course":`${Ve.length} brokerage${Ve.length!==1?"s":""} selected`})]}),Ve.length>0&&e.jsx(q,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ce,children:"Clear all"})]}),e.jsx(Ne,{placeholder:"Search brokerages...",value:ue,onChange:Ze=>me(Ze.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Le.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Le.map(Ze=>{const rt=Ve.includes(Ze.id);return e.jsxs("div",{className:zt("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",rt?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>We(Ze.id),children:[e.jsx("div",{className:zt("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",rt?"bg-primary border-primary":"border-muted-foreground/30"),children:rt&&e.jsx("svg",{className:"h-3 w-3 text-primary-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:Ze.name}),rt&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},Ze.id)})})]})]})]})}),e.jsxs(fs,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[r.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:r.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:r.id,thumbnail_url:null}).then(()=>he.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($r,{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(Qy,{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:te,type:"file",accept:"image/*",className:"hidden",onChange:async Ze=>{var ct;const rt=(ct=Ze.target.files)==null?void 0:ct[0];if(!(!rt||!r)){ae(!0);try{const vt=rt.name.split(".").pop(),kt=`${r.id}/thumbnail.${vt}`,{error:St}=await U.storage.from("lms-thumbnails").upload(kt,rt,{upsert:!0});if(St)throw St;const{data:Yt}=U.storage.from("lms-thumbnails").getPublicUrl(kt),es=`${Yt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:r.id,thumbnail_url:es}),he.success("Thumbnail uploaded")}catch{he.error("Failed to upload thumbnail")}finally{ae(!1),te.current&&(te.current.value="")}}}}),e.jsxs(q,{variant:"outline",size:"sm",disabled:ne,onClick:()=>{var Ze;return(Ze=te.current)==null?void 0:Ze.click()},children:[ne?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ka,{className:"h-4 w-4 mr-2"}),ne?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Course Settings"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order before advancing"})]}),e.jsx(Rr,{checked:r.is_sequential,onCheckedChange:Ze=>a.mutateAsync({id:r.id,is_sequential:Ze}).then(()=>he.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(Rr,{checked:r.is_published,onCheckedChange:Ze=>a.mutateAsync({id:r.id,is_published:Ze}).then(()=>he.success("Updated"))})]})]})]})]})]})]}),e.jsx(vs,{open:y||!!f,onOpenChange:Ze=>{Ze||(_(!1),x(null))},children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:f?"Edit Module":"Add Module"}),e.jsx(an,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Title"}),e.jsx(Ne,{value:b.title,onChange:Ze=>j(rt=>({...rt,title:Ze.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{value:b.description,onChange:Ze=>j(rt=>({...rt,description:Ze.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:zt("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",F?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var Ze;return(Ze=W.current)==null?void 0:Ze.click()},children:[e.jsx("input",{ref:W,type:"file",accept:"video/*",className:"hidden",onChange:Ze=>{var ct;const rt=(ct=Ze.target.files)==null?void 0:ct[0];rt&&(O(rt),j(vt=>({...vt,video_url:""})))}}),F?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(bn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:F.name}),e.jsx(q,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:Ze=>{Ze.stopPropagation(),O(null)},children:e.jsx($r,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(ka,{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(ls,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",B,"%"]})]}),e.jsx(ki,{value:B,className:"h-1.5"})]}),!F&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("div",{className:"flex-1 h-px bg-border"}),e.jsx("span",{children:"or paste a URL"}),e.jsx("div",{className:"flex-1 h-px bg-border"})]}),e.jsx(Ne,{value:b.video_url,onChange:Ze=>j(rt=>({...rt,video_url:Ze.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Text Content"}),e.jsx(pr,{value:b.text_content,onChange:Ze=>j(rt=>({...rt,text_content:Ze.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Duration (minutes)"}),e.jsx(Ne,{type:"number",value:b.duration_minutes,onChange:Ze=>j(rt=>({...rt,duration_minutes:Ze.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>{_(!1),x(null),O(null)},children:"Cancel"}),e.jsxs(q,{onClick:f?we:Qe,disabled:!b.title.trim()||Z,children:[Z?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),Z?"Uploading...":f?"Save Changes":"Add Module"]})]})]})}),e.jsx(vs,{open:!!N,onOpenChange:Ze=>{Ze||C(null)},children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Add Resource"}),e.jsx(an,{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(ce,{children:"Title"}),e.jsx(Ne,{value:A.title,onChange:Ze=>E(rt=>({...rt,title:Ze.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Type"}),e.jsxs(Ds,{value:A.resource_type,onValueChange:Ze=>E(rt=>({...rt,resource_type:Ze})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"link",children:"Link"}),e.jsx(lt,{value:"pdf",children:"PDF"}),e.jsx(lt,{value:"template",children:"Template"}),e.jsx(lt,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"URL"}),e.jsx(Ne,{value:A.url,onChange:Ze=>E(rt=>({...rt,url:Ze.target.value})),placeholder:"https://..."})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>C(null),children:"Cancel"}),e.jsx(q,{onClick:()=>N&&Se(N),disabled:!A.title.trim(),children:"Add Resource"})]})]})}),e.jsx(vs,{open:Ee,onOpenChange:Me,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Edit Course"}),e.jsx(an,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Title"}),e.jsx(Ne,{value:de,onChange:Ze=>fe(Ze.target.value)})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{value:je,onChange:Ze=>xe(Ze.target.value),rows:3})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>Me(!1),children:"Cancel"}),e.jsx(q,{onClick:et,disabled:!de.trim(),children:"Save"})]})]})})]})}function MKs(){return pt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await U.rpc("get_lms_stats");if(t)throw t;return s}})}function IKs(){return pt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await U.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function PKs(s){return pt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.rpc("get_lms_agent_progress",{p_course_id:s});if(r)throw r;return t||[]},enabled:!!s})}function LKs(){const s=qr(),{data:t,isLoading:r}=MKs(),{data:n,isLoading:a}=IKs(),[i,l]=k.useState(null),{data:o,isLoading:c}=PKs(i),[d,u]=k.useState(""),m=n==null?void 0:n.find(y=>y.course_id===i),f=o==null?void 0:o.filter(y=>{var _,b;return!d||((_=y.agent_name)==null?void 0:_.toLowerCase().includes(d.toLowerCase()))||((b=y.email)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))}),x=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:vm,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:qn,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Dr,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:wo,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:Wo,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:Mo,color:"text-rose-500"}];return e.jsx(ws,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(Aa,{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(ch,{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:x.map(y=>e.jsx(ke,{className:zt("transition-all",r&&"animate-pulse"),children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(y.icon,{className:zt("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:r?"—":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(Mo,{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(ke,{className:"animate-pulse",children:e.jsx(Pe,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},y))}):n!=null&&n.length?e.jsx("div",{className:"space-y-2",children:n.map(y=>{const _=i===y.course_id;return e.jsx(ke,{className:zt("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(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:y.course_title}),e.jsx(Xe,{variant:y.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:y.is_published?"Live":"Draft"})]})}),e.jsx(Ia,{className:zt("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(ki,{value:y.avg_completion_pct,className:"h-2"})]})]})},y.course_id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Pe,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:"No courses created yet"})})})]}),e.jsxs("div",{className:"xl:col-span-3 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(M1,{className:"h-5 w-5 text-primary"}),m?`Agent Progress — ${m.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{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(ke,{className:"animate-pulse",children:e.jsx(Pe,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},y))}):f!=null&&f.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:f.map((y,_)=>{const b=y.completion_pct>=100;return e.jsx(ke,{className:zt("transition-all",b&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:zt("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(Wn,{className:"h-9 w-9 shrink-0",children:[e.jsx(Xa,{src:y.avatar_url||void 0}),e.jsx(Kn,{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}),b&&e.jsxs(Xe,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(qn,{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(jn,{className:"h-3 w-3"}),As(new Date(y.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:zt("text-sm font-bold",b?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[y.completion_pct,"%"]}),e.jsx(ki,{value:y.completion_pct,className:"h-1.5 mt-1"})]})]})})},y.user_id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Pe,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:d?"No agents match your search":"No agents have started this course yet"})})})]}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"py-16 text-center",children:[e.jsx(Dr,{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 DKs(){const{user:s}=Cs(),t=qr(),{data:r,isLoading:n}=SKs();return e.jsx(ws,{title:"LevelUp U",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/10 via-primary/5 to-background border p-8",children:[e.jsx("div",{className:"relative z-10",children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-primary/15 flex items-center justify-center",children:e.jsx(ch,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"LevelUp U"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Your training & development hub"})]})]})}),e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/5 rounded-full -translate-y-1/2 translate-x-1/2"})]}),n?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(a=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Pe,{className:"p-6",children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-3"})]})},a))}):r!=null&&r.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:r.map(a=>e.jsx(RKs,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(vm,{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 RKs({course:s,userId:t,onClick:r}){var o;const n=((o=s.modules)==null?void 0:o.length)??0,{data:a}=Lbt(s.id),i=(a==null?void 0:a.filter(c=>c.completed).length)??0,l=n>0?Math.round(i/n*100):0;return e.jsxs(ke,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/50 overflow-hidden",onClick:r,children:[s.thumbnail_url?e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:s.thumbnail_url,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}):e.jsx("div",{className:"aspect-video bg-gradient-to-br from-primary/15 via-primary/5 to-muted flex items-center justify-center",children:e.jsx(ch,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors line-clamp-1",children:s.title}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vm,{className:"h-3.5 w-3.5"}),n," module",n!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[s.is_sequential?e.jsx(T1,{className:"h-3.5 w-3.5"}):e.jsx(HE,{className:"h-3.5 w-3.5"}),s.is_sequential?"In order":"Any order"]})]}),n>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[i," of ",n," completed"]}),e.jsxs("span",{className:"font-medium text-foreground",children:[l,"%"]})]}),e.jsx(ki,{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(Ia,{className:"h-3.5 w-3.5"})]})})]})]})}function OKs(){const{courseId:s}=xo(),t=qr(),{user:r}=Cs(),{data:n,isLoading:a}=CKs(s),{data:i}=Lbt(s),l=TKs(),[o,c]=k.useState(null),d=(n==null?void 0:n.modules)||[],u=new Set((i==null?void 0:i.filter(N=>N.completed).map(N=>N.module_id))||[]),m=u.size,f=d.length>0?Math.round(m/d.length*100):0;k.useEffect(()=>{if(d.length>0&&!o){const N=d.find(C=>!u.has(C.id));c((N==null?void 0:N.id)||d[0].id)}},[d,o,u]);const x=d.find(N=>N.id===o),y=d.findIndex(N=>N.id===o),_=(N,C)=>{if(!(n!=null&&n.is_sequential)||C===0)return!1;for(let A=0;A{if(!(!x||!r||!s))try{await l.mutateAsync({courseId:s,moduleId:x.id,userId:r.id}),he.success("Module completed! 🎉"),y{const C=N.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(C)return`https://www.youtube.com/embed/${C[1]}`;const A=N.match(/vimeo\.com\/(\d+)/);if(A)return`https://player.vimeo.com/video/${A[1]}`;const E=N.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`:N};return a?e.jsx(ws,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):n?e.jsx(ws,{title:n.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:n.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[m,"/",d.length," completed"]}),e.jsxs("span",{children:[f,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(ki,{value:f,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(ke,{className:"lg:sticky lg:top-4",children:e.jsxs(Pe,{className:"p-0",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Modules"})}),e.jsx(ui,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((N,C)=>{const A=_(N,C),E=u.has(N.id),D=N.id===o;return e.jsxs("button",{disabled:A,onClick:()=>!A&&c(N.id),className:zt("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",D?"bg-primary/10 text-primary":"hover:bg-muted/50",A&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:A?e.jsx(Gc,{className:"h-4 w-4 text-muted-foreground"}):E?e.jsx(qn,{className:"h-4 w-4 text-green-500"}):e.jsx(Rh,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:zt("font-medium truncate",D&&"text-primary"),children:[C+1,". ",N.title]}),N.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(jn,{className:"h-3 w-3"})," ",N.duration_minutes," min"]})]})]},N.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:x?e.jsxs(e.Fragment,{children:[x.video_url&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:j(x.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:x.title}),x.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:x.description})]}),u.has(x.id)?e.jsxs(Xe,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(q,{size:"sm",onClick:b,disabled:l.isPending,children:[e.jsx(qn,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),x.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:x.text_content}),x.resources&&x.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:x.resources.map(N=>e.jsxs("a",{href:N.url||N.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:[N.resource_type==="pdf"?e.jsx(En,{className:"h-4 w-4 text-red-500 shrink-0"}):N.resource_type==="template"?e.jsx(ch,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(Ul,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:N.title}),e.jsx(un,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},N.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(q,{variant:"outline",size:"sm",disabled:y===0,onClick:()=>y>0&&c(d[y-1].id),children:[e.jsx(Aa,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),yc(d[y+1].id),children:["Next ",e.jsx(Ia,{className:"h-3.5 w-3.5 ml-1"})]}):f===100&&e.jsx(Xe,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(ws,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(q,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function FKs({headline:s,subtext:t,primaryColor:r,accentColor:n,heroImageUrl:a,logoUrl:i,brokerageName:l}){return e.jsxs("section",{className:"relative min-h-screen flex items-center justify-center overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${n} 0%, ${r} 50%, ${n}ee 100%)`}}),a&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${a})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px), radial-gradient(circle at 75% 75%, white 1px, transparent 1px)",backgroundSize:"60px 60px"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white to-transparent"}),e.jsxs("div",{className:"relative z-10 text-center max-w-4xl mx-auto px-6 py-24",children:[i&&e.jsx(Zr.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(Zr.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(Zr.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(Zr.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(Zr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:n},children:["Get In Touch",e.jsx(ci,{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(Zr.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 U0({children:s,className:t="",delay:r=0,direction:n="up"}){const a=k.useRef(null),i=EWt(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:n==="up"?40:0,x:n==="left"?-40:n==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(Zr.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:r,ease:[.25,.46,.45,.94]},className:t,children:s})}function zKs({benefits:s,accentColor:t,primaryColor:r}){return s.length===0?null:e.jsx("section",{id:"benefits",className:"py-24 md:py-32 px-6 bg-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(U0,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase mb-4 block",style:{color:r},children:"Why Top Agents Choose Us"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mb-4 tracking-tight",style:{color:t},children:"Built For Your Success"}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full mt-6",style:{backgroundColor:r}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8",children:s.map((n,a)=>e.jsx(U0,{delay:a*.1,children:e.jsxs("div",{className:"group relative p-8 rounded-2xl border border-gray-100 bg-white hover:border-transparent hover:shadow-2xl transition-all duration-500 h-full",children:[e.jsx("div",{className:"absolute inset-0 rounded-2xl opacity-0 group-hover:opacity-100 transition-opacity duration-500",style:{background:`linear-gradient(135deg, ${r}08, ${t}05)`}}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl flex items-center justify-center text-2xl mb-5 transition-transform duration-300 group-hover:scale-110",style:{backgroundColor:`${r}12`},children:n.icon}),e.jsx("h3",{className:"text-xl font-bold mb-3 tracking-tight",style:{color:t},children:n.title}),e.jsx("p",{className:"text-gray-500 leading-relaxed text-[15px]",children:n.description})]})]})},a))})]})})}function BKs({images:s,primaryColor:t,accentColor:r}){const[n,a]=k.useState(null);return s.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"py-24 md:py-32 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(U0,{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(Dr,{className:"h-4 w-4",style:{color:t}}),e.jsx("span",{className:"text-sm font-medium text-gray-600",children:"Life at Our Brokerage"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:r},children:"Our Team & Culture"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-4",children:s.map((i,l)=>e.jsx(U0,{delay:l*.08,children:e.jsxs("button",{onClick:()=>a(l),className:"relative w-full aspect-[4/3] overflow-hidden rounded-xl group cursor-pointer",children:[e.jsx("img",{src:i,alt:`Team ${l+1}`,className:"w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-all duration-500"})]})},l))})]})}),n!==null&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 cursor-pointer",onClick:()=>a(null),children:[e.jsx("button",{onClick:()=>a(null),className:"absolute top-6 right-6 text-white/80 hover:text-white transition-colors",children:e.jsx($r,{className:"h-8 w-8"})}),e.jsx("img",{src:s[n],alt:"Gallery",className:"max-w-full max-h-[85vh] object-contain rounded-lg",onClick:i=>i.stopPropagation()})]})]})}function $Ks({testimonials:s,primaryColor:t,accentColor:r}){return s.length===0?null:e.jsx("section",{className:"py-24 md:py-32 px-6 bg-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(U0,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase mb-4 block",style:{color:t},children:"Agent Testimonials"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:r},children:"Hear From Our Agents"}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full mt-6",style:{backgroundColor:t}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8",children:s.map((n,a)=>{var i;return e.jsx(U0,{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(u2,{className:"h-8 w-8 mb-5 opacity-20",style:{color:t}}),e.jsxs("p",{className:"text-gray-700 text-lg leading-relaxed mb-8 font-light italic",children:['"',n.quote,'"']}),e.jsxs("div",{className:"flex items-center gap-4",children:[n.photo_url?e.jsx("img",{src:n.photo_url,alt:n.name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white shadow-md"}):e.jsx("div",{className:"h-12 w-12 rounded-full flex items-center justify-center text-white text-base font-bold shadow-md",style:{background:`linear-gradient(135deg, ${t}, ${r})`},children:((i=n.name)==null?void 0:i[0])||"?"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-base",style:{color:r},children:n.name}),n.role&&e.jsx("p",{className:"text-sm text-gray-500",children:n.role})]})]})]})},a)})})]})})}function UKs({form:s,setForm:t,onSubmit:r,isPending:n,primaryColor:a,accentColor:i}){return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(U0,{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(U0,{delay:.2,children:e.jsxs("form",{onSubmit:l=>{l.preventDefault(),r()},className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(Ne,{required:!0,value:s.first_name,onChange:l=>t(o=>({...o,first_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(Ne,{value:s.last_name,onChange:l=>t(o=>({...o,last_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(Ne,{type:"email",required:!0,value:s.email,onChange:l=>t(o=>({...o,email:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(Ne,{value:s.phone,onChange:l=>t(o=>({...o,phone:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(Ne,{value:s.current_brokerage,onChange:l=>t(o=>({...o,current_brokerage:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Your current brokerage name"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(Ne,{value:s.license_number,onChange:l=>t(o=>({...o,license_number:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(Ne,{type:"number",min:"0",value:s.experience_years,onChange:l=>t(o=>({...o,experience_years:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(Ne,{value:s.annual_production,onChange:l=>t(o=>({...o,annual_production:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"e.g. $5M, 20 transactions"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(pr,{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(q,{type:"submit",className:"w-full h-13 text-base font-semibold rounded-xl group transition-all duration-300 hover:shadow-lg",style:{background:`linear-gradient(135deg, ${a}, ${i})`},disabled:n,children:n?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Submitting..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:["Send My Info",e.jsx(ci,{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(Oh,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function qKs({form:s,setForm:t,onSubmit:r,isPending:n,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=k.useState(1),[d,u]=k.useState(""),m=3,f=!!s.first_name&&!!s.email,x=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(U0,{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(U0,{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,"/",m]})]}),e.jsxs(tEe,{mode:"wait",children:[o===1&&e.jsxs(Zr.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:()=>x(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(ci,{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(Zr.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(ce,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(Ne,{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(ce,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(Ne,{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(ce,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(Ne,{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(ce,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(Ne,{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(q,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(q,{type:"button",disabled:!f,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(ci,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Zr.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(ce,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(Ne,{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(ce,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(Ne,{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(ce,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(Ne,{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(ce,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(pr,{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(q,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(q,{type:"button",onClick:r,disabled:n,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:n?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Sending..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(la,{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(Oh,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Ui,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Mn,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function VKs({config:s,primaryColor:t,accentColor:r,brokerageId:n,brokerageName:a}){const{toast:i}=Ba(),[l,o]=k.useState("250000"),[c,d]=k.useState("12"),[u,m]=k.useState("70"),[f,x]=k.useState("150"),[y,_]=k.useState(""),[b,j]=k.useState(!1),[N,C]=k.useState(!1),A=s.commission_split_pct??80,E=s.cap_amount??16e3,D=s.post_cap_split_pct??100,R=s.monthly_fee??99,F=s.transaction_fee??0,O=k.useMemo(()=>{const Z=parseFloat(l)||0,Q=Math.max(0,parseInt(c,10)||0),W=parseFloat(u)||0,te=parseFloat(f)||0,ne=Z*(W/100)-te*12-F*Q,ae=1-A/100,ue=ae>0?E/ae:Z,me=Math.min(Z,ue),de=Math.max(0,Z-ue),fe=me*ae+de*(1-D/100),je=Z-fe-R*12-F*Q,xe=je-ne;return{currentNet:ne,newNet:je,diff:xe}},[l,c,u,f,A,E,D,R,F]),B=Z=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Z),K=async Z=>{if(Z.preventDefault(),!!y){C(!0);try{const{error:Q}=await U.from("recruit_lead_magnet_downloads").insert({brokerage_id:n,email:y,source:"calculator"});if(Q)throw Q;const{error:W}=await U.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:n,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(f)||0},plan:{commission_split_pct:A,cap_amount:E,post_cap_split_pct:D,monthly_fee:R,transaction_fee:F},result:O,primary_color:t,accent_color:r}});W&&console.error("Breakdown email failed:",W),j(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(Q){i({title:"Error",description:Q.message,variant:"destructive"})}finally{C(!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(U0,{children:e.jsxs("div",{className:"text-center mb-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full text-xs font-semibold mb-4",style:{backgroundColor:`${t}15`,color:r},children:[e.jsx(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:r},children:s.headline||"See What You Could Earn With Us"}),e.jsx("p",{className:"text-gray-500 text-lg font-light max-w-xl mx-auto",children:s.subtext||"Confidential 60-second calculator — no signup required."})]})}),e.jsx(U0,{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(__,{className:"h-5 w-5",style:{color:t}}),e.jsx("h3",{className:"font-semibold",style:{color:r},children:"Your Numbers"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-gray-600 text-sm",children:"Your GCI Last 12 Months"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(Ne,{type:"number",value:l,onChange:Z=>o(Z.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(Ne,{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(ce,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(Ne,{type:"number",value:u,onChange:Z=>m(Z.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-gray-600 text-sm",children:"Your Current Monthly Fees"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(Ne,{type:"number",value:f,onChange:Z=>x(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, ${r}, ${t})`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(Wo,{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:B(O.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:B(O.newNet)})]})]}),e.jsxs(Zr.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:O.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[O.diff>=0?"+":"",B(O.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:O.diff>=0?"more per year":"per year"})]},O.diff),s.show_email_capture&&!b&&e.jsxs("form",{onSubmit:K,className:"mt-6 space-y-2",children:[e.jsx("p",{className:"text-white/80 text-xs",children:s.email_capture_label||"Want the full breakdown? Enter your email."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{type:"email",required:!0,value: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(q,{type:"submit",disabled:N,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),b&&e.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-white/90 bg-white/10 rounded-lg p-3",children:[e.jsx(la,{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 HKs({config:s,primaryColor:t,accentColor:r,brokerageId:n}){const{toast:a}=Ba(),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(!1),[m,f]=k.useState(!1),x=async y=>{y.preventDefault(),f(!0);try{const{error:_}=await U.from("recruit_lead_magnet_downloads").insert({brokerage_id:n,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(_)throw _;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(_){a({title:"Error",description:_.message,variant:"destructive"})}finally{f(!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(U0,{children:e.jsx("div",{className:"rounded-3xl p-8 md:p-12 shadow-xl border border-gray-100",style:{background:`linear-gradient(135deg, ${t}08, ${r}08)`},children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-8",children:[e.jsx("div",{className:"shrink-0 h-24 w-24 rounded-2xl flex items-center justify-center shadow-lg",style:{background:`linear-gradient(135deg, ${t}, ${r})`},children:e.jsx(ME,{className:"h-12 w-12 text-white"})}),e.jsxs("div",{className:"flex-1 text-center md:text-left",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold mb-3",style:{backgroundColor:`${t}15`,color:r},children:[e.jsx(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:r},children:s.title||"Get the Full Comp Plan PDF"}),e.jsx("p",{className:"text-gray-500 leading-relaxed mb-5",children:s.description||"See exactly how splits, caps, and fees work — no call required."}),d?e.jsxs("div",{className:"flex items-center gap-2 p-4 rounded-xl bg-green-50 border border-green-200 text-green-800 text-sm",children:[e.jsx(la,{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:x,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(Ne,{value:o,onChange:y=>c(y.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(Ne,{type:"email",required:!0,value:i,onChange:y=>l(y.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(q,{type:"submit",disabled:m,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${r})`},children:[e.jsx(ME,{className:"h-4 w-4 mr-2"}),m?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function GKs(){const{slug:s}=xo(),{toast:t}=Ba(),[r,n]=k.useState(!1),[a,i]=k.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});k.useEffect(()=>{document.body.classList.add("recruit-landing-page");const O=()=>{['[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(Q=>document.querySelectorAll(Q).forEach(W=>W.style.display="none"))};O();const B=[setTimeout(O,500),setTimeout(O,1500),setTimeout(O,3e3)],K=new MutationObserver(O);return K.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),B.forEach(clearTimeout),K.disconnect()}},[]);const{data:l,isLoading:o,error:c}=pt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:O,error:B}=await U.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(B)throw B;return O},enabled:!!s}),{data:d}=pt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:O,error:B}=await U.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(B&&B.code!=="PGRST116")throw B;return O},enabled:!!(l!=null&&l.id)}),u=Mt({mutationFn:async()=>{const O={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:B}=await U.from("recruit_interest_submissions").insert(O);if(B)throw B;U.functions.invoke("recruit-lead-notify",{body:{lead:O,brokerage_id:l.id}}).catch(K=>console.error("Lead notification error:",K))},onSuccess:()=>n(!0),onError:O=>t({title:"Error",description:O.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(Ga,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const m=d,f=(m==null?void 0:m.primary_color)||"#406E71",x=(m==null?void 0:m.accent_color)||"#2a4c64",y=(m==null?void 0:m.benefits)||[],_=(m==null?void 0:m.testimonials)||[],b=(m==null?void 0:m.gallery_images)||[],j=(m==null?void 0:m.hero_headline)||`Join ${l.name}`,N=(m==null?void 0:m.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",C=(m==null?void 0:m.calculator_enabled)===!0,A=(m==null?void 0:m.calculator_config)||{},E=(m==null?void 0:m.lead_magnet_enabled)===!0,D=(m==null?void 0:m.lead_magnet_config)||{},R=(m==null?void 0:m.form_style)||"classic",F=(m==null?void 0:m.confidential_messaging)!==!1;return r?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(Zr.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, ${f}, ${x})`},children:e.jsx(la,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:x},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:x},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:f}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":f,"--recruit-accent":x},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(m==null?void 0:m.logo_url)&&e.jsx("img",{src:m.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:x},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, ${f}, ${x})`},children:["Apply Now ",e.jsx(ci,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(FKs,{headline:j,subtext:N,primaryColor:f,accentColor:x,heroImageUrl:m==null?void 0:m.hero_image_url,logoUrl:m==null?void 0:m.logo_url,brokerageName:l.name}),e.jsx(zKs,{benefits:y,accentColor:x,primaryColor:f}),e.jsx(BKs,{images:b,primaryColor:f,accentColor:x}),e.jsx($Ks,{testimonials:_,primaryColor:f,accentColor:x}),C&&e.jsx(VKs,{config:A,primaryColor:f,accentColor:x,brokerageId:l.id,brokerageName:l.name}),E&&e.jsx(HKs,{config:D,primaryColor:f,accentColor:x,brokerageId:l.id}),R==="multi_step"?e.jsx(qKs,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:f,accentColor:x,showConfidentialBadges:F}):e.jsx(UKs,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:f,accentColor:x}),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 WKs(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 KKs(){var f,x,y,_;const{shareToken:s}=xo(),t=k.useRef(!1),{data:r,isLoading:n,error:a}=pt({queryKey:["public-recruit-video",s],queryFn:async()=>{var E;if(!s)throw new Error("No token");const{data:b,error:j}=await U.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(j)throw j;const{data:N}=await U.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(E=b.video)==null?void 0:E.owner_user_id).single(),{data:C}=await U.from("brokerages").select("name").eq("id",b.brokerage_id).single(),{data:A}=await U.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",b.brokerage_id).maybeSingle();return{rv:b,profile:N,brokerage:C,settings:A}},enabled:!!s});if(k.useEffect(()=>{var b;!((b=r==null?void 0:r.rv)!=null&&b.id)||t.current||(t.current=!0,U.rpc("log_recruit_video_view",{p_recruit_video_id:r.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(f=r==null?void 0:r.rv)==null?void 0:f.id]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=r,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((x=i.prospect)==null?void 0:x.first_name)||"there",m=(y=i.video)!=null&&y.playback_url?WKs(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(Yo,{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})]}),m&&e.jsx("div",{className:"rounded-xl overflow-hidden shadow-xl bg-black",children:e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:m,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}),e.jsxs("div",{className:"bg-white rounded-xl shadow-sm border p-6 flex items-center gap-4",children:[l!=null&&l.avatar_url?e.jsx("img",{src:l.avatar_url,alt:"",className:"h-14 w-14 rounded-full object-cover"}):e.jsx("div",{className:"h-14 w-14 rounded-full flex items-center justify-center text-white text-lg font-bold",style:{backgroundColor:d},children:((_=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(q,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{U.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(vn,{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 YKs="relzejiswnotikjgvjhz",nYe=`https://${YKs}.supabase.co/functions/v1/recruit-unsubscribe`;function ZKs(){const[s]=ic(),t=s.get("token")||"",[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,m]=k.useState({});k.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const x=()=>{['[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(N=>N.style.display="none"))};x();const y=[setTimeout(x,500),setTimeout(x,1500),setTimeout(x,3e3)],_=new MutationObserver(x);return _.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),y.forEach(clearTimeout),_.disconnect()}},[]),k.useEffect(()=>{if(!t){m({error:"Missing unsubscribe token in link."}),n(!1);return}fetch(`${nYe}?token=${encodeURIComponent(t)}`).then(async x=>{const y=await x.json();if(!x.ok)throw new Error(y.error||"Lookup failed");m(y),y.already_unsubscribed&&o(!0)}).catch(x=>m({error:x.message||"Could not load status"})).finally(()=>n(!1))},[t]);const f=async()=>{i(!0);try{const x=await fetch(nYe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),y=await x.json();if(!x.ok)throw new Error(y.error||"Failed");o(!0)}catch(x){m({...u,error:x.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:r?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(ls,{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(go,{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(qn,{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(A1,{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(A1,{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(ce,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(pr,{id:"reason",value:c,onChange:x=>d(x.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(q,{onClick:f,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Confirm Unsubscribe"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. We process your request instantly."})]})})})}function XKs(){const s=qr(),t=is(),{isAdmin:r}=Cs(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState(null),{data:d,isLoading:u}=pt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:E},error:D}=await U.auth.getUser();if(D)throw D;if(!E)return[];const{data:R,error:F}=await U.from("social_accounts").select("*").eq("user_id",E.id).order("created_at",{ascending:!1});if(F)throw F;return R}}),m=Mt({mutationFn:async E=>{const{data:{user:D},error:R}=await U.auth.getUser();if(R)throw R;if(!D)throw new Error("Not authenticated");const{error:F}=await U.from("social_accounts").delete().eq("id",E).eq("user_id",D.id);if(F)throw F},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),he.success("Account disconnected successfully")},onError:()=>{he.error("Failed to disconnect account")}}),f=async E=>{a(!0);try{const{data:D,error:R}=await U.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:E}});if(R)throw R;if(D!=null&&D.authUrl)window.location.href=D.authUrl;else throw new Error("Failed to get authorization URL")}catch(D){console.error("Meta OAuth error:",D),he.error("Failed to start connection. Please try again."),a(!1)}},x=async()=>{a(!0);try{const{data:E,error:D}=await U.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(D)throw D;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),he.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},y=async()=>{a(!0);try{const{data:E,error:D}=await U.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(D)throw D;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),he.error("Failed to start Google connection. Please try again."),a(!1)}},_=(d==null?void 0:d.filter(E=>E.platform==="facebook"))||[],b=(d==null?void 0:d.filter(E=>E.platform==="instagram"))||[],j=(d==null?void 0:d.filter(E=>E.platform==="linkedin"))||[],N=(d==null?void 0:d.filter(E=>E.platform==="google_business"))||[],C=((d==null?void 0:d.length)||0)>0,A=async(E,D)=>{l(E),c(null);try{const{data:R,error:F}=await U.functions.invoke("meta-api-test",{body:{testType:"all",accountId:E}});if(F)throw F;c(R.results||[]),he.success(R.summary||"API tests completed")}catch(R){console.error("Meta API test error:",R),he.error("Failed to run API tests")}finally{l(null)}};return e.jsx(ws,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs(Xe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Ir,{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(q,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Social Swag"]}),C&&e.jsx(ke,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Pe,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(Ti,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-green-800 dark:text-green-200",children:"You're all set!"}),e.jsx("p",{className:"text-sm text-green-600 dark:text-green-400",children:"You can now post directly to your connected accounts from Social Swag."})]})]})}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(ke,{children:[e.jsx(Pt,{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(Dt,{className:"text-lg",children:"Facebook"}),e.jsx(Ur,{children:"Connect your Facebook Pages"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(lo,{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(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:E.profile_picture_url||""}),e.jsx(Kn,{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(Xe,{variant:E.is_active?"default":"secondary",className:"text-xs",children:E.is_active?"Connected":"Inactive"})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Facebook?"}),e.jsx(Ho,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>m.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(q,{onClick:()=>f("facebook"),disabled:n,className:"w-full gap-2",variant:_.length>0?"outline":"default",children:[n?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),_.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{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(gu,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Instagram"}),e.jsx(Ur,{children:"Connect Instagram Business accounts"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(lo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.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(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:E.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(gu,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",E.platform_username||"Instagram Account"]}),e.jsx(Xe,{variant:E.is_active?"default":"secondary",className:"text-xs",children:E.is_active?"Connected":"Inactive"})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Instagram?"}),e.jsx(Ho,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>m.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(q,{onClick:()=>f("instagram"),disabled:n,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[n?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),b.length>0?"Connect Another Account":"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{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(Yf,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"LinkedIn"}),e.jsx(Ur,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(lo,{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(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:E.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(Yf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:E.platform_username||"LinkedIn Account"}),e.jsx(Xe,{variant:E.is_active?"default":"secondary",className:"text-xs",children:E.is_active?"Connected":"Inactive"})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect LinkedIn?"}),e.jsx(Ho,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>m.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(q,{onClick:x,disabled:n,className:"w-full gap-2",variant:j.length>0?"outline":"default",children:[n?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{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(ke,{className:`relative overflow-hidden ${r?"":"opacity-75"}`,children:[!r&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Xe,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Coming Soon"})}),r&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Xe,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Pt,{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(Ma,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Google Business"}),e.jsx(Ur,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(lo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):N.length>0?e.jsx("div",{className:"space-y-3",children:N.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(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:E.profile_picture_url||""}),e.jsx(Kn,{children:e.jsx(Ma,{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(Xe,{variant:E.is_active?"default":"secondary",className:"text-xs",children:E.is_active?"Connected":"Inactive"})]})]}),e.jsxs(el,{children:[e.jsx(hh,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})}),e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Disconnect Google Business?"}),e.jsx(Ho,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>m.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:r?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(q,{onClick:r?y:void 0,disabled:!r||n,className:"w-full gap-2",variant:N.length>0?"outline":"default",children:[n?e.jsx(lo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ys,{className:"h-4 w-4"}),N.length>0?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates directly to your Google Business Profile"})]})]})]}),r&&(_.length>0||b.length>0)&&e.jsxs(ke,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Pt,{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(tS,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Ur,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:['Click "Run Tests" on an account to trigger API calls for: ',e.jsx("strong",{children:"public_profile"}),", ",e.jsx("strong",{children:"pages_show_list"}),", ",e.jsx("strong",{children:"pages_read_engagement"}),", ",e.jsx("strong",{children:"instagram_basic"}),", ",e.jsx("strong",{children:"pages_manage_posts"}),", and ",e.jsx("strong",{children:"instagram_content_publish"}),"."]}),e.jsxs("div",{className:"space-y-3",children:[_.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(q,{size:"sm",variant:"outline",onClick:()=>A(E.id),disabled:i===E.id,children:i===E.id?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(tS,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${E.id}`)),b.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(gu,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",E.platform_username||"Instagram"]})]}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>A(E.id),disabled:i===E.id,children:i===E.id?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(tS,{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,D)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[E.status==="success"?e.jsx(qn,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):E.status==="pending"?e.jsx(ls,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(ad,{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})]})]},D))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Note: Facebook posts are auto-deleted. Instagram posts will remain and should be manually deleted. Allow up to 24 hours for Meta to register the API calls."})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-lg",children:"How it works"})}),e.jsx(Pe,{children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"1"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Connect your accounts"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link your Facebook, Instagram, or LinkedIn account"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"2"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Browse Social Swag"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Find the perfect image and caption for your post"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"3"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Post with one click"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Click "Create Post" to share directly to your accounts'})]})]})]})})]})]})})}function QKs(){const[s]=ic(),t=qr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing your connection...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:f,error:x}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/social-connections/callback"}});if(x)throw x;if(f!=null&&f.success)n("success"),i(`Successfully connected ${((m=f.accounts)==null?void 0:m.length)||0} account(s)!`),he.success("Social accounts connected successfully!");else throw new Error((f==null?void 0:f.error)||"Unknown error")}catch(f){console.error("OAuth callback error:",f),n("error"),i(f instanceof Error?f.message:"Failed to connect accounts"),he.error("Failed to connect: "+(f instanceof Error?f.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{className:"text-center",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(Ti,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(ad,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Dt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Ur,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(q,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"View Connected Accounts":"Try Again"})})]})})}function JKs(){const[s]=ic(),t=qr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your Google Business Profile...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),he.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:m,error:f}=await U.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:u}});if(f)throw f;if(m!=null&&m.success)n("success"),i(m.message||"Successfully connected Google Business Profile!"),he.success("Google Business Profile connected!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("Google OAuth callback error:",m),n("error"),i(m instanceof Error?m.message:"Failed to connect Google Business Profile"),he.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{className:"text-center",children:[r==="loading"&&e.jsx(ls,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(Ti,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(ad,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Dt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Ur,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(q,{onClick:()=>t("/social-connections"),children:r==="success"?"View Connected Accounts":"Try Again"})})]})})}function eYs(){const[s]=ic(),t=qr(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your LinkedIn account...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("state"),d=s.get("error"),u=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,u),n("error"),i(u||"Failed to connect LinkedIn account"),he.error(u||"Failed to connect LinkedIn");return}if(!o){n("error"),i("No authorization code received"),he.error("No authorization code received");return}try{const{data:f,error:x}=await U.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(x)throw x;if(f!=null&&f.success)n("success"),i(`Successfully connected ${((m=f.accounts)==null?void 0:m.length)||1} LinkedIn account`),he.success("LinkedIn connected successfully!");else throw new Error((f==null?void 0:f.error)||"Failed to connect LinkedIn account")}catch(f){console.error("LinkedIn callback error:",f),n("error"),i(f instanceof Error?f.message:"Failed to connect LinkedIn account"),he.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Pt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 rounded-full bg-blue-600/10 p-4 w-fit",children:[r==="loading"&&e.jsx(ls,{className:"h-8 w-8 animate-spin text-blue-600"}),r==="success"&&e.jsx(Ti,{className:"h-8 w-8 text-green-600"}),r==="error"&&e.jsx(ad,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Dt,{className:"flex items-center justify-center gap-2",children:[e.jsx(Yf,{className:"h-5 w-5 text-blue-600"}),r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Ur,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:e.jsx(q,{onClick:()=>t("/mission-control/integrations"),disabled:r==="loading",children:r==="success"?"View Integrations":"Back to Integrations"})})]})})}function tYs(){const s=qr(),[t,r]=k.useState(null),{data:n,isLoading:a}=obt(t||void 0,!0),{data:i,isLoading:l}=xIe(!0),{cartItems:o}=Lge(),c=o.reduce((u,m)=>u+m.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(ws,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(u=>e.jsx(dr,{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(dr,{className:"h-72 w-full"},u))})]})}):e.jsx(ws,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs(q,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(lg,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(Xe,{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(q,{variant:t===null?"default":"outline",size:"sm",onClick:()=>r(null),children:"All"}),i.map(u=>e.jsx(q,{variant:t===u.id?"default":"outline",size:"sm",onClick:()=>r(u.id),children:u.name},u.id))]}),n&&n.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:n.map(u=>{var m;return e.jsxs(ke,{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:((m=u.images.find(f=>f.is_primary))==null?void 0:m.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(yc,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(Xe,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Pe,{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(yc,{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 Dbt=k.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));Dbt.displayName="Breadcrumb";const Rbt=k.forwardRef(({className:s,...t},r)=>e.jsx("ol",{ref:r,className:zt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));Rbt.displayName="BreadcrumbList";const hhe=k.forwardRef(({className:s,...t},r)=>e.jsx("li",{ref:r,className:zt("inline-flex items-center gap-1.5",s),...t}));hhe.displayName="BreadcrumbItem";const BCe=k.forwardRef(({asChild:s,className:t,...r},n)=>{const a=s?i5e:"a";return e.jsx(a,{ref:n,className:zt("transition-colors hover:text-foreground",t),...r})});BCe.displayName="BreadcrumbLink";const Obt=k.forwardRef(({className:s,...t},r)=>e.jsx("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:zt("font-normal text-foreground",s),...t}));Obt.displayName="BreadcrumbPage";const $Ce=({children:s,className:t,...r})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:zt("[&>svg]:size-3.5",t),...r,children:s??e.jsx(Ia,{})});$Ce.displayName="BreadcrumbSeparator";function sYs(){var Q,W;const{productId:s}=xo(),t=qr(),{data:r,isLoading:n}=ZGs(s||""),{addToCart:a,cartItems:i}=Lge(),[l,o]=k.useState(null),[c,d]=k.useState(1),[u,m]=k.useState(0),[f,x]=k.useState(null),[y,_]=k.useState(!1),[b,j]=k.useState(!1),N=(Q=r==null?void 0:r.variants)==null?void 0:Q.find(te=>te.id===l),C=((W=r==null?void 0:r.variants)==null?void 0:W.filter(te=>te.is_active))||[],A=Number((r==null?void 0:r.base_price)||0),E=N?Number(N.price_adjustment):0,D=A+E,R=Number((r==null?void 0:r.shipping_fee)||0),F=i.reduce((te,ne)=>te+ne.quantity,0),O=async te=>{if(!te.target.files||te.target.files.length===0)return;_(!0);const ne=te.target.files[0],ae=ne.name.split(".").pop(),ue=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${ae}`;try{const{error:me}=await U.storage.from("marketplace").upload(ue,ne);if(me)throw me;const{data:{publicUrl:de}}=U.storage.from("marketplace").getPublicUrl(ue);x(de),he.success("Artwork uploaded successfully")}catch(me){he.error("Failed to upload artwork: "+me.message)}finally{_(!1)}},B=()=>{if(r){if(C.length>0&&!l){he.error("Please select an option");return}a(r,N||void 0,c,f||void 0),j(!0),he.success("Added to cart!"),setTimeout(()=>j(!1),2e3)}},K=()=>{r!=null&&r.images&&m(te=>(te+1)%r.images.length)},Z=()=>{r!=null&&r.images&&m(te=>(te-1+r.images.length)%r.images.length)};return n?e.jsx(ws,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(dr,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(dr,{className:"h-8 w-3/4"}),e.jsx(dr,{className:"h-6 w-1/4"}),e.jsx(dr,{className:"h-24 w-full"}),e.jsx(dr,{className:"h-12 w-full"})]})]})}):r?e.jsxs(ws,{title:r.name,children:[e.jsx(Dbt,{className:"mb-6",children:e.jsxs(Rbt,{children:[e.jsx(hhe,{children:e.jsx(BCe,{asChild:!0,children:e.jsx(Vn,{to:"/marketplace",children:"Marketplace"})})}),r.category&&e.jsxs(e.Fragment,{children:[e.jsx($Ce,{}),e.jsx(hhe,{children:e.jsx(BCe,{asChild:!0,children:e.jsx(Vn,{to:`/marketplace?category=${r.category.id}`,children:r.category.name})})})]}),e.jsx($Ce,{}),e.jsx(hhe,{children:e.jsx(Obt,{children:r.name})})]})}),e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative aspect-square bg-muted rounded-lg overflow-hidden flex items-center justify-center",children:r.images&&r.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:r.images[u].image_url,alt:r.name,className:"max-w-full max-h-full object-contain"}),r.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(q,{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(jl,{className:"h-6 w-6"})}),e.jsx(q,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:K,children:e.jsx(Ia,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(yc,{className:"h-24 w-24 text-muted-foreground"})})}),r.images&&r.images.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:r.images.map((te,ne)=>e.jsx("button",{onClick:()=>m(ne),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${ne===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:te.image_url,alt:"",className:"w-full h-full object-cover"})},te.id))}),r.video&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Product Video"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:r.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[r.category&&e.jsx(Xe,{variant:"secondary",className:"mb-2",children:r.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:r.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",D.toFixed(2)]}),R>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",R.toFixed(2)," shipping"]})]})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})}),C.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C.map(te=>e.jsxs(q,{variant:l===te.id?"default":"outline",onClick:()=>o(te.id),children:[te.name,Number(te.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(te.price_adjustment)>0?"+":"","$",Number(te.price_adjustment).toFixed(2),")"]})]},te.id))})]}),r.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{children:"Upload Your Artwork (Optional)"}),f?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:f,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(q,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>x(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:O,className:"hidden",id:"artwork-upload",disabled:y}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(ka,{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(ce,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"outline",size:"icon",onClick:()=>d(te=>Math.max(1,te-1)),children:"-"}),e.jsx(Ne,{type:"number",value:c,onChange:te=>d(Math.max(1,parseInt(te.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(q,{variant:"outline",size:"icon",onClick:()=>d(te=>te+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(q,{size:"lg",className:"flex-1",onClick:B,disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(la,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(lg,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(q,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(lg,{className:"h-5 w-5"}),F>0&&e.jsx(Xe,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:F})]})]}),r.requires_proof_approval&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-lg",children:"📋 This product requires proof approval before production. You'll receive a proof to review after your order is placed."})]})]})]}):e.jsx(ws,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(yc,{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(q,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function rYs(){const s=qr(),{cartItems:t,removeFromCart:r,updateQuantity:n,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=Lge(),[d,u]=k.useState(!1),[m,f]=k.useState(""),x=async()=>{if(t.length===0){he.error("Your cart is empty");return}u(!0);try{const{data:y,error:_}=await U.functions.invoke("marketplace-checkout",{body:{items:t.map(b=>{var j;return{product_id:b.product.id,variant_id:((j=b.variant)==null?void 0:j.id)||null,quantity:b.quantity,artwork_url:b.artworkUrl||null}}),notes:m.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){he.error("Checkout failed: "+y.message)}finally{u(!1)}};return t.length===0?e.jsx(ws,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(T_,{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(q,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(ws,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(y=>{var _,b;return e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children: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(T_,{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(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return r(y.product.id,(j=y.variant)==null?void 0:j.id)},children:e.jsx(zr,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return n(y.product.id,(j=y.variant)==null?void 0:j.id,y.quantity-1)},disabled:y.quantity<=1,children:e.jsx(N_,{className:"h-3 w-3"})}),e.jsx(Ne,{type:"number",value:y.quantity,onChange:j=>{var N;return n(y.product.id,(N=y.variant)==null?void 0:N.id,parseInt(j.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(q,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return n(y.product.id,(j=y.variant)==null?void 0:j.id,y.quantity+1)},children:e.jsx(Ys,{className:"h-3 w-3"})})]})]})]})})},`${y.product.id}-${((b=y.variant)==null?void 0:b.id)||"base"}`)}),e.jsx(q,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(ke,{className:"sticky top-4",children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Order Summary"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((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(cl,{}),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(cl,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(pr,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:m,onChange:y=>f(y.target.value),rows:3,className:"resize-none"})]}),e.jsx(q,{className:"w-full",size:"lg",onClick:x,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(ci,{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 nYs(){const s=qr(),{data:t,isLoading:r}=oWs();return r?e.jsx(ws,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(n=>e.jsx(dr,{className:"h-32 w-full"},n))})}):!t||t.length===0?e.jsx(ws,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(yc,{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(q,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(ws,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(n=>{var a,i,l;return e.jsx(ke,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${n.id}`),children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:n.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:As(new Date(n.created_at),"MMM d, yyyy")})]}),e.jsx(Xe,{className:pIe[n.status],children:DP[n.status]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex -space-x-2",children:[(a=n.items)==null?void 0:a.slice(0,3).map((o,c)=>e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",style:{zIndex:3-c},children:[o.quantity,"×"]},o.id)),n.items&&n.items.length>3&&e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",children:["+",n.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=n.items)==null?void 0:i.length)===1?n.items[0].product_name:`${(l=n.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(n.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n.tracking_url&&e.jsxs(q,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(n.tracking_url,"_blank")},children:[e.jsx(un,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(Ia,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},n.id)})})})}const aYe=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function aYs({currentStatus:s,statusHistory:t}){const r=aYe.indexOf(s);return e.jsx("div",{className:"space-y-3",children:aYe.map((n,a)=>{const i=t==null?void 0:t.find(d=>d.status===n),l=ar;return e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center ${l?"bg-green-500 text-white":o?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:l?e.jsx(qn,{className:"h-4 w-4"}):o?e.jsx(jn,{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:DP[n]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[As(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},n)})})}function iYs(){var j;const{orderId:s}=xo(),t=qr(),{data:r,isLoading:n,refetch:a}=lWs(s||""),i=uWs(),l=hWs(),[o,c]=k.useState(!1),[d,u]=k.useState(null),[m,f]=k.useState(""),[x,y]=k.useState(null),_=async N=>{y(N);try{await i.mutateAsync({orderId:s,itemId:N}),he.success("Proof approved!"),a()}catch{he.error("Failed to approve proof")}finally{y(null)}},b=async()=>{if(d){y(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:m}),he.success("Revision requested"),c(!1),f(""),u(null),a()}catch{he.error("Failed to request revision")}finally{y(null)}}};return n?e.jsx(ws,{title:"Order Details",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsx(dr,{className:"h-64 w-full"}),e.jsx(dr,{className:"h-48 w-full"})]}),e.jsx(dr,{className:"h-96 w-full"})]})}):r?e.jsxs(ws,{title:`Order ${r.order_number}`,children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{children:"Order Status"}),e.jsx(Xe,{className:pIe[r.status],children:DP[r.status]})]}),e.jsx(Pe,{children:e.jsx(aYs,{currentStatus:r.status,statusHistory:r.status_history})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Items"})}),e.jsx(Pe,{className:"space-y-4",children:(j=r.items)==null?void 0:j.map(N=>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:N.product_name}),N.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:N.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",N.quantity," × $",Number(N.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(N.unit_price)*N.quantity).toFixed(2)]})]}),N.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:N.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(t2,{className:"h-4 w-4"}),"View Artwork",e.jsx(un,{className:"h-3 w-3"})]})]}),N.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:N.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(t2,{className:"h-4 w-4"}),"View Proof",e.jsx(un,{className:"h-3 w-3"})]}),N.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(q,{size:"sm",onClick:()=>_(N.id),disabled:x===N.id,children:[x===N.id?e.jsx(ls,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(wm,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>{u(N.id),c(!0)},disabled:x===N.id,children:[e.jsx(JF,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),N.proof_status==="approved"&&e.jsxs(Xe,{className:"bg-green-100 text-green-800",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),N.proof_status==="rejected"&&N.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(Xe,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:N.proof_notes})]})]})]},N.id))})]}),r.shipping_name&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(t7,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"font-medium",children:r.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[r.shipping_address,e.jsx("br",{}),r.shipping_city,", ",r.shipping_state," ",r.shipping_zip]}),r.tracking_number&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tracking Number:"}),e.jsx("p",{className:"font-mono font-medium",children:r.tracking_number}),r.tracking_url&&e.jsxs(q,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(r.tracking_url,"_blank"),children:["Track Package",e.jsx(un,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(ke,{className:"sticky top-4",children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Order Summary"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",As(new Date(r.created_at),"MMMM d, yyyy")]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(r.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(r.shipping_total).toFixed(2)]})]})]}),e.jsx(cl,{}),e.jsxs("div",{className:"flex justify-between font-bold text-lg",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(r.total).toFixed(2)]})]}),r.notes&&e.jsxs(e.Fragment,{children:[e.jsx(cl,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Order Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.notes})]})]})]})]})})]}),e.jsx(vs,{open:o,onOpenChange:c,children:e.jsxs(ys,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Request Changes"}),e.jsx(an,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(pr,{placeholder:"Describe the changes needed...",value:m,onChange:N=>f(N.target.value),rows:4}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(q,{onClick:b,disabled:!m.trim()||x!==null,children:[x?e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(ws,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(yc,{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(q,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function oYs(){const s=qr(),[t]=ic();return t.get("session_id"),k.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(ws,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-8 pb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(qn,{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(yc,{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(q,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(ci,{className:"h-4 w-4 ml-2"})]}),e.jsx(q,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function lYs(){const{user:s}=Cs(),[t,r]=k.useState("store"),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),[d,u]=k.useState(5),[m,f]=k.useState(""),[x,y]=k.useState(!1),[_,b]=k.useState(!1),[j,N]=k.useState(""),[C,A]=k.useState(null),[E,D]=k.useState(!1),{hasSubmittedReview:R,submitReview:F,markPostedToGoogle:O}=fct(),{data:B}=cbt(),{data:K,isLoading:Z}=lbt(),{data:Q,isLoading:W}=vWs(n),{data:te,isLoading:ne}=bWs(s==null?void 0:s.id),{data:ae=0}=wWs(s==null?void 0:s.id),ue=jWs(),me=new Set((te==null?void 0:te.map(Oe=>Oe.item_id))||[]),de=async()=>{if(i)try{const Oe=await ue.mutateAsync(i.id);i.item_type==="reelflow_credits"?he.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):he.success(`Successfully purchased "${i.name}"!`),l(null)}catch(Oe){he.error(Oe.message||"Failed to purchase item")}},fe=async()=>{if(!m.trim()){he.error("Please write a review");return}y(!0);const Oe=await F(d,m);y(!1),Oe.success?(he.success("Thank you for your review! You earned 25 points!"),N(m),b(!0),f(""),u(5)):he.error(Oe.error||"Failed to submit review")},je=()=>{navigator.clipboard.writeText(j),he.success("Review copied to clipboard!")},xe=()=>{O(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},Ee=()=>{b(!1),c(!1),N("")};return Z||W||ne?e.jsx(ws,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(dr,{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(Oe=>e.jsx(dr,{className:"h-64"},Oe))})]})}):e.jsxs(ws,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Reward Store"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Redeem your points for exclusive rewards"})]}),e.jsx(ke,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/20 flex items-center justify-center",children:e.jsx(fa,{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:ae.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(wo,{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(ld,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(E0,{open:E,onOpenChange:D,children:e.jsxs(ke,{className:"border-primary/20",children:[e.jsx(A0,{asChild:!0,children:e.jsx(Pt,{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(wo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-base",children:"How to Earn Points"}),e.jsx(Ur,{children:"See all the ways you can earn spendable points"})]})]}),E?e.jsx(pg,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Co,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(M0,{children:e.jsx(Pe,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[B==null?void 0:B.filter(Oe=>Oe.is_active).map(Oe=>{const Ie=ze=>{switch(ze){case"event_attendance":return e.jsx(vn,{className:"h-5 w-5"});case"leave_review":return e.jsx(fa,{className:"h-5 w-5"});case"add_listing":return e.jsx(Pn,{className:"h-5 w-5"});case"first_contact":return e.jsx(Dr,{className:"h-5 w-5"});case"first_video":return e.jsx(bn,{className:"h-5 w-5"});case"first_community_post":return e.jsx(Ui,{className:"h-5 w-5"});default:return e.jsx(Di,{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:Ie(Oe.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:Oe.action_name}),Oe.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Oe.description})]}),e.jsxs(Xe,{variant:"secondary",className:"font-bold shrink-0",children:["+",Oe.points]})]},Oe.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(ld,{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(Xe,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!R&&e.jsx(ke,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-yellow-500/20 flex items-center justify-center",children:e.jsx(Ui,{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(q,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(fa,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(ta,{value:t,onValueChange:r,children:[e.jsxs(ea,{children:[e.jsxs(rs,{value:"store",className:"flex items-center gap-2",children:[e.jsx(T_,{className:"h-4 w-4"}),"Store"]}),e.jsxs(rs,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"}),"My Rewards",te&&te.length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1",children:te.length})]})]}),e.jsxs(fs,{value:"store",className:"mt-6",children:[K&&K.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(q,{variant:n===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),K.map(Oe=>e.jsxs(q,{variant:n===Oe.id?"default":"outline",size:"sm",onClick:()=>a(Oe.id),children:[Oe.icon&&`${Oe.icon} `,Oe.name]},Oe.id))]}),!Q||Q.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Di,{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:Q.map(Oe=>{const Ie=Oe.item_type==="reelflow_credits",ze=!Ie&&me.has(Oe.id),Ve=!Ie&&Oe.max_quantity!==null&&Oe.current_quantity===0,Le=ae>=Oe.points_cost;return e.jsxs(ke,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${ze?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>A(Oe),children:[Oe.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:Oe.preview_image_url,alt:Oe.name,className:"w-full h-full object-cover"}),ze&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Xe,{className:"bg-green-500 text-white",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Ve&&!ze&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Xe,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Di,{className:"h-12 w-12 text-muted-foreground/50"}),ze&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Xe,{className:"bg-green-500 text-white",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Pt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(Dt,{className:"text-lg",children:Oe.name}),e.jsxs(Xe,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(fa,{className:"h-3 w-3 mr-1"}),Oe.points_cost]})]}),Oe.category&&e.jsxs(Xe,{variant:"outline",className:"w-fit",children:[Oe.category.icon&&`${Oe.category.icon} `,Oe.category.name]})]}),e.jsxs(Pe,{children:[e.jsx(Ur,{className:"mb-4 line-clamp-2",children:Oe.description||"No description available"}),Oe.max_quantity!==null&&!ze&&!Ie&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[Oe.current_quantity," of ",Oe.max_quantity," remaining"]}),Ie&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",Oe.max_quantity," ReelFlow credits per purchase"]}),ze?e.jsx(q,{className:"w-full",onClick:$e=>{$e.stopPropagation(),Oe.file_url&&_je(Oe.file_url,Oe.name)},disabled:!Oe.file_url,children:Oe.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(q,{className:"w-full",onClick:$e=>{$e.stopPropagation(),l(Oe)},disabled:Ve||!Le,children:Ve?"Sold Out":Le?e.jsxs(e.Fragment,{children:[e.jsx(T_,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${Oe.points_cost-ae} more pts`})]})]},Oe.id)})})]}),e.jsx(fs,{value:"my-rewards",className:"mt-6",children:!te||te.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(yc,{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:te.map(Oe=>{var Ie,ze,Ve,Le,$e,ve,Qe;return e.jsxs(ke,{className:"overflow-hidden",children:[(Ie=Oe.item)!=null&&Ie.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:Oe.item.preview_image_url,alt:((ze=Oe.item)==null?void 0:ze.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(Di,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Pt,{className:"pb-2",children:[e.jsx(Dt,{className:"text-lg",children:((Ve=Oe.item)==null?void 0:Ve.name)||"Unknown Item"}),e.jsxs(Ur,{className:"text-xs",children:["Purchased for ",Oe.points_spent," points • ",new Date(Oe.purchased_at).toLocaleDateString()]})]}),e.jsx(Pe,{children:((Le=Oe.item)==null?void 0:Le.item_type)==="reelflow_credits"?e.jsxs(q,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(qn,{className:"h-4 w-4 mr-2 text-green-500"}),($e=Oe.item)==null?void 0:$e.max_quantity," Credits Applied"]}):e.jsx(q,{className:"w-full",onClick:()=>{var we,nt;(we=Oe.item)!=null&&we.file_url&&_je(Oe.item.file_url,(nt=Oe.item)==null?void 0:nt.name)},disabled:!((ve=Oe.item)!=null&&ve.file_url),children:((Qe=Oe.item)==null?void 0:Qe.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},Oe.id)})})})]})]}),e.jsx(el,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Confirm Purchase"}),e.jsxs(Ho,{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:[ae," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[ae-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:de,disabled:ue.isPending,children:ue.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(vs,{open:o,onOpenChange:Oe=>{!Oe&&_?Ee():c(Oe)},children:e.jsx(ys,{children:_?e.jsxs(e.Fragment,{children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(an,{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(q,{variant:"outline",className:"w-full",onClick:je,children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(fn,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(q,{variant:"outline",onClick:Ee,children:"Maybe Later"}),e.jsxs(q,{onClick:xe,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Leave a Review"}),e.jsx(an,{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(Oe=>e.jsx("button",{type:"button",onClick:()=>u(Oe),className:"focus:outline-none",children:e.jsx(fa,{className:`h-8 w-8 transition-colors ${d>=Oe?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},Oe))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(pr,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:m,onChange:Oe=>f(Oe.target.value),rows:4})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(q,{onClick:fe,disabled:x,className:"bg-yellow-600 hover:bg-yellow-700",children:x?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(vs,{open:!!C,onOpenChange:()=>A(null),children:e.jsxs(ys,{className:"max-w-lg",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[C==null?void 0:C.name,e.jsxs(Xe,{variant:"secondary",className:"font-bold",children:[e.jsx(fa,{className:"h-3 w-3 mr-1"}),C==null?void 0:C.points_cost]})]}),(C==null?void 0:C.category)&&e.jsxs(Xe,{variant:"outline",className:"w-fit",children:[C.category.icon&&`${C.category.icon} `,C.category.name]})]}),(C==null?void 0:C.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:C.preview_image_url,alt:C.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(C==null?void 0:C.description)||"No description available"}),(C==null?void 0:C.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",C==null?void 0:C.max_quantity," ReelFlow credits per purchase"]}),(C==null?void 0:C.item_type)!=="reelflow_credits"&&(C==null?void 0:C.max_quantity)!==null&&!me.has((C==null?void 0:C.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[C==null?void 0:C.current_quantity," of ",C==null?void 0:C.max_quantity," remaining"]})]}),e.jsx(fn,{children:C&&C.item_type!=="reelflow_credits"&&me.has(C.id)?e.jsx(q,{className:"w-full",onClick:()=>{C.file_url&&_je(C.file_url,C.name)},disabled:!C.file_url,children:C.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Access"]})}):C&&e.jsx(q,{className:"w-full",onClick:()=>{A(null),l(C)},disabled:C.item_type!=="reelflow_credits"&&C.max_quantity!==null&&C.current_quantity===0||ae{s&&ne()},[s==null?void 0:s.id]);const ne=async()=>{if(!s)return;o(!0),j(!1),_(!0);const{data:$e}=await U.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);$e==null||$e.forEach(nt=>{nt.action_key==="referral_signup"&&m(nt.points),nt.action_key==="referral_paid"&&x(nt.points)});const{data:ve}=await U.from("profiles").select("name").eq("id",s.id).maybeSingle();ve!=null&&ve.name&&C(ve.name);let{data:Qe}=await U.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Qe){const{data:nt}=await U.rpc("generate_agent_referral_code",{_user_id:s.id}),Se=nt||`agent${s.id.slice(0,6)}`,{data:Ge,error:We}=await U.from("agent_referral_codes").insert({user_id:s.id,code:Se}).select("code").maybeSingle();!We&&Ge&&(Qe=Ge)}i((Qe==null?void 0:Qe.code)??null);const{data:we}=await U.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(we&&we.length>0){const nt=we.map(We=>We.referred_user_id),{data:Se}=await U.from("profiles").select("id, name, email").in("id",nt),Ge=new Map((Se==null?void 0:Se.map(We=>[We.id,We]))??[]);d(we.map(We=>({...We,referred_profile:Ge.get(We.referred_user_id)??null})))}else d([]);o(!1)},ae=k.useMemo(()=>a?`${cYs}/trial?ref=${a}`:"",[a]),ue=c.length,me=c.filter($e=>$e.status==="qualified").length,de=c.filter($e=>$e.signup_points_awarded).length*u+c.filter($e=>$e.paid_points_awarded).length*f,fe=async()=>{ae&&(await navigator.clipboard.writeText(ae),he.success("Referral link copied!"))},je=()=>{const $e=encodeURIComponent("Join me on LevelUp"),ve=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: ${ae} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${$e}&body=${ve}`},xe=()=>{const $e=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${ae}`);window.location.href=`sms:?&body=${$e}`},Ee=async()=>{if(navigator.share&&ae)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:ae})}catch{}else fe()},Me=$e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($e.trim()),Oe=$e=>{const ve=($e??D).trim().replace(/,$/,"");if(!ve)return;const Qe=ve.split(/[\s,;]+/).filter(Boolean),we=[...F];let nt=0;for(const Se of Qe){if(!Me(Se)){he.error(`Invalid email: ${Se}`);continue}we.includes(Se)||(we.push(Se),nt++)}O(we),nt>0&&R("")},Ie=$e=>O(F.filter(ve=>ve!==$e)),ze=()=>{Q(`${N?N.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),K("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)},Ve=$e=>{const ve=$e.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Qe=N||"A fellow agent",we="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",nt=ae;return`
LevelUp
You're Invited

${Qe} thinks you'd love LevelUp 🎉

${ve}

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

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

`.trim()},Le=async()=>{if(F.length===0&&(D.trim()&&Oe(),F.length===0)){he.error("Add at least one recipient");return}if(!Z.trim()){he.error("Subject is required");return}te(!0);const $e=Ve(B);let ve=0,Qe=0;for(const we of F)try{const{data:nt,error:Se}=await U.functions.invoke("gmail-send",{body:{to:we,subject:Z,body:$e,source:"referral_invite"}});if(Se||nt!=null&&nt.error)throw new Error((Se==null?void 0:Se.message)||(nt==null?void 0:nt.error));ve++}catch(nt){console.error("Gmail send failed for",we,nt),Qe++}te(!1),ve>0?(he.success(`Invite sent to ${ve} ${ve===1?"person":"people"}`+(Qe>0?` (${Qe} failed)`:"")),O([]),R(""),E(!1)):he.error("Failed to send invites")};return!b&&!y?e.jsx(ws,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(Yo,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(ke,{className:"border-2 border-dashed",children:[e.jsxs(Pt,{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(Dt,{children:"Refer & Earn is for active members"}),e.jsx(Ur,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Pe,{className:"flex justify-center",children:e.jsx(q,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(ws,{title:"Refer & Earn",children:[e.jsxs("div",{className:"container max-w-5xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs(Yo,{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(Di,{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:[f," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx(Dr,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ue}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx(qn,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:me}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx(wo,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:de.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Ur,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(Ne,{readOnly:!0,value:l?"Loading…":ae,className:"font-mono text-sm",onFocus:$e=>$e.currentTarget.select()}),e.jsxs(q,{onClick:fe,disabled:!ae,children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[r&&e.jsxs(q,{size:"sm",onClick:ze,disabled:!ae,className:"bg-primary hover:bg-primary/90",children:[e.jsx(hn,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:je,disabled:!ae,children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:xe,disabled:!ae,children:[e.jsx(Ui,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:Ee,disabled:!ae,children:[e.jsx(Ec,{className:"h-4 w-4 mr-2"})," More…"]})]}),!r&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["💡 ",e.jsx("button",{onClick:()=>t("/integrations"),className:"underline hover:text-foreground",children:"Connect Gmail"})," to send branded invite emails directly from your inbox."]}),a&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Your code: ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:a})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Your Referrals"}),e.jsx(Ur,{children:"Track who joined and when they upgrade."})]}),e.jsx(Pe,{children:l?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Loading…"}):c.length===0?e.jsxs("div",{className:"text-center py-10 space-y-2",children:[e.jsx(Dr,{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($e=>{var we,nt;const ve=((we=$e.referred_profile)==null?void 0:we.name)||((nt=$e.referred_profile)==null?void 0:nt.email)||"New agent",Qe=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date($e.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:ve}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Qe]})]}),$e.status==="qualified"?e.jsxs(Xe,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"})," Paid · +",u+f," pts"]}):e.jsxs(Xe,{variant:"secondary",children:[e.jsx(jn,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},$e.id)})})})]}),e.jsx(ke,{className:"bg-muted/30",children:e.jsxs(Pe,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Ir,{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:[f," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(cl,{className:"opacity-0"})]}),e.jsx(vs,{open:A,onOpenChange:E,children:e.jsxs(ys,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(hn,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(an,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:n}),". We'll deliver a branded LevelUp invite with your personal note."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[F.map($e=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 pr-1",children:[$e,e.jsx("button",{type:"button",onClick:()=>Ie($e),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${$e}`,children:e.jsx($r,{className:"h-3 w-3"})})]},$e)),e.jsx("input",{type:"email",value:D,onChange:$e=>R($e.target.value),onKeyDown:$e=>{$e.key==="Enter"||$e.key===","||$e.key===" "?($e.preventDefault(),Oe()):$e.key==="Backspace"&&!D&&F.length>0&&O(F.slice(0,-1))},onBlur:()=>D.trim()&&Oe(),onPaste:$e=>{const ve=$e.clipboardData.getData("text");/[\s,;]/.test(ve)&&($e.preventDefault(),Oe(ve))},placeholder:F.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(ce,{htmlFor:"email-subject",children:"Subject"}),e.jsx(Ne,{id:"email-subject",value:Z,onChange:$e=>Q($e.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(pr,{id:"personal-note",value:B,onChange:$e=>K($e.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(ce,{children:"Preview"}),e.jsxs("div",{className:"border rounded-md overflow-hidden bg-muted/30",children:[e.jsxs("div",{className:"px-3 py-2 bg-muted/60 border-b text-xs text-muted-foreground flex items-center justify-between",children:[e.jsxs("span",{className:"truncate",children:["From: ",n]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",Z||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Ve(B),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>E(!1),disabled:W,children:"Cancel"}),e.jsxs(q,{onClick:Le,disabled:W,children:[e.jsx(hn,{className:"h-4 w-4 mr-2"}),W?"Sending…":`Send${F.length>0?` to ${F.length}`:""}`]})]})]})})]})}const Fbt=()=>{const{user:s}=Cs(),t=is(),r=pt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await U.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),n=pt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await U.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=Mt({mutationFn:async d=>{const{data:u,error:m}=await U.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(m)throw m;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=Mt({mutationFn:async({id:d,...u})=>{const{data:m,error:f}=await U.from("smart_presentations").update(u).eq("id",d).select().single();if(f)throw f;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=Mt({mutationFn:async d=>{const{data:u,error:m}=await U.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(m)throw m;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),he.success("Presentation published!")}}),o=Mt({mutationFn:async d=>{const{error:u}=await U.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),he.success("Presentation archived")}}),c=Mt({mutationFn:async d=>{const{error:u}=await U.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),he.success("Saved as template!")}});return{presentations:r.data||[],templates:n.data||[],isLoading:r.isLoading,templatesLoading:n.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},uYs=()=>{const s=qr(),{presentations:t,isLoading:r,archivePresentation:n,saveAsTemplate:a}=Fbt(),i=o=>o.status==="draft"?e.jsx(Xe,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(Xe,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(Xe,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(Xe,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),he.success("Link copied!")};return e.jsx(ws,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs(q,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Create Presentation"]})]}),r?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(dr,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Jy,{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(q,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(ke,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(En,{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 ",As(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nn,{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(q,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(q,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Fy,{className:"h-4 w-4"})})}),e.jsxs(Sd,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(ti,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(ti,{onClick:()=>a.mutate(o),children:[e.jsx(En,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(ti,{onClick:()=>n.mutate(o.id),className:"text-destructive",children:[e.jsx(Qk,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},iYe={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."}]},hYs=[{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 mYs(s){const t=iYe[s];if(t)return t;const r=s.toLowerCase();for(const[n,a]of Object.entries(iYe))if(r.includes(n.toLowerCase())||n.toLowerCase().includes(r))return a;return hYs}function fYs({sectionTitle:s,contactId:t,onVideoReady:r}){const[n,a]=k.useState(!1),[i,l]=k.useState("script"),[o,c]=k.useState(0),[d,u]=k.useState(0),{canRecord:m}=Q0t(),f=V2(),[x,y]=k.useState(""),[_,b]=k.useState(!1),[j,N]=k.useState(!0),[C,A]=k.useState(!1),[E,D]=k.useState(null),R=mYs(s),F=()=>{l("script"),c(0),u(0),y(""),b(!1),N(!0),A(!1),D(null)},O=W=>{!W&&(i==="uploading"||i==="processing")||(a(W),W||F())},B=W=>{D(W),y(R[W].text),b(!1)},K=()=>{l("record"),N(x.trim().length>0)},Z=()=>{y(""),N(!1),l("record")},Q=k.useCallback(async(W,te)=>{l("uploading");try{const ne=s||"Presentation Video",{videoId:ae,uploadUrl:ue,libraryId:me}=await dM(ne),{apiKey:de}=await uM(ae),fe=new XMLHttpRequest;fe.upload.onprogress=Oe=>{Oe.lengthComputable&&c(Oe.loaded/Oe.total*100)},await new Promise((Oe,Ie)=>{fe.onload=()=>fe.status>=200&&fe.status<300?Oe():Ie(new Error("Upload failed")),fe.onerror=()=>Ie(new Error("Upload failed")),fe.open("PUT",ue),fe.setRequestHeader("AccessKey",de),fe.send(W)}),l("processing");let je=0;const xe=Date.now(),Ee=9e4;let Me=null;for(;je<4;){if(await new Promise(Ie=>setTimeout(Ie,3e3)),Date.now()-xe>Ee){const Ie=W.size/1048576,ze=`https://iframe.mediadelivery.net/embed/${me}/${ae}?responsive=true`;await f.mutateAsync({bunny_video_id:ae,playback_url:ze,file_size_mb:Ie,title:ne,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),r(ze),he.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const Oe=await W_(ae);if(je=Oe.status,u(Oe.encodeProgress||0),je===4)Me={playbackUrl:Oe.directPlayUrl,thumbnailUrl:Oe.thumbnailUrl,previewUrl:Oe.previewUrl||null,duration:Oe.length||te,fileSizeMb:(Oe.storageSize||W.size)/(1024*1024)};else if(je===5||je===6)throw new Error("Video processing failed")}if(!Me)throw new Error("No video data");await f.mutateAsync({bunny_video_id:ae,contact_id:t||void 0,playback_url:Me.playbackUrl,thumbnail_url:Me.thumbnailUrl,preview_url:Me.previewUrl,duration_seconds:Me.duration,file_size_mb:Me.fileSizeMb,title:ne,status:"ready",touch_type:"presentation"}),r(Me.playbackUrl),he.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(ne){console.error("Recording upload error:",ne),he.error("Failed to process video. Please try again."),l("record")}},[s,t,r,f]);return e.jsxs(vs,{open:n,onOpenChange:O,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[90vh] overflow-y-auto !top-[5%] !translate-y-0 sm:!top-[5%] sm:!translate-y-0",children:[e.jsx(_s,{children:e.jsxs(bs,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:R.map((W,te)=>e.jsxs("button",{onClick:()=>B(te),className:zt("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",E===te?"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(En,{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})]},te))})]}),x&&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(q,{variant:"ghost",size:"sm",onClick:()=>b(!0),className:"h-7 text-xs gap-1",children:[e.jsx(Ua,{className:"h-3 w-3"}),"Edit"]})]}),_?e.jsx(pr,{value:x,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:x})]}),!x&&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(pr,{value:x,onChange:W=>{y(W.target.value),D(null)},rows:4,placeholder:"Type your own script here...",className:"text-sm"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:Z,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(q,{onClick:K,disabled:!1,children:x.trim()?"Continue with Script":"Continue Without Script"})]})]}),!m&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(du,{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."}),x.trim()&&e.jsxs(q,{variant:"ghost",size:"sm",onClick:()=>N(!j),className:"h-7 text-xs gap-1",children:[j?e.jsx(Wf,{className:"h-3 w-3"}):e.jsx(Nn,{className:"h-3 w-3"}),j?"Hide Script":"Show Script"]})]}),e.jsx(pM,{maxDurationSeconds:600,onRecordingComplete:Q,onRecordingStateChange:A,onError:W=>he.error(W),teleprompterContent:x.trim()?e.jsx(cIe,{text:x,isVisible:j,onToggleVisibility:()=>N(!j),isRecording:C,startCountdown:!1}):void 0}),e.jsx(q,{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(ls,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ki,{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(ls,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ki,{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(Ti,{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 pYs({sectionTitle:s,contactId:t,onVideoReady:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState("idle"),[d,u]=k.useState(0),m=k.useRef(null),f=V2(),{data:x}=wye(),y=(x==null?void 0:x.total_storage_mb)||0,b=((x==null?void 0:x.max_storage_mb)||1024)-y,j=()=>{l(null),c("idle"),u(0)},N=R=>{!R&&o!=="idle"&&o!=="done"||(a(R),R||j())},C=R=>{var B;const F=(B=R.target.files)==null?void 0:B[0];if(!F)return;if(!F.type.startsWith("video/")){he.error("Please select a video file");return}const O=F.size/(1024*1024);if(O>500){he.error("Video file must be less than 500MB");return}if(O>b){he.error(`Not enough storage. You have ${b.toFixed(1)} MB remaining.`);return}l(F)},A=k.useCallback(async()=>{if(i){c("creating"),u(0);try{const R=s||i.name,{data:F,error:O}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:R,isAgentVideo:!0}});if(O)throw new Error(O.message);const{videoId:B,libraryId:K}=F;c("uploading");const{data:Z,error:Q}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:B,isAgentVideo:!0}});if(Q)throw new Error(Q.message);await new Promise((ne,ae)=>{const ue=new XMLHttpRequest;ue.upload.addEventListener("progress",me=>{me.lengthComputable&&u(Math.round(me.loaded/me.total*100))}),ue.addEventListener("load",()=>ue.status>=200&&ue.status<300?ne():ae(new Error(`Upload failed (${ue.status})`))),ue.addEventListener("error",()=>ae(new Error("Upload failed"))),ue.open("PUT",Z.uploadUrl),ue.setRequestHeader("AccessKey",Z.apiKey),ue.send(i)}),c("processing");const W=i.size/(1024*1024),te=`https://iframe.mediadelivery.net/embed/${K}/${B}`;await f.mutateAsync({bunny_video_id:B,playback_url:te,file_size_mb:W,title:R,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),r(te),c("done"),he.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(R){console.error("Upload error:",R),he.error(R instanceof Error?R.message:"Failed to upload video"),c("idle")}}},[i,s,t,r,f]),E=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},D=o!=="idle"&&o!=="done";return e.jsxs(vs,{open:n,onOpenChange:N,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(_s,{children:e.jsxs(bs,{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(bn,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(i.size/(1024*1024)).toFixed(1)," MB"]})]}),!D&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx($r,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var R;return(R=m.current)==null?void 0:R.click()},children:[e.jsx(ka,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:m,type:"file",accept:"video/*",className:"hidden",onChange:C,disabled:D}),D&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:E()})]}),e.jsx(ki,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>N(!1),disabled:D,children:"Cancel"}),e.jsx(q,{onClick:A,disabled:!i||D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const oYe=[{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"}],lYe=()=>{const s=qr(),{id:t}=xo(),{user:r}=Cs(),{templates:n,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=Fbt(),{isGmailConnected:c,gmailEmail:d}=Cm(),[u,m]=k.useState(!1),[f,x]=k.useState("client"),[y,_]=k.useState(!1),[b,j]=k.useState(""),[N,C]=k.useState([]),[A,E]=k.useState(!1),[D,R]=k.useState(null),[F,O]=k.useState(!1),[B,K]=k.useState(""),[Z,Q]=k.useState(""),[W,te]=k.useState(""),[ne,ae]=k.useState("buyer"),[ue,me]=k.useState(""),[de,fe]=k.useState(null),[je,xe]=k.useState(""),[Ee,Me]=k.useState([]),[Oe,Ie]=k.useState("schedule_call"),[ze,Ve]=k.useState("Schedule a Call"),[Le,$e]=k.useState(""),[ve,Qe]=k.useState(""),[we,nt]=k.useState(null),[Se,Ge]=k.useState(t||null),[We,Ce]=k.useState(null),[qe,et]=k.useState(!1),Ze=async(ht,Jt)=>{if(!r)return;const Ms=5*1024*1024;if(ht.size>Ms){he.error("Image must be under 5MB");return}if(!ht.type.startsWith("image/")){he.error("Please upload an image file");return}nt(Jt);try{const ts=ht.name.split(".").pop()||"jpg",Xs=`${r.id}/${Date.now()}.${ts}`,{error:js}=await U.storage.from("listing-photos").upload(Xs,ht);if(js)throw js;const{data:{publicUrl:$s}}=U.storage.from("listing-photos").getPublicUrl(Xs);Yt(Jt,{image_url:$s}),he.success("Image uploaded")}catch{he.error("Failed to upload image")}finally{nt(null)}};k.useEffect(()=>{t&&rt(t)},[t]);const rt=async ht=>{const{data:Jt,error:Ms}=await U.from("smart_presentations").select("*").eq("id",ht).single();if(Ms||!Jt)return;const ts=Jt;if(_(!0),xe(ts.title),K(ts.client_name||""),me(ts.property_address||""),Me(ts.sections||[]),Ie(ts.cta_type||"schedule_call"),Ve(ts.cta_label||"Schedule a Call"),$e(ts.cta_url||""),Qe(ts.heading||""),Ce(ts.share_token),et(ts.status==="published"),Ge(ts.id),x("builder"),ts.contact_id){const{data:Xs}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",ts.contact_id).maybeSingle();Xs&&(R(Xs),Q(Xs.email||""),te(Xs.phone||""))}};k.useEffect(()=>{if(!r||b.length<1){C([]);return}const ht=setTimeout(async()=>{E(!0);const{data:Jt}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",r.id).or(`first_name.ilike.%${b}%,last_name.ilike.%${b}%,email.ilike.%${b}%`).limit(10);C(Jt||[]),E(!1)},300);return()=>clearTimeout(ht)},[b,r]);const ct=ht=>{R(ht),K(`${ht.first_name} ${ht.last_name||""}`.trim()),Q(ht.email||""),te(ht.phone||""),O(!1)},vt=async()=>{if(!B.trim()){he.error("Client name is required");return}const ht=B.trim().split(" "),Jt=ht[0],Ms=ht.slice(1).join(" ")||null,{data:ts,error:Xs}=await U.from("innercircle_contacts").insert({owner_user_id:r.id,first_name:Jt,last_name:Ms,email:Z||null,phone:W||null,lead_source:"Smart Presentation"}).select().single();if(Xs){he.error("Failed to create client");return}R(ts),he.success("Client created & saved to Agent OS"),x("template")},kt=ht=>{fe(ht);const Jt=(ht.sections||[]).map(Ms=>({...Ms,is_visible:!0,video_url:"",text:""}));if(Me(Jt),xe(ht.name+(B?` for ${B}`:"")),ht.cta_config){const Ms=ht.cta_config;Ie(Ms.type||"schedule_call"),Ve(Ms.label||"Schedule a Call")}x("builder")},St=()=>{Me([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),xe(B?`Presentation for ${B}`:"New Presentation"),x("builder")},Yt=(ht,Jt)=>{Me(Ms=>Ms.map((ts,Xs)=>Xs===ht?{...ts,...Jt}:ts))},es=ht=>{Yt(ht,{is_visible:!Ee[ht].is_visible})},zs=()=>{Me(ht=>[...ht,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},sr=ht=>{Me(Jt=>Jt.filter((Ms,ts)=>ts!==ht))},ms=async()=>{if(!je.trim()){he.error("Title is required");return}try{if(Se){const ht=await l.mutateAsync({id:Se,title:je,sections:Ee,client_name:B,property_address:ue||null,cta_type:Oe,cta_label:ze,cta_url:Le||null,heading:ve||null});he.success("Saved")}else{const ht=await i.mutateAsync({title:je,contact_id:(D==null?void 0:D.id)||void 0,client_name:B,property_address:ue||void 0,template_id:(de==null?void 0:de.id)||void 0,sections:Ee,cta_type:Oe,cta_label:ze,cta_url:Le||void 0,heading:ve||void 0});Ge(ht.id),Ce(ht.share_token),he.success("Presentation created!")}}catch(ht){console.error("Failed to save presentation:",ht);const Jt=(ht==null?void 0:ht.message)||(ht==null?void 0:ht.toString())||"Unknown error";he.error(`Failed to save: ${Jt}`)}},gt=async()=>{try{await ms();const ht=Se;if(ht){const Jt=await o.mutateAsync(ht);Ce(Jt.share_token),et(!0),x("share")}}catch(ht){console.error("Failed to publish presentation:",ht),he.error(`Failed to publish: ${(ht==null?void 0:ht.message)||"Unknown error"}`)}},Ut=We?`https://presentations.relevelup.com/${We}`:"";return e.jsx(ws,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(Aa,{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:[f==="client"&&"Who is this presentation for?",f==="template"&&"Choose a starting template",f==="builder"&&"Customize your presentation",f==="share"&&"Share with your client"]})]})]}),!y&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((ht,Jt)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:zt("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",f===ht?"bg-primary text-primary-foreground":Jt<["client","template","builder","share"].indexOf(f)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Jt<["client","template","builder","share"].indexOf(f)?e.jsx(la,{className:"h-4 w-4"}):Jt+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:ht}),Jt<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},ht))}),f==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{R(null),K(""),Q(""),te(""),O(!1),x("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(hn,{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(ci,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors shrink-0"})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:b,onChange:ht=>j(ht.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[A&&e.jsx(dr,{className:"h-12 w-full"}),N.map(ht=>e.jsxs("button",{onClick:()=>ct(ht),className:zt("w-full text-left p-3 rounded-lg border transition-colors",(D==null?void 0:D.id)===ht.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[ht.first_name," ",ht.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ht.email||ht.phone||"No contact info"})]},ht.id)),!b&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),b&&N.length===0&&!A&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),D&&e.jsxs(q,{onClick:()=>x("template"),className:"w-full gap-2",children:["Continue with ",D.first_name,e.jsx(ci,{className:"h-4 w-4"})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(xl,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ce,{className:"text-xs",children:"Name *"}),e.jsx(Ne,{value:B,onChange:ht=>{K(ht.target.value),O(!0),R(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Email"}),e.jsx(Ne,{value:Z,onChange:ht=>Q(ht.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Phone"}),e.jsx(Ne,{value:W,onChange:ht=>te(ht.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Client Type"}),e.jsxs(Ds,{value:ne,onValueChange:ae,children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"buyer",children:"Buyer"}),e.jsx(lt,{value:"seller",children:"Seller"}),e.jsx(lt,{value:"recruit",children:"Recruit"}),e.jsx(lt,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Property Address"}),e.jsx(Ne,{value:ue,onChange:ht=>me(ht.target.value),placeholder:"Optional"})]})]}),F&&B&&e.jsxs(q,{onClick:vt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(ci,{className:"h-4 w-4"})]})]})]})]})]}),f==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ta,{defaultValue:"system",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"mine",children:"My Core Templates"}),e.jsx(rs,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(rs,{value:"blank",children:"+ Start Blank"})]}),e.jsx(fs,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(ht=>e.jsx(dr,{className:"h-32"},ht))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.filter(ht=>!ht.is_system).length===0?e.jsx("p",{className:"text-muted-foreground col-span-2 text-center py-8",children:"You haven't saved any templates yet. Create a presentation and save it as a template!"}):n.filter(ht=>!ht.is_system).map(ht=>e.jsx(cYe,{template:ht,onSelect:kt},ht.id))})}),e.jsx(fs,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.filter(ht=>ht.is_system).map(ht=>e.jsx(cYe,{template:ht,onSelect:kt},ht.id))})}),e.jsx(fs,{value:"blank",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start with a blank canvas and add your own sections."}),e.jsx(q,{onClick:St,children:"Start from Scratch"})]})})})]}),e.jsxs(q,{variant:"outline",onClick:()=>x("client"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back"]})]}),f==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Presentation Title"}),e.jsx(Ne,{value:je,onChange:ht=>xe(ht.target.value)})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Page Heading"}),e.jsx(Ne,{value:ve,onChange:ht=>Qe(ht.target.value),placeholder:B?`Welcome, ${B}!`:"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(ce,{children:"Client Name"}),e.jsx(Ne,{value:B,onChange:ht=>K(ht.target.value)})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Property Address"}),e.jsx(Ne,{value:ue,onChange:ht=>me(ht.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(q,{variant:"outline",size:"sm",onClick:zs,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:Ee.map((ht,Jt)=>e.jsx(ke,{className:zt(!ht.is_visible&&"opacity-50"),children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 pt-1",children:[e.jsx(Vu,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:ht.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ne,{value:ht.title,onChange:Ms=>Yt(Jt,{title:Ms.target.value}),className:"font-semibold border-none p-0 h-auto text-base focus-visible:ring-0 bg-transparent"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>es(Jt),children:ht.is_visible?e.jsx(Nn,{className:"h-4 w-4"}):e.jsx(Wf,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>sr(Jt),className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})]})]}),e.jsx(Ne,{value:ht.description||"",onChange:Ms=>Yt(Jt,{description:Ms.target.value}),placeholder:"Section description...",className:"text-sm"}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ce,{className:"text-xs",children:"Video URL"}),e.jsx(Ne,{value:ht.video_url||"",onChange:Ms=>Yt(Jt,{video_url:Ms.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(fYs,{sectionTitle:ht.title,contactId:D==null?void 0:D.id,onVideoReady:Ms=>Yt(Jt,{video_url:Ms})}),e.jsx(pYs,{sectionTitle:ht.title,contactId:D==null?void 0:D.id,onVideoReady:Ms=>Yt(Jt,{video_url:Ms})}),e.jsx(cM,{userId:r==null?void 0:r.id,onSelect:Ms=>Yt(Jt,{video_url:Ms})})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),ht.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:ht.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(q,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>Yt(Jt,{image_url:""}),children:e.jsx($r,{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:[we===Jt?e.jsx(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Qy,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:we===Jt?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:we===Jt,onChange:Ms=>{var Xs;const ts=(Xs=Ms.target.files)==null?void 0:Xs[0];ts&&Ze(ts,Jt),Ms.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Text (optional)"}),e.jsx(V1,{content:ht.text||"",onChange:Ms=>Yt(Jt,{text:Ms}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Jt))})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Call to Action"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"CTA Type"}),e.jsxs(Ds,{value:Oe,onValueChange:ht=>{Ie(ht);const Jt=oYe.find(Ms=>Ms.value===ht);Jt&&Ve(Jt.label)},children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:oYe.map(ht=>e.jsx(lt,{value:ht.value,children:ht.label},ht.value))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Button Label"}),e.jsx(Ne,{value:ze,onChange:ht=>Ve(ht.target.value)})]}),e.jsxs("div",{children:[e.jsxs(ce,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(Ne,{value:Le,onChange:ht=>$e(ht.target.value),placeholder:"https://calendly.com/..."}),!Le&&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(q,{variant:"outline",onClick:()=>x("template"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(q,{variant:"outline",onClick:ms,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(q,{onClick:gt,disabled:o.isPending,className:"gap-2",children:[e.jsx(hn,{className:"h-4 w-4"}),qe?"Update & Reshare":"Publish & Share"]})]})]})]}),f==="share"&&We&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4",children:e.jsx(la,{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 ",B||"your client",". You'll be notified when they view it."]}),e.jsxs("div",{className:"flex items-center gap-2 w-full max-w-lg",children:[e.jsx(Ne,{value:Ut,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(q,{onClick:()=>{navigator.clipboard.writeText(Ut),he.success("Link copied!")},children:e.jsx(si,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(q,{variant:"outline",className:"gap-2",onClick:()=>{const ht=`Hi ${B||""}! I put together something for you — check it out: ${Ut}`;navigator.clipboard.writeText(ht),he.success("Message copied!")},children:[e.jsx(Ui,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(q,{variant:"outline",className:"gap-2",onClick:()=>{c?m(!0):window.open(`mailto:${Z||""}?subject=${encodeURIComponent(je)}&body=${encodeURIComponent(`Hi ${(D==null?void 0:D.first_name)||(B==null?void 0:B.split(" ")[0])||""}, I put together a personalized presentation for you: ${Ut} Looking forward to connecting!`)}`)},children:[e.jsx(Ks,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(uw,{open:u,onOpenChange:m,contact:D?{id:D.id,first_name:D.first_name,last_name:D.last_name,email:Z||D.email||""}:Z?{id:"",first_name:(B==null?void 0:B.split(" ")[0])||"",last_name:(B==null?void 0:B.split(" ").slice(1).join(" "))||"",email:Z}:void 0,defaultSubject:je,defaultBody:`Hi ${(D==null?void 0:D.first_name)||(B==null?void 0:B.split(" ")[0])||""}, I put together a personalized presentation for you: ${Ut} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(q,{variant:"outline",onClick:()=>x("builder"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(q,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},cYe=({template:s,onSelect:t})=>e.jsx(ke,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Pe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:s.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold",children:s.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:s.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Xe,{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(q,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),xYs=()=>{var _;const{shareToken:s}=xo(),[t,r]=k.useState(null),[n,a]=k.useState(!0),[i,l]=k.useState(0),[o,c]=k.useState(!1);k.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),k.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:b,error:j}=await U.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(j||!b){c(!0),a(!1);return}const{data:N}=await U.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",b.owner_user_id).single();let C;if(N!=null&&N.brokerage_id){const{data:E}=await U.from("brokerages").select("name").eq("id",N.brokerage_id).single();C=(E==null?void 0:E.name)||void 0}let A=null;if(b.contact_id){const{data:E}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",b.contact_id).single();A=E}r({...b,owner_name:N==null?void 0:N.name,owner_email:N==null?void 0:N.email,owner_phone:N==null?void 0:N.phone,owner_avatar:N==null?void 0:N.avatar_url,owner_title:(N==null?void 0:N.title)||void 0,brokerage_name:C,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 U.rpc("log_presentation_view",{p_presentation_id:b.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await U.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(n)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(dr,{className:"h-12 w-3/4 mx-auto"}),e.jsx(dr,{className:"h-64 w-full"}),e.jsx(dr,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const m=t.sections.filter(b=>b.is_visible!==!1),f=m[i],x=b=>{const j=b.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(j)return`https://www.youtube.com/embed/${j[1]}?rel=0`;if(b.includes("iframe.mediadelivery.net/play/")){const A=b.replace("/play/","/embed/"),E=A.includes("?")?"&":"?";return`${A}${E}responsive=true`}if(b.includes("iframe.mediadelivery.net")){if(b.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const E=b.includes("?")?"&":"?";return`${b}${E}responsive=true`}return""}const N=b.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(N)return`https://www.loom.com/embed/${N[1]}`;const C=b.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return C?`https://iframe.mediadelivery.net/embed/${C[1]}/${C[2]}?responsive=true`:b},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:[f!=null&&f.video_url&&x(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:x(f.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):f!=null&&f.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:f.image_url,alt:f.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:f==null?void 0:f.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:f==null?void 0:f.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:f==null?void 0:f.description})]}),(f==null?void 0:f.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:f.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((b,j)=>e.jsx("button",{onClick:()=>l(j),className:zt("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:b.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:b.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:b.description})]})]})},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(q,{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(un,{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(Xnt,{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 gYs({openHouseId:s,enableSurvey:t,onToggleSurvey:r}){const{data:n,isLoading:a}=vRt(s),i=jRt(),l=NRt(),o=kRt(),c=SRt(),[d,u]=k.useState(""),[m,f]=k.useState("rating"),x=async j=>{r(j),j&&(!n||n.length===0)&&await c.mutateAsync(s)},y=async()=>{if(!d.trim())return;const j=(n==null?void 0:n.reduce((N,C)=>Math.max(N,C.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:m,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})},b=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(ce,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(k1,{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(Rr,{checked:t,onCheckedChange:x})]}),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(ls,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:n==null?void 0:n.map(j=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Vu,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:j.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:j.question_type.replace("_"," ")})]}),e.jsx(Rr,{checked:j.is_active,onCheckedChange:()=>_(j),className:"scale-75"}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>b(j),children:e.jsx(zr,{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(ce,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(Ne,{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(Ds,{value:m,onValueChange:f,children:[e.jsx(Ps,{className:"w-28 h-9 text-xs",children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"rating",children:"Rating"}),e.jsx(lt,{value:"open_text",children:"Text"})]})]}),e.jsx(q,{size:"sm",variant:"outline",onClick:y,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(Ys,{className:"h-3.5 w-3.5"})})]})]})})]})}function yYs({openHouseId:s}){const{user:t}=Cs(),{data:r=[],isLoading:n}=ARt(s),a=IRt(),[i,l]=k.useState(""),[o,c]=k.useState(!1),d=async()=>{const u=i.trim();if(u){c(!0);try{await a.mutateAsync({open_house_id:s,name:u,sort_order:r.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),n?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(ls,{className:"h-4 w-4 animate-spin inline"})," Loading…"]}):r.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No rooms yet — add your first below."}):e.jsx("div",{className:"space-y-3",children:r.map((u,m)=>e.jsx(vYs,{room:u,index:m,total:r.length,userId:(t==null?void 0:t.id)||"",openHouseId:s},u.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(Ne,{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(q,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function vYs({room:s,index:t,total:r,userId:n,openHouseId:a}){const i=PRt(),l=LRt(),o=DRt(),c=RRt(),d=k.useRef(null),[u,m]=k.useState(!0),[f,x]=k.useState(s.name),[y,_]=k.useState(s.description||""),[b,j]=k.useState(!1),N=k.useMemo(()=>s.media.filter(O=>O.kind==="video"&&O.agent_video_id).map(O=>O.agent_video_id),[s.media]),{data:C={}}=pt({queryKey:["room-video-statuses",s.id,N.join(",")],enabled:N.length>0,queryFn:async()=>{const{data:O,error:B}=await U.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",N);if(B)throw B;const K=O||[],Z=K.filter(W=>W.status==="processing"&&W.bunny_video_id);await Promise.all(Z.map(async W=>{try{const{data:te}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:W.bunny_video_id,isAgentVideo:!0}});te&&te.status===4&&(await U.from("agent_videos").update({status:"ready",playback_url:te.directPlayUrl,thumbnail_url:te.thumbnailUrl,preview_url:te.previewUrl,duration_seconds:te.length||void 0,updated_at:new Date().toISOString()}).eq("id",W.id),W.status="ready",W.thumbnail_url=te.thumbnailUrl,W.preview_url=te.previewUrl)}catch{}}));const Q={};return K.forEach(W=>{Q[W.id]={status:W.status,thumbnail_url:W.thumbnail_url,preview_url:W.preview_url}}),Q},refetchInterval:O=>{const B=O.state.data;return B?Object.values(B).some(K=>K.status!=="ready"&&K.status!=="failed")?5e3:!1:5e3}}),A=()=>{f.trim()&&f!==s.name&&i.mutate({id:s.id,open_house_id:a,name:f.trim()})},E=()=>{y!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:y.trim()||null})},D=()=>{confirm(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},R=O=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+O})},F=async O=>{const B=Array.from(O.target.files||[]);if(!(!B.length||!n)){j(!0);try{for(const K of B){const Z=K.type.startsWith("video/"),Q=Z?500*1024*1024:15*1024*1024;if(K.size>Q){Dn({title:`${K.name} is too large`,description:Z?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(Z){try{const ue=`${s.name} – ${K.name.replace(/\.[^/.]+$/,"")}`,{data:me,error:de}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:ue,isAgentVideo:!0}});if(de||!me)throw new Error((de==null?void 0:de.message)||"Could not start upload");const{videoId:fe,libraryId:je}=me,{data:xe,error:Ee}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:fe,isAgentVideo:!0}});if(Ee||!xe)throw new Error((Ee==null?void 0:Ee.message)||"Could not get upload URL");await new Promise((Ve,Le)=>{const $e=new XMLHttpRequest;$e.addEventListener("load",()=>{$e.status>=200&&$e.status<300?Ve():Le(new Error(`Upload failed (${$e.status})`))}),$e.addEventListener("error",()=>Le(new Error("Upload failed"))),$e.open("PUT",xe.uploadUrl),$e.setRequestHeader("AccessKey",xe.apiKey),$e.send(K)});const Me=`https://iframe.mediadelivery.net/embed/${je}/${fe}`,Oe=K.size/(1024*1024),{data:Ie,error:ze}=await U.from("agent_videos").insert({owner_user_id:n,bunny_video_id:fe,playback_url:Me,file_size_mb:Oe,title:ue,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(ze)throw ze;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Me,sort_order:s.media.length,agent_video_id:Ie.id}),Dn({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(ue){Dn({title:"Video upload failed",description:(ue==null?void 0:ue.message)||"Try again",variant:"destructive"})}continue}const W=K.name.split(".").pop()||"jpg",te=`${n}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${W}`,{error:ne}=await U.storage.from("open-house-tour-media").upload(te,K,{upsert:!1,contentType:K.type});if(ne){Dn({title:"Upload failed",description:ne.message,variant:"destructive"});continue}const{data:ae}=U.storage.from("open-house-tour-media").getPublicUrl(te);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ae.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(Vu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>m(O=>!O),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(q,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(-1),disabled:t===0,children:e.jsx(pg,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(1),disabled:t===r-1,children:e.jsx(Co,{className:"h-4 w-4"})}),e.jsx(q,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:D,children:e.jsx(zr,{className:"h-4 w-4"})})]}),u&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(Ne,{value:f,onChange:O=>x(O.target.value),onBlur:A,placeholder:"Room name",className:"h-9"}),e.jsx(pr,{value:y,onChange:O=>_(O.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(O=>{const B=O.agent_video_id?C[O.agent_video_id]:void 0,K=B==null?void 0:B.status,Z=O.kind==="video"&&K&&K!=="ready"&&K!=="failed",Q=O.kind==="video"&&K==="failed",W=(B==null?void 0:B.thumbnail_url)||(B==null?void 0:B.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[O.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(O.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:O.url,className:"w-full h-full object-cover"}),!Z&&!Q&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(bn,{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(ls,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),Q&&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:O.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:O.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($r,{className:"h-3.5 w-3.5"})})]},O.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:F,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",size:"sm",onClick:()=>{var O;return(O=d.current)==null?void 0:O.click()},disabled:b,className:"flex-1",children:b?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(cM,{userId:n,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async O=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:O.playback_url||"",sort_order:s.media.length,agent_video_id:O.id}),Dn({title:"Video added to room"})}catch(B){Dn({title:"Failed to add video",description:B==null?void 0:B.message,variant:"destructive"})}}})]})]})]})}function bYs({open:s,onOpenChange:t,openHouse:r}){const n=Jnt(),{user:a}=Cs(),i=k.useRef(null),l=k.useRef(null),o=k.useRef(null),c=r.kind==="virtual",[d,u]=k.useState(r.auto_forward_to_card??!1),[m,f]=k.useState(r.disclosure_pdf_url??""),[x,y]=k.useState(r.enable_survey??!1),[_,b]=k.useState(r.ask_visitor_intent??!0),[j,N]=k.useState(r.ask_visitor_address??!1),[C,A]=k.useState(r.photo_url??""),[E,D]=k.useState(!1),[R,F]=k.useState(!1),[O,B]=k.useState(!1),[K,Z]=k.useState(r.hero_video_url??""),[Q,W]=k.useState(!1),[te,ne]=k.useState(r.price!=null?String(r.price):""),[ae,ue]=k.useState(r.beds!=null?String(r.beds):""),[me,de]=k.useState(r.baths!=null?String(r.baths):""),[fe,je]=k.useState(r.sqft!=null?String(r.sqft):""),[xe,Ee]=k.useState(r.enable_question??!0),[Me,Oe]=k.useState(r.enable_showing??!0),[Ie,ze]=k.useState(r.enable_disclosures??!0),[Ve,Le]=k.useState(r.enable_offer??!0),[$e,ve]=k.useState(r.brand_color_override??""),[Qe,we]=k.useState(r.property_description??""),nt=async et=>{var St;const Ze=(St=et.target.files)==null?void 0:St[0];if(!Ze||!a)return;if(Ze.size>200*1024*1024){Dn({title:"Video must be under 200MB",variant:"destructive"});return}if(!Ze.type.startsWith("video/")){Dn({title:"Please upload a video file",variant:"destructive"});return}W(!0);const rt=Ze.name.split(".").pop()||"mp4",ct=`${a.id}/${r.id}/hero-${Date.now()}.${rt}`,{error:vt}=await U.storage.from("open-house-tour-media").upload(ct,Ze,{upsert:!0,contentType:Ze.type});if(vt){Dn({title:"Upload failed",description:vt.message,variant:"destructive"}),W(!1);return}const{data:kt}=U.storage.from("open-house-tour-media").getPublicUrl(ct);Z(kt.publicUrl),W(!1),Dn({title:"Video uploaded!"})},Se=async et=>{var St;const Ze=(St=et.target.files)==null?void 0:St[0];if(!Ze||!a)return;if(Ze.size>10*1024*1024){Dn({title:"Image must be under 10MB",variant:"destructive"});return}if(!Ze.type.startsWith("image/")){Dn({title:"Please upload an image file",variant:"destructive"});return}F(!0);const rt=Ze.name.split(".").pop()||"jpg",ct=`${a.id}/${r.id}-${Date.now()}.${rt}`,{error:vt}=await U.storage.from("open-house-photos").upload(ct,Ze,{upsert:!0});if(vt){Dn({title:"Upload failed",description:vt.message,variant:"destructive"}),F(!1);return}const{data:kt}=U.storage.from("open-house-photos").getPublicUrl(ct);A(kt.publicUrl),F(!1),Dn({title:"Photo updated!"})},Ge=()=>{A(""),l.current&&(l.current.value="")},We=async et=>{var kt;const Ze=(kt=et.target.files)==null?void 0:kt[0];if(!Ze||!a)return;if(Ze.size>20*1024*1024){Dn({title:"File must be under 20MB",variant:"destructive"});return}if(Ze.type!=="application/pdf"){Dn({title:"Only PDF files are accepted",variant:"destructive"});return}D(!0);const rt=`${a.id}/disclosures/${r.id}-${Date.now()}.pdf`,{error:ct}=await U.storage.from("open-house-photos").upload(rt,Ze,{upsert:!0});if(ct){Dn({title:"Upload failed",description:ct.message,variant:"destructive"}),D(!1);return}const{data:vt}=U.storage.from("open-house-photos").getPublicUrl(rt);f(vt.publicUrl),D(!1),Dn({title:"PDF uploaded!"})},Ce=()=>{f(""),i.current&&(i.current.value="")},qe=async()=>{B(!0);try{const et={id:r.id,auto_forward_to_card:d,disclosure_pdf_url:m||null,enable_survey:x,ask_visitor_intent:_,ask_visitor_address:j,photo_url:C||null};c&&(et.hero_video_url=K||null,et.price=te.trim()?Number(te):null,et.beds=ae.trim()?parseInt(ae,10):null,et.baths=me.trim()?Number(me):null,et.sqft=fe.trim()?parseInt(fe,10):null,et.enable_question=xe,et.enable_showing=Me,et.enable_disclosures=Ie,et.enable_offer=Ve,et.brand_color_override=$e.trim()||null,et.property_description=Qe.trim()||null),await n.mutateAsync(et),Dn({title:"Settings saved!"}),t(!1)}catch{Dn({title:"Failed to save",variant:"destructive"})}finally{B(!1)}};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(an,{className:"truncate",children:r.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[c&&e.jsxs(e.Fragment,{children:[r.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(bn,{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:nt,className:"hidden"}),K?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:K,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(q,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var et;return(et=o.current)==null?void 0:et.click()},disabled:Q,children:Q?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(q,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>Z(""),children:e.jsx($r,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var et;return(et=o.current)==null?void 0:et.click()},disabled:Q,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:Q?e.jsx(ls,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(bn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(yYs,{openHouseId:r.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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(ce,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(Ne,{type:"number",value:te,onChange:et=>ne(et.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(Ne,{type:"number",value:fe,onChange:et=>je(et.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(Ne,{type:"number",value:ae,onChange:et=>ue(et.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(Ne,{type:"number",step:"0.5",value:me,onChange:et=>de(et.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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(pr,{value:Qe,onChange:et=>we(et.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(ce,{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(Rr,{checked:xe,onCheckedChange:Ee})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(Rr,{checked:Me,onCheckedChange:Oe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(Rr,{checked:Ie,onCheckedChange:ze})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(Rr,{checked:Ve,onCheckedChange:Le})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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:$e||"#0f172a",onChange:et=>ve(et.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(Ne,{value:$e,onChange:et=>ve(et.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),$e&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>ve(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(et=>e.jsx("button",{type:"button",onClick:()=>ve(et),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:et},"aria-label":et},et))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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:Se,className:"hidden"}),C?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:C,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(q,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var et;return(et=l.current)==null?void 0:et.click()},disabled:R,children:[R?e.jsx(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"}),R?"":"Replace"]}),e.jsx(q,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:Ge,children:e.jsx($r,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var et;return(et=l.current)==null?void 0:et.click()},disabled:R,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:R?e.jsx(ls,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(zo,{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(ce,{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(Rr,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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:We,className:"hidden"}),m?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(En,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:Ce,children:e.jsx($r,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var et;return(et=i.current)==null?void 0:et.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(ls,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{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(ce,{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(Rr,{checked:_,onCheckedChange:b})]})}),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(ce,{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(Rr,{checked:j,onCheckedChange:N})]})}),e.jsx(gYs,{openHouseId:r.id,enableSurvey:x,onToggleSurvey:y}),e.jsx(q,{onClick:qe,disabled:O,className:"w-full",children:O?"Saving...":"Save Settings"})]})]})})}const zbt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function _Ys({question:s,responses:t}){const r=t.filter(l=>l.question_id===s.id&&l.rating_value!=null),n=r.length;if(n===0)return null;const a=r.reduce((l,o)=>l+(o.rating_value||0),0)/n,i=[5,4,3,2,1].map(l=>({val:l,count:r.filter(o=>o.rating_value===l).length,pct:Math.round(r.filter(o=>o.rating_value===l).length/n*100)}));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:s.question_text}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[a.toFixed(1)," avg (",n," responses)"]})]}),e.jsx("div",{className:"space-y-1",children:i.map(l=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-16 text-muted-foreground text-right",children:zbt[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 wYs({openHouseId:s}){const{data:t,isLoading:r}=wRt(s),{data:n}=Qnt(s),a=k.useMemo(()=>{const m={};return n==null||n.forEach(f=>{m[f.id]=f}),m},[n]);if(r||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(m=>m.question_type==="rating"),c=i.filter(m=>m.question_type!=="rating"),d=[...new Set(l.map(m=>m.visitor_id))],u=d.length;return u===0?e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(k1,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(ke,{children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(k1,{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(Pe,{children:e.jsxs(ta,{defaultValue:"summary",children:[e.jsxs(ea,{className:"mb-4",children:[e.jsxs(rs,{value:"summary",className:"text-xs gap-1",children:[e.jsx(Mo,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(rs,{value:"individual",className:"text-xs gap-1",children:[e.jsx(qi,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(fs,{value:"summary",className:"space-y-6",children:[o.map(m=>e.jsx(_Ys,{question:m,responses:l},m.id)),c.map(m=>{const f=l.filter(x=>x.question_id===m.id&&x.text_value);return f.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:m.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:f.map(x=>{const y=a[x.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:x.text_value})]},x.id)})})]},m.id)})]}),e.jsx(fs,{value:"individual",className:"space-y-4",children:d.map(m=>{const f=a[m],x=l.filter(y=>y.visitor_id===m);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[f?`${f.first_name} ${f.last_name||""}`.trim():"Unknown Visitor",(f==null?void 0:f.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:f.email})]}),e.jsx("div",{className:"space-y-1",children:x.map(y=>{const _=i.find(b=>b.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?zbt[y.rating_value]||y.rating_value:y.text_value})]},y.id):null})})]},m)})})]})})]})}const jYs={question:{label:"Question",icon:Ui,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:vn,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:En,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:Xl,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},dYe={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 NYs({openHouseId:s}){const{data:t=[],isLoading:r}=ORt(s),n=FRt(),[a,i]=k.useState(null),[l,o]=k.useState("all"),c=t.filter(m=>l==="all"?!0:l==="new"?m.status==="new":m.action_type===l),d={all:t.length,new:t.filter(m=>m.status==="new").length,question:t.filter(m=>m.action_type==="question").length,showing:t.filter(m=>m.action_type==="showing").length,disclosure:t.filter(m=>m.action_type==="disclosure").length,offer:t.filter(m=>m.action_type==="offer").length},u=(m,f)=>{n.mutate({id:m,status:f,open_house_id:s})};return r?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loading leads…"}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/40 border-b flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(n2,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(Xe,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(Xe,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([m,f,x])=>e.jsxs("button",{onClick:()=>o(m),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===m?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[f," ",e.jsx("span",{className:"opacity-60",children:x})]},m))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(m=>{const f=jYs[m.action_type],x=f.icon,y=m.payload||{},_=a===m.id,b=m.status==="contacted",j=m.status==="archived";return e.jsxs("li",{className:`transition-colors ${j?"opacity-60":""} ${m.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(_?null:m.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${f.bg}`,children:e.jsx(x,{className:`h-4 w-4 ${f.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(Xe,{variant:"outline",className:`text-[10px] ${f.color}`,children:f.label}),m.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),b&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(qn,{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(jn,{className:"h-3 w-3"}),As(new Date(m.created_at),"MMM d, h:mm a")]}),y.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Ks,{className:"h-3 w-3"}),y.email]}),y.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"}),y.phone]})]})]}),_?e.jsx(Co,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(Ia,{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(dYe).some(N=>y[N]!=null&&y[N]!==""&&!(Array.isArray(y[N])&&y[N].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(dYe).map(([N,C])=>{const A=y[N];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:C}),e.jsx("div",{className:"font-medium",children:Array.isArray(A)?A.join(", "):String(A)})]},N)})}),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(q,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(Ks,{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(q,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Mn,{className:"h-3.5 w-3.5"}),"Call"]})}),!b&&e.jsxs(q,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(m.id,"contacted"),children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),j?e.jsx(q,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(m.id,"new"),children:"Restore"}):e.jsxs(q,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(m.id,"archived"),children:[e.jsx(Qk,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},m.id)})})]})}function kYs({open:s,onOpenChange:t,openHouse:r}){const{isGmailConnected:n,gmailEmail:a}=Cm(),i=xa(),[l,o]=k.useState([]),[c,d]=k.useState([]),[u,m]=k.useState(!1),[f,x]=k.useState(!1),[y,_]=k.useState(""),[b,j]=k.useState(""),[N,C]=k.useState(""),[A,E]=k.useState(!1),[D,R]=k.useState(!1),[F,O]=k.useState(!1),B=`https://guestbook.relevelup.com/${r.slug}`;k.useEffect(()=>{s&&(j(`Take a virtual tour of ${r.property_address}`),C(`I wanted to share an immersive virtual tour of ${r.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),d([]),_(""),E(n),l.length===0&&K())},[s,r.id,n]);const K=async()=>{if(i){x(!0);try{const{data:me,error:de}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).limit(1e3);if(de)throw de;o(me||[])}catch{he.error("Failed to load contacts")}finally{x(!1)}}},Z=me=>`${me.first_name} ${me.last_name||""}`.trim(),Q=me=>{d(de=>de.find(fe=>fe.id===me.id)?de.filter(fe=>fe.id!==me.id):[...de,me])},W=()=>{const me=y.trim();if(!me)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(me)){he.error("Invalid email");return}d(fe=>[...fe,{id:`manual-${me}`,first_name:me.split("@")[0],last_name:null,email:me}]),_("")},te=k.useMemo(()=>c.filter(me=>!!me.email).map(me=>({email:me.email,name:Z(me)})),[c]),ne=me=>{const de=me?`Hi ${me},`:"Hi there,",fe=N.split(/\n\n+/).map(je=>`

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

`).join("");return`

${de}

${fe}

▶ Start Virtual Tour

Or copy this link: ${B}

`},ae=async()=>{var me;if(te.length===0){he.error("Add at least one recipient");return}R(!0);try{if(A&&n){let de=0;for(const fe of te){const{data:je,error:xe}=await U.functions.invoke("gmail-send",{body:{to:fe.email,subject:b,body:ne((me=fe.name)==null?void 0:me.split(" ")[0])}});!xe&&(je!=null&&je.success)?de+=1:console.warn("gmail-send error",xe,je)}if(de===0)throw new Error("Gmail send failed");he.success(`Sent to ${de} of ${te.length} via Gmail`)}else{const{data:de,error:fe}=await U.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:r.id,recipients:te,subject:b,personalMessage:N}});if(fe)throw fe;if(!(de!=null&&de.success))throw new Error((de==null?void 0:de.error)||"Send failed");he.success(`Sent to ${de.sent} of ${de.total} recipient${de.total===1?"":"s"}`)}t(!1)}catch(de){he.error((de==null?void 0:de.message)||"Failed to send")}finally{R(!1)}},ue=async()=>{await navigator.clipboard.writeText(B),O(!0),setTimeout(()=>O(!1),1500)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(_s,{className:"min-w-0",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ks,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(an,{className:"truncate",children:r.property_address})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 flex items-center gap-2 min-w-0",children:[e.jsx(tl,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:B}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:ue,className:"shrink-0 h-7 gap-1",children:[F?e.jsx(la,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(si,{className:"h-3.5 w-3.5"}),F?"Copied":"Copy"]})]}),n&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(q,{type:"button",variant:A?"default":"outline",size:"sm",onClick:()=>E(!0),className:"gap-1.5",children:[e.jsx(Ks,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(q,{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(ce,{className:"flex items-center gap-1.5",children:[e.jsx(Dr,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(sl,{open:u,onOpenChange:m,modal:!0,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(q,{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(xg,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Ko,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(jg,{children:[e.jsx(Ng,{placeholder:"Search contacts..."}),e.jsxs(kg,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(Sg,{children:f?"Loading...":"No contacts found."}),e.jsx(Cg,{children:l.map(me=>{const de=!!c.find(xe=>xe.id===me.id),fe=Z(me).slice(0,80),je=(me.email||"").slice(0,80);return e.jsxs(Sp,{value:`${fe} ${je}`,onSelect:()=>Q(me),className:"py-2",children:[e.jsx(la,{className:zt("mr-2 h-4 w-4 shrink-0",de?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:fe||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:je})]})]},me.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(me=>e.jsxs(Xe,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:Z(me)}),e.jsx("button",{onClick:()=>Q(me),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx($r,{className:"h-3 w-3"})})]},me.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(Ne,{value:y,onChange:me=>_(me.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),W())}}),e.jsx(q,{type:"button",variant:"outline",size:"sm",onClick:W,children:"Add"})]})]}),e.jsx(cl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(Ne,{id:"vt-subject",value:b,onChange:me=>j(me.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(pr,{id:"vt-message",value:N,onChange:me=>C(me.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(q,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsxs(q,{onClick:ae,disabled:D||te.length===0||!b.trim(),className:"gap-2",children:[D?e.jsx(ls,{className:"h-4 w-4 animate-spin"}):e.jsx(hn,{className:"h-4 w-4"}),D?"Sending...":`Send${te.length?` to ${te.length}`:""}`]})]})]})]})})}const UCe="guestbook.relevelup.com";function SYs(){const{data:s,isLoading:t}=pRt(),r=xRt(),n=Jnt(),a=gRt(),[i,l]=k.useState(!1),[o,c]=k.useState(null),{user:d}=Cs(),u=xa(),[m,f]=k.useState(null),[x,y]=k.useState(null),[_,b]=k.useState(!1),j=k.useRef(null),[N,C]=k.useState({property_address:"",city:"",state:"",zip:"",event_date:As(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=F=>{var B;const O=(B=F.target.files)==null?void 0:B[0];if(O){if(O.size>5*1024*1024){Dn({title:"Photo must be under 5MB",variant:"destructive"});return}f(O),y(URL.createObjectURL(O))}},E=()=>{f(null),y(null),j.current&&(j.current.value="")},D=async()=>{if(!N.property_address){Dn({title:N.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let F;if(m&&d){b(!0);const B=m.name.split(".").pop(),K=`${u}/${Date.now()}.${B}`,{error:Z}=await U.storage.from("open-house-photos").upload(K,m,{upsert:!0});if(Z){Dn({title:"Photo upload failed",description:Z.message,variant:"destructive"}),b(!1);return}const{data:Q}=U.storage.from("open-house-photos").getPublicUrl(K);F=Q.publicUrl,b(!1)}const O=N.kind==="virtual"?{...N,start_time:void 0,end_time:void 0,photo_url:F}:{...N,photo_url:F};await r.mutateAsync(O),l(!1),C({property_address:"",city:"",state:"",zip:"",event_date:As(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()},R=F=>{navigator.clipboard.writeText(`https://${UCe}/${F}`),Dn({title:"Link copied!"})};return e.jsxs(ws,{title:"Guest Book",children:[e.jsx(Yo,{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(vs,{open:i,onOpenChange:l,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"New Open House"]})}),e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Create Open House"}),e.jsx(an,{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(ce,{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:()=>C(F=>({...F,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${N.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:()=>C(F=>({...F,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${N.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"})]})]})]}),N.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:()=>C(F=>({...F,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${N.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:()=>C(F=>({...F,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${N.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),N.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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:()=>C(F=>({...F,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${N.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:()=>C(F=>({...F,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${N.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(ce,{children:N.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(Ne,{value:N.property_address,onChange:F=>C(O=>({...O,property_address:F.target.value})),placeholder:N.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(ce,{children:"City"}),e.jsx(Ne,{value:N.city,onChange:F=>C(O=>({...O,city:F.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"State"}),e.jsx(Ne,{value:N.state,onChange:F=>C(O=>({...O,state:F.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"ZIP"}),e.jsx(Ne,{value:N.zip,onChange:F=>C(O=>({...O,zip:F.target.value})),placeholder:"78701"})]})]}),N.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(ce,{children:"Date"}),e.jsx(Ne,{type:"date",value:N.event_date,onChange:F=>C(O=>({...O,event_date:F.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Start Time"}),e.jsx(Ne,{type:"time",value:N.start_time,onChange:F=>C(O=>({...O,start_time:F.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"End Time"}),e.jsx(Ne,{type:"time",value:N.end_time,onChange:F=>C(O=>({...O,end_time:F.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Welcome Message"}),e.jsx(pr,{value:N.agent_greeting,onChange:F=>C(O=>({...O,agent_greeting:F.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(ce,{children:N.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:j,type:"file",accept:"image/*",onChange:A,className:"hidden"}),x?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:x,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($r,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var F;return(F=j.current)==null?void 0:F.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(Qy,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",N.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(q,{onClick:D,disabled:r.isPending||_,className:"w-full",children:_?"Uploading photo...":r.isPending?"Creating...":N.kind==="virtual"?"Create Virtual Open House":N.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(F=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Pt,{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"})]})},F))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map(F=>e.jsx(CYs,{openHouse:F,isExpanded:o===F.id,onToggle:()=>c(o===F.id?null:F.id),onCopyLink:()=>R(F.slug||""),onToggleActive:()=>n.mutate({id:F.id,is_active:!F.is_active}),onDelete:()=>a.mutate(F.id)},F.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(S_,{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(q,{onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function CYs({openHouse:s,isExpanded:t,onToggle:r,onCopyLink:n,onToggleActive:a,onDelete:i}){const{data:l}=Qnt(t?s.id:void 0),{data:o}=pt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:R,error:F}=await U.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(F)throw F;const O=R.brokerages;return{...R,brokerage_name:(O==null?void 0:O.name)||null}},enabled:!!s.agent_id}),[c,d]=k.useState(!1),[u,m]=k.useState(!1),[f,x]=k.useState(!1),[y,_]=k.useState(!1),b=k.useRef(null),j=`https://${UCe}/${s.slug}`,N=R=>{if(!R)return"";const[F,O]=R.split(":"),B=parseInt(F),K=B>=12?"PM":"AM";return`${B>12?B-12:B||12}:${O} ${K}`},C=()=>{if(!(l!=null&&l.length))return;const R=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],F=l.map(Q=>[Q.first_name,Q.last_name||"",Q.email||"",Q.phone||"",Q.visitor_address||"",Q.visitor_intent||"",Q.wants_market_updates?"Yes":"No",(Q.message||"").replace(/"/g,'""'),As(new Date(Q.created_at),"MM/dd/yyyy h:mm a")]),O=[R,...F].map(Q=>Q.map(W=>`"${W}"`).join(",")).join(` `),B=new Blob([O],{type:"text/csv"}),K=URL.createObjectURL(B),Z=document.createElement("a");Z.href=K,Z.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,Z.click(),URL.revokeObjectURL(K)},A=k.useCallback(()=>{if(!b.current)return;const R=b.current.querySelector("svg");if(!R)return;const F=new XMLSerializer().serializeToString(R),O=document.createElement("canvas");O.width=1024,O.height=1024;const B=O.getContext("2d"),K=new Image;K.onload=()=>{B==null||B.drawImage(K,0,0,1024,1024);const Z=document.createElement("a");Z.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,Z.href=O.toDataURL("image/png"),Z.click()},K.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(F)))},[s.property_address]),E=k.useCallback(()=>{var we;if(!b.current)return;const R=b.current.querySelector("svg");if(!R)return;const F=new XMLSerializer().serializeToString(R),O="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(F))),B=As(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),K=s.start_time?`${N(s.start_time)}${s.end_time?" – "+N(s.end_time):""}`:"",Z=[s.city,s.state].filter(Boolean).join(", "),Q=s.agent_greeting||"Welcome! Please sign in below.",W=!!s.photo_url,te=!!o,ne=W||te,ae=W&&te,ue=ae?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",me=ae?"28px":"34px",de=ae?"0.2in 0.75in":ne?"0.3in 0.75in":"0.4in 0.75in",fe=ne?"0.15in":"0.3in",je=ne?"0.15in":"0.3in",xe=ae?"14px 36px":"22px 44px",Ee=ae?"20px":"24px",Me=ne?"0.2in":"0.35in",Oe=ae?"1.8in":"2.4in",Ie=ne?"0.15in":"0.3in",ze=ae?"140px":ne?"160px":"200px",Ve=ae?"16px":"24px",Le=ae?"10px 20px":"16px 28px",$e=ae?"44px":"56px",ve="0.15in",Qe=window.open("","_blank");Qe&&(Qe.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
${B}
${K?`
Time
${K}
`:""}
${Q}
${o?`
${o.avatar_url?`${o.name}`:`
${((we=o.name)==null?void 0:we.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
`),Qe.document.close(),setTimeout(()=>{Qe.focus(),Qe.print()},500))},[s,j,o]),D=async()=>{_(!0);try{const{error:R}=await U.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(R)throw R;Dn({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(R){Dn({title:"Failed to send",description:R.message,variant:"destructive"})}finally{_(!1)}};return e.jsxs(ke,{className:`transition-all ${s.is_active?"border-primary/30":"opacity-75"}`,children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Dt,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[e.jsx(Xe,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(Xe,{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(Nn,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(Xe,{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(Ma,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(Xe,{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(qi,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(Xe,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Ga,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(q,{variant:"ghost",size:"icon",onClick:r,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(pg,{className:"h-4 w-4"}):e.jsx(Co,{className:"h-4 w-4"})})]}),e.jsxs(Ur,{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(Ma,{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(jn,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vn,{className:"h-3 w-3"}),As(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(jn,{className:"h-3 w-3"}),N(s.start_time),s.end_time?` – ${N(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(Dr,{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(S_,{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(q,{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(h2,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:n,title:"Copy link",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(si,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>x(!0),title:"Share tour via email",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(Ec,{className:"h-3.5 w-3.5"}),"Share"]}),s.kind==="virtual"&&e.jsxs(q,{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(Nn,{className:"h-3.5 w-3.5"}),"Preview Tour"]}),e.jsxs(q,{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(S_,{className:"h-3.5 w-3.5"}),"QR"]}),s.kind!=="virtual"&&e.jsxs(q,{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(lP,{className:"h-3.5 w-3.5"}),"Tablet"]}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>m(!0),title:"Settings",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(Bo,{className:"h-3.5 w-3.5"})}),e.jsx(q,{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(un,{className:"h-3.5 w-3.5"})}),e.jsx(q,{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(Wf,{className:"h-3.5 w-3.5"}):e.jsx(Nn,{className:"h-3.5 w-3.5"})}),e.jsx(q,{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(zr,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(Pe,{className:"pt-0",children:[e.jsx(cl,{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://",UCe,"/",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(q,{variant:"outline",size:"sm",onClick:C,className:"h-7 text-xs gap-1",children:[e.jsx(li,{className:"h-3 w-3"}),"Export CSV"]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/30 text-xs text-muted-foreground",children:[e.jsx("th",{className:"text-left p-2 font-medium",children:"Name"}),e.jsx("th",{className:"text-left p-2 font-medium hidden sm:table-cell",children:"Contact"}),e.jsx("th",{className:"text-left p-2 font-medium hidden md:table-cell",children:"Intent"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Time"})]})}),e.jsx("tbody",{children:l.map(R=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[R.first_name,R.last_name?` ${R.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[R.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:R.email}),R.phone&&e.jsx("div",{className:"text-xs",children:R.phone}),R.visitor_address&&e.jsx("div",{className:"text-xs truncate max-w-[180px]",children:R.visitor_address})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:R.visitor_intent?e.jsx(Xe,{variant:"outline",className:"text-xs capitalize",children:R.visitor_intent}):R.partial_signin?e.jsx(Xe,{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:As(new Date(R.created_at),"h:mm a")})]},R.id))})]})})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No visitors yet. Share the link to start collecting sign-ins!"}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(NYs,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(wYs,{openHouseId:s.id})})]}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{className:"sm:max-w-sm",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"QR Code"}),e.jsx(an,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:b,className:"bg-white p-4 rounded-xl",children:e.jsx(d$,{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(q,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(li,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(q,{variant:"outline",className:"flex-1",onClick:E,children:[e.jsx(UF,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(q,{variant:"default",className:"w-full",onClick:D,disabled:y,children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),y?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(bYs,{open:u,onOpenChange:m,openHouse:s}),s.kind==="virtual"&&e.jsx(kYs,{open:f,onOpenChange:x,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function TYs(){const{slug:s}=xo();return s?e.jsx(vlt,{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 Bbt({photoUrl:s,videoUrl:t,onPhotoChange:r,onVideoChange:n,contactId:a}){const{user:i}=Cs(),l=V2(),o=k.useRef(null),c=k.useRef(null),[d,u]=k.useState(!1),[m,f]=k.useState(!1),[x,y]=k.useState(0),_=async j=>{if(i){u(!0);try{const N=j.name.split(".").pop()||"jpg",C=`${i.id}/card-${Date.now()}.${N}`,{error:A}=await U.storage.from("listing-photos").upload(C,j);if(A)throw A;const{data:{publicUrl:E}}=U.storage.from("listing-photos").getPublicUrl(C);r(E),he.success("Photo uploaded")}catch(N){he.error(N.message||"Failed to upload photo")}finally{u(!1)}}},b=async j=>{if(i){if(j.size>500*1024*1024){he.error("Video must be under 500MB");return}f(!0),y(0);try{const{videoId:N,libraryId:C}=await dM(`Card Video - ${Date.now()}`),{uploadUrl:A,apiKey:E}=await uM(N);await new Promise((F,O)=>{const B=new XMLHttpRequest;B.upload.addEventListener("progress",K=>{K.lengthComputable&&y(Math.round(K.loaded/K.total*100))}),B.addEventListener("load",()=>{B.status>=200&&B.status<300?F():O(new Error("Upload failed"))}),B.addEventListener("error",()=>O(new Error("Upload failed"))),B.open("PUT",A),B.setRequestHeader("AccessKey",E),B.send(j)});const D=`https://iframe.mediadelivery.net/embed/${C}/${N}`;n(D);const R=parseFloat((j.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:N,playback_url:`https://iframe.mediadelivery.net/play/${C}/${N}`,file_size_mb:R,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),he.success("Video uploaded & added to your library")}catch(N){he.error(N.message||"Failed to upload video")}finally{f(!1),y(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(ce,{children:"Media (optional)"}),e.jsxs(ta,{defaultValue:"photo",className:"w-full",children:[e.jsxs(ea,{className:"grid w-full grid-cols-2",children:[e.jsxs(rs,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(zo,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(rs,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(fs,{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(q,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx($r,{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(ls,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Tp,{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 C;const N=(C=j.target.files)==null?void 0:C[0];N&&_(N),j.target.value=""}})]}),e.jsxs(fs,{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(q,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx($r,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=c.current)==null?void 0:j.click()},disabled:m,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:m?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(ls,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",x,"%"]}),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:`${x}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ka,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a video (max 500MB)"})]})}),!t&&!m&&e.jsx("div",{className:"mt-2",children:e.jsx(dIe,{contactId:a,onVideoReady:j=>n(j)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:j=>{var C;const N=(C=j.target.files)==null?void 0:C[0];N&&b(N),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 EYs=[{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 AYs({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:EYs.map((t,r)=>e.jsxs(Zr.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:r*.04,duration:.25},onClick:()=>s(t.type),className:`group relative flex flex-col items-start gap-1 p-3.5 rounded-xl border bg-gradient-to-br ${t.gradient} hover:shadow-md hover:scale-[1.02] active:scale-[0.98] transition-all text-left`,children:[e.jsx("span",{className:"text-2xl",children:t.emoji}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:t.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight",children:t.description})]},t.type))})}const gD={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 uYe({initialOpen:s,initialCardType:t,initialContactId:r,initialRecipientName:n,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=Cs(),c=is(),[d,u]=k.useState(!1),[m,f]=k.useState("type"),[x,y]=k.useState(""),[_,b]=k.useState(null),[j,N]=k.useState(!1),[C,A]=k.useState("home_anniversary"),[E,D]=k.useState(""),[R,F]=k.useState(""),[O,B]=k.useState(""),[K,Z]=k.useState(""),[Q,W]=k.useState("elegant"),[te,ne]=k.useState(null),[ae,ue]=k.useState(null),me=k.useState(!1);!me[0]&&s&&t&&(me[1](!0),u(!0),A(t),r&&b(r),n&&D(n),a&&F(a),i&&B(i),f(n?"details":"contact"));const{data:de}=pt({queryKey:["contacts-for-card",o==null?void 0:o.id,x],queryFn:async()=>{let $e=U.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, wedding_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);x&&($e=$e.or(`first_name.ilike.%${x}%,last_name.ilike.%${x}%`));const{data:ve,error:Qe}=await $e;if(Qe)throw Qe;return ve},enabled:!!(o!=null&&o.id)&&d}),{data:fe}=pt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:$e,error:ve}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(ve)throw ve;return $e},enabled:!!(o!=null&&o.id)}),je=$e=>{b($e.id),D(`${$e.first_name}${$e.last_name?" "+$e.last_name:""}`),F([$e.address,$e.city,$e.state].filter(Boolean).join(", "));const ve=C==="wedding_anniversary"?$e.wedding_anniversary:C==="home_anniversary"?$e.home_anniversary:"";B(ve||""),f("details")},xe=$e=>{A($e),f("contact")},Ee=async()=>{var $e;if(!(!o||!fe)){N(!0);try{const ve={owner_user_id:o.id,contact_id:_,card_type:C,template:Q,recipient_name:E,property_address:R||null,home_anniversary_date:O||null,custom_message:K||null,property_photo_url:te||null,video_url:ae||null,agent_name:fe.name||"Agent",agent_photo_url:fe.avatar_url,agent_phone:fe.phone,agent_email:fe.email,agent_brokerage:(($e=fe.brokerage)==null?void 0:$e.name)||null},{error:Qe}=await U.from("sendable_cards").insert(ve);if(Qe)throw Qe;he.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),Me()}catch(ve){he.error(ve.message||"Failed to create card")}finally{N(!1)}}},Me=()=>{u(!1),f("type"),A("home_anniversary"),y(""),b(null),D(""),F(""),B(""),Z(""),W("elegant"),ne(null),ue(null)},Oe={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"},Ie=gD[C],ze=C==="home_anniversary"||C==="wedding_anniversary",Ve=C==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",Le=["home_anniversary","just_listed","just_sold"].includes(C);return e.jsxs(vs,{open:d,onOpenChange:$e=>{$e?u(!0):(Me(),l==null||l(!1))},children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{className:"gap-2",children:[e.jsx(Ys,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:m==="type"?"What type of card?":m==="contact"?`${Oe[C]} — Choose a Contact`:`${Oe[C]} — Customize`})}),m==="type"&&e.jsx(AYs,{onSelect:xe}),m==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(q,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>f("type"),children:[e.jsx(Aa,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search contacts...",value:x,onChange:$e=>y($e.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[de==null?void 0:de.map($e=>e.jsxs("button",{onClick:()=>je($e),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(qi,{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:[$e.first_name," ",$e.last_name]}),$e.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(Pn,{className:"h-3 w-3"}),$e.address]})]}),(C==="home_anniversary"&&$e.home_anniversary||C==="wedding_anniversary"&&$e.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"})]},$e.id)),(de==null?void 0:de.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(q,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{f("details")},children:"Skip — enter details manually"})})]}),m==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(q,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>f("contact"),children:[e.jsx(Aa,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Recipient Name"}),e.jsx(Ne,{value:E,onChange:$e=>D($e.target.value),placeholder:"John & Jane Smith"})]}),Le&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Property Address"}),e.jsx(Ne,{value:R,onChange:$e=>F($e.target.value),placeholder:"123 Main St, Austin, TX"})]}),ze&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:Ve}),e.jsx(Ne,{type:"date",value:O,onChange:$e=>B($e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Personal Message (optional)"}),e.jsx(pr,{value:K,onChange:$e=>Z($e.target.value),placeholder:Ie.defaultMessage,rows:3})]}),e.jsx(Bbt,{photoUrl:te,videoUrl:ae,onPhotoChange:ne,onVideoChange:ue,contactId:_}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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:$e,label:ve,gradient:Qe})=>e.jsxs("button",{onClick:()=>W($e),className:`p-2 rounded-lg border-2 transition-all text-center ${Q===$e?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${Qe}`}),e.jsx("span",{className:"text-[10px] font-medium",children:ve})]},$e))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(q,{variant:"outline",onClick:()=>f("contact"),className:"flex-1",children:"Back"}),e.jsx(q,{onClick:Ee,disabled:!E||j,className:"flex-1 gap-2",children:j?"Creating...":"Create Card"})]})]})]})]})}function MYs({open:s,onOpenChange:t}){const r=qr(),n=a=>{t(!1),r(a)};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsx(bs,{children:"Set up an email sender"}),e.jsx(an,{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:()=>n("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(Ks,{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:()=>n("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(n2,{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(q,{variant:"ghost",onClick:()=>t(!1),children:"Not now"})})]})]})})}const IYs={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 PYs({card:s}){const{user:t}=Cs(),{isGmailConnected:r,hasVerifiedSes:n,canSendEmail:a,sendMethod:i}=Cm(),l=is(),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[m,f]=k.useState("");k.useEffect(()=>{o&&s.contact_id&&!m&&U.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:E})=>{E!=null&&E.email&&f(E.email)})},[o,s.contact_id]);const x={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,_]=k.useState(x[s.card_type]||`A Special Card for ${s.recipient_name}!`),[b,j]=k.useState(""),N=`https://cardstudio.relevelup.com/c/${s.share_token}`,C=Mt({mutationFn:async()=>{var O;if(!m)throw new Error("Recipient email is required");const E=`
${b?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,{data:D}=await U.auth.getSession(),R=(O=D==null?void 0:D.session)==null?void 0:O.access_token,F=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/gmail-send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R}`},body:JSON.stringify({to:m,subject:y,body:E,contactId:s.contact_id||void 0})});if(!F.ok){const B=await F.json();throw new Error(B.error||"Failed to send")}return F.json()},onSuccess:async()=>{await U.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:"gmail"}).eq("id",s.id),l.invalidateQueries({queryKey:["sendable-cards"]}),he.success(`Card sent to ${m}!`),c(!1)},onError:E=>{he.error(E.message||"Failed to send email")}}),A=i==="mass_email"?"Mass Email":"Gmail";return a?e.jsxs(vs,{open:o,onOpenChange:c,children:[e.jsx(Yi,{asChild:!0,children:e.jsx(q,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(hn,{className:"h-3 w-3"})})}),e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsx(_s,{children:e.jsxs(bs,{children:["Send Card via ",A]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{htmlFor:"gmail-to",children:"To"}),e.jsx(U0t,{value:m,onChange:f,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(ce,{children:"Subject"}),e.jsx(Ne,{value:y,onChange:E=>_(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Personal Note (optional)"}),e.jsx(pr,{value:b,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:N})]}),e.jsx(q,{onClick:()=>C.mutate(),disabled:!m||C.isPending,className:"w-full gap-2",children:C.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(hn,{className:"h-4 w-4"})," Send Card"]})})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"outline",size:"sm",className:"gap-1 text-xs",title:"Set up an email sender to send cards",onClick:()=>u(!0),children:e.jsx(hn,{className:"h-3 w-3"})}),e.jsx(MYs,{open:d,onOpenChange:u})]})}function LYs({card:s}){const t=is(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(s.recipient_name),[c,d]=k.useState(s.property_address||""),[u,m]=k.useState(s.home_anniversary_date||""),[f,x]=k.useState(s.custom_message||""),[y,_]=k.useState(s.template),[b,j]=k.useState(s.property_photo_url),[N,C]=k.useState(s.video_url||null),A=D=>{D&&(o(s.recipient_name),d(s.property_address||""),m(s.home_anniversary_date||""),x(s.custom_message||""),_(s.template),j(s.property_photo_url),C(s.video_url||null)),n(D)},E=async()=>{if(!l.trim()){he.error("Recipient name is required");return}i(!0);try{const{error:D}=await U.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:f.trim()||null,template:y,property_photo_url:b||null,video_url:N||null}).eq("id",s.id);if(D)throw D;t.invalidateQueries({queryKey:["sendable-cards"]}),he.success("Card updated"),n(!1)}catch(D){he.error(D.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(vs,{open:r,onOpenChange:A,children:[e.jsx(Yi,{asChild:!0,children:e.jsx(q,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Ua,{className:"h-3 w-3"})})}),e.jsxs(ys,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Recipient Name"}),e.jsx(Ne,{value:l,onChange:D=>o(D.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Property Address"}),e.jsx(Ne,{value:c,onChange:D=>d(D.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Home Anniversary Date"}),e.jsx(Ne,{type:"date",value:u,onChange:D=>m(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Personal Message (optional)"}),e.jsx(pr,{value:f,onChange:D=>x(D.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(Bbt,{photoUrl:b,videoUrl:N,onPhotoChange:j,onVideoChange:C,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(D=>e.jsxs("button",{onClick:()=>_(D),className:`p-3 rounded-lg border-2 transition-all text-center ${y===D?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${D==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":D==="bold"?"bg-gradient-to-br from-violet-500 to-fuchsia-500":"bg-gradient-to-br from-amber-200 to-orange-300"}`}),e.jsx("span",{className:"text-xs font-medium capitalize",children:D})]},D))})]}),e.jsx(q,{onClick:E,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function DYs(){const{user:s}=Cs(),t=is(),[r,n]=k.useState(""),[a,i]=ic(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),u=a.get("date"),m=!!l,{data:f,isLoading:x}=pt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:C,error:A}=await U.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(A)throw A;return C},enabled:!!(s!=null&&s.id)}),y=Mt({mutationFn:async C=>{const{error:A}=await U.from("sendable_cards").delete().eq("id",C);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),he.success("Card deleted")}}),_=C=>{const A=`https://cardstudio.relevelup.com/c/${C}`;navigator.clipboard.writeText(A),he.success("Share link copied!")},b=f==null?void 0:f.filter(C=>{var A;return!r||C.recipient_name.toLowerCase().includes(r.toLowerCase())||((A=C.property_address)==null?void 0:A.toLowerCase().includes(r.toLowerCase()))}),j={elegant:"Elegant",bold:"Bold",warm:"Warm"},N={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(ws,{title:"Card Studio",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Card Studio"})}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create & send beautiful branded cards to your clients"})]}),e.jsx(uYe,{initialOpen:m,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(_n,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search cards...",value:r,onChange:C=>n(C.target.value),className:"pl-9"})]}),x?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(C=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Pe,{className:"p-4",children:[e.jsx("div",{className:"h-40 bg-muted rounded-lg mb-3"}),e.jsx("div",{className:"h-4 bg-muted rounded w-2/3 mb-2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2"})]})},C))}):b!=null&&b.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(C=>e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`aspect-[16/10] flex items-center justify-center relative overflow-hidden ${C.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":C.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:[C.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"})]}),C.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%)]"})]}),C.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:C.card_type==="home_anniversary"?"🏡":C.card_type==="wedding_anniversary"?"💍":C.card_type==="birthday"?"🎂":C.card_type==="just_sold"?"🎉":C.card_type==="just_listed"?"🏠":C.card_type==="thank_you"?"💐":C.card_type==="congratulations"?"🏆":C.card_type==="holiday"?"🎄":C.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${C.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:N[C.card_type]||C.card_type}),e.jsx("p",{className:`font-semibold text-base ${C.template==="bold"?"text-white":"text-foreground"}`,children:C.recipient_name}),C.property_address&&e.jsx("p",{className:`text-xs mt-1 ${C.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:C.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(Xe,{variant:C.template==="bold"?"outline":"secondary",className:`text-[10px] ${C.template==="bold"?"border-white/30 text-white/80":""}`,children:j[C.template]||C.template})})]}),e.jsxs(Pe,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Nn,{className:"h-3 w-3"}),C.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Nl(new Date(C.created_at),{addSuffix:!0})})]}),C.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",As(new Date(C.sent_at),"MMM d, yyyy")," via ",C.sent_via]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(q,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>_(C.share_token),children:[e.jsx(si,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(LYs,{card:C}),e.jsx(PYs,{card:C}),e.jsx(q,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${C.share_token}`,"_blank"),children:e.jsx(un,{className:"h-3 w-3"})}),e.jsx(q,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>y.mutate(C.id),children:e.jsx(zr,{className:"h-3 w-3"})})]})]})]},C.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Ks,{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(uYe,{initialOpen:m,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const RV=[{id:"mls",label:"MLS Description",tag:"Standard",icon:Pn,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:Gf,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:zh,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:w_,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:SF,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:Wo,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:gu,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:Yf,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:fh,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:jn,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:E_,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:xu,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:wF,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:ph,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:bn,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:rf,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:BE,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:Gf,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:BF,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:Ma,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:Ks,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:IF,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:Dr,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:E_,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:hF,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:Ma,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function RYs(){var ca,Vi,so,Ka,kn,Fi,zi,Qa,Hi,Gi,Qn;const{user:s}=Cs(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState([]),[o,c]=k.useState(""),[d,u]=k.useState([]),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState(""),[C,A]=k.useState(""),[E,D]=k.useState(""),[R,F]=k.useState(""),[O,B]=k.useState(null),[K,Z]=k.useState(""),[Q,W]=k.useState(""),[te,ne]=k.useState(""),[ae,ue]=k.useState(""),[me,de]=k.useState(""),[fe,je]=k.useState(""),[xe,Ee]=k.useState(""),[Me,Oe]=k.useState(""),[Ie,ze]=k.useState(""),[Ve,Le]=k.useState(""),[$e,ve]=k.useState(""),[Qe,we]=k.useState(""),[nt,Se]=k.useState(""),[Ge,We]=k.useState(""),[Ce,qe]=k.useState(""),[et,Ze]=k.useState(""),[rt,ct]=k.useState(""),[vt,kt]=k.useState(""),[St,Yt]=k.useState(""),[es,zs]=k.useState(""),[sr,ms]=k.useState(""),[gt,Ut]=k.useState(""),[ht,Jt]=k.useState(""),[Ms,ts]=k.useState(""),[Xs,js]=k.useState(""),[$s,Js]=k.useState("listing"),[or,Er]=k.useState("mls"),[Sr,Gr]=k.useState({}),[Yr,Fn]=k.useState({}),[sa,gs]=k.useState(!1),[mi,In]=k.useState(!1),Br=vr=>{Js(vr);const Ca=RV.find(Ji=>Ji.category===vr);Ca&&Er(Ca.id)},{data:ps}=pt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&sa,queryFn:async()=>{const{data:vr,error:Ca}=await U.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(Ca)throw Ca;return vr||[]}}),Or=()=>{const vr=o.trim();vr&&(l(Ca=>[...Ca,vr]),c(""))},Qr=vr=>l(Ca=>Ca.filter((Ji,Zo)=>Zo!==vr)),Tn=vr=>{var Ca,Ji,Zo,vl;B(vr.id),r(vr.property_address||""),D(vr.city||""),F(vr.state||""),N(((Ca=vr.price)==null?void 0:Ca.toString())||""),f(((Ji=vr.bedrooms)==null?void 0:Ji.toString())||""),y(((Zo=vr.bathrooms)==null?void 0:Zo.toString())||""),b(((vl=vr.square_footage)==null?void 0:vl.toString())||""),A(vr.property_type||""),a(vr.description||""),gs(!1),he.success("Listing imported")},Qt=async vr=>{if(!(!vr.target.files||!(s!=null&&s.id))){In(!0);try{const Ca=[];for(const Ji of Array.from(vr.target.files).slice(0,10)){const Zo=`${s.id}/${Date.now()}-${Ji.name.replace(/[^\w.-]/g,"_")}`,{error:vl}=await U.storage.from("listing-photos").upload(Zo,Ji,{upsert:!1});if(vl){console.error(vl);continue}const{data:vo}=U.storage.from("listing-photos").getPublicUrl(Zo);Ca.push(vo.publicUrl)}u(Ji=>[...Ji,...Ca]),Ca.length&&he.success(`${Ca.length} photo(s) uploaded`)}catch(Ca){he.error(Ca.message||"Photo upload failed")}finally{In(!1)}}},Re=RV.find(vr=>vr.id===or),Ke=async vr=>{var Ji,Zo,vl;const Ca=RV.find(vo=>vo.id===vr);if(!t.trim()&&!n.trim()&&i.length===0){he.error("Add a property address, MLS remarks, or features first");return}if((Ji=Ca.extras)!=null&&Ji.includes("openHouse")&&(!K||!Q||!te)){he.error("Add the open house date, start and end time");return}if((Zo=Ca.extras)!=null&&Zo.includes("priceImprovement")&&(!ae||!me)){he.error("Add previous and new price");return}if((vl=Ca.extras)!=null&&vl.includes("sold")&&!fe){he.error("Add the sold price");return}Er(vr),Fn(vo=>({...vo,[vr]:!0}));try{const{data:vo,error:hd}=await U.functions.invoke("listing-studio-generate",{body:{copyType:vr,propertyAddress:t,mlsRemarks:n,features:i,photoUrls:d,listingId:O,bedrooms:m?Number(m):null,bathrooms:x?Number(x):null,squareFootage:_?Number(_):null,price:j?Number(j):null,propertyType:C||null,city:E||null,state:R||null,openHouseDate:K||null,openHouseStart:Q||null,openHouseEnd:te||null,previousPrice:ae?Number(ae):null,newPrice:me?Number(me):null,soldPrice:fe?Number(fe):null,soldDate:xe||null,comingSoonDate:Me||null,builderName:Ie||null,yearBuilt:Ve?Number(Ve):null,warrantyInfo:$e||null,monthlyRent:Qe?Number(Qe):null,capRate:nt||null,occupancy:Ge||null,daysOnMarket:Ce?Number(Ce):null,offerCount:et?Number(et):null,originalListPrice:rt?Number(rt):null,soldDaysOnMarket:vt?Number(vt):null,commissionOffered:St||null,refreshments:es||null,vibe:sr||null,neighborhoodHighlights:gt||null,agentName:ht||null,agentBrokerage:Ms||null,agentContact:Xs||null}});if(hd)throw hd;if(vo!=null&&vo.error)throw new Error(vo.error);Gr(ju=>({...ju,[vr]:vo.content}))}catch(vo){he.error(vo.message||"Generation failed")}finally{Fn(vo=>({...vo,[vr]:!1}))}},at=vr=>{navigator.clipboard.writeText(vr),he.success("Copied to clipboard")},Nt=Re.icon,Ft=Sr[or]?Sr[or].trim().split(/\s+/).length:0,qt=vr=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:RV.filter(Ca=>Ca.category===vr).map(Ca=>{const Ji=Ca.icon,Zo=or===Ca.id,vl=!!Sr[Ca.id];return e.jsxs("button",{onClick:()=>Er(Ca.id),className:zt("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",Zo?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[Zo&&e.jsx("div",{className:zt("absolute inset-0 opacity-[0.07] bg-gradient-to-br",Ca.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:zt("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",Ca.accent),children:e.jsx(Ji,{className:"h-4 w-4"})}),vl&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(la,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:Ca.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Ca.desc})]})]})]},Ca.id)})}),cs=(ca=Re.extras)==null?void 0:ca.includes("openHouse"),it=(Vi=Re.extras)==null?void 0:Vi.includes("priceImprovement"),Xt=(so=Re.extras)==null?void 0:so.includes("sold"),Bs=(Ka=Re.extras)==null?void 0:Ka.includes("comingSoon"),us=(kn=Re.extras)==null?void 0:kn.includes("newConstruction"),cr=(Fi=Re.extras)==null?void 0:Fi.includes("investment"),Ar=(zi=Re.extras)==null?void 0:zi.includes("underContract"),xr=(Qa=Re.extras)==null?void 0:Qa.includes("brokerOpen"),Kr=(Hi=Re.extras)==null?void 0:Hi.includes("vibe"),mn=(Gi=Re.extras)==null?void 0:Gi.includes("neighborhood"),pn=(Qn=Re.extras)==null?void 0:Qn.includes("signoff"),wn=cs||it||Xt||Bs||us||cr||Ar||xr||Kr||mn||pn;return e.jsx(ws,{title:"Listing Studio",children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl border bg-gradient-to-br from-fuchsia-500/10 via-violet-500/5 to-sky-500/10 dark:from-fuchsia-500/20 dark:via-violet-500/10 dark:to-sky-500/20",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_top_right,_hsl(var(--primary)/0.15),_transparent_60%)]"}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-fuchsia-500/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-24 h-72 w-72 rounded-full bg-sky-500/20 blur-3xl"}),e.jsxs("div",{className:"relative px-6 py-8 sm:px-10 sm:py-12 flex flex-col md:flex-row md:items-center gap-6",children:[e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-background/60 backdrop-blur-sm border text-xs font-medium",children:[e.jsx(Ir,{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(vs,{open:sa,onOpenChange:gs,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(En,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(ys,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsx(bs,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(ps!=null&&ps.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),ps==null?void 0:ps.map(vr=>e.jsxs("button",{onClick:()=>Tn(vr),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:vr.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[vr.city,vr.state].filter(Boolean).join(", "),vr.price?` · $${Number(vr.price).toLocaleString()}`:"",vr.bedrooms?` · ${vr.bedrooms}bd`:"",vr.bathrooms?` · ${vr.bathrooms}ba`:""]})]},vr.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(ke,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Pe,{className:"p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 grid place-items-center",children:e.jsx(Pn,{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(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(Ne,{value:t,onChange:vr=>r(vr.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(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(Ne,{value:E,onChange:vr=>D(vr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(Ne,{value:R,onChange:vr=>F(vr.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(Ne,{type:"number",value:j,onChange:vr=>N(vr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(Ne,{value:C,onChange:vr=>A(vr.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(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(Ne,{type:"number",value:m,onChange:vr=>f(vr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(Ne,{type:"number",step:"0.5",value:x,onChange:vr=>y(vr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(Ne,{type:"number",value:_,onChange:vr=>b(vr.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(pr,{value:n,onChange:vr=>a(vr.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(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:o,onChange:vr=>c(vr.target.value),onKeyDown:vr=>vr.key==="Enter"&&(vr.preventDefault(),Or()),placeholder:"e.g. Quartz countertops"}),e.jsx(q,{type:"button",size:"icon",variant:"secondary",onClick:Or,children:e.jsx(Ys,{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((vr,Ca)=>e.jsxs(Xe,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[vr,e.jsx("button",{onClick:()=>Qr(Ca),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx($r,{className:"h-3 w-3"})})]},Ca))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{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(Qy,{className:"h-4 w-4"}),mi?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:Qt,disabled:mi,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((vr,Ca)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:vr,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(Ji=>Ji.filter((Zo,vl)=>vl!==Ca)),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($r,{className:"h-3 w-3"})})]},Ca))})]}),wn&&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(Ir,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",Re.label]})]}),cs&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(Ne,{type:"date",value:K,onChange:vr=>Z(vr.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(Ne,{type:"time",value:Q,onChange:vr=>W(vr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(Ne,{type:"time",value:te,onChange:vr=>ne(vr.target.value)})]})]})]}),it&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(Ne,{type:"number",value:ae,onChange:vr=>ue(vr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(Ne,{type:"number",value:me,onChange:vr=>de(vr.target.value),placeholder:"$"})]})]}),Xt&&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(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(Ne,{type:"number",value:fe,onChange:vr=>je(vr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(Ne,{type:"date",value:xe,onChange:vr=>Ee(vr.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(Ne,{type:"number",value:rt,onChange:vr=>ct(vr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(Ne,{type:"number",value:vt,onChange:vr=>kt(vr.target.value)})]})]})]}),Bs&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(Ne,{type:"date",value:Me,onChange:vr=>Oe(vr.target.value)})]}),us&&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(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(Ne,{value:Ie,onChange:vr=>ze(vr.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(Ne,{type:"number",value:Ve,onChange:vr=>Le(vr.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(Ne,{value:$e,onChange:vr=>ve(vr.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),cr&&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(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(Ne,{type:"number",value:Qe,onChange:vr=>we(vr.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(Ne,{value:nt,onChange:vr=>Se(vr.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Ge,onChange:vr=>We(vr.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"})]})]})]}),Ar&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(Ne,{type:"number",value:Ce,onChange:vr=>qe(vr.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(Ne,{type:"number",value:et,onChange:vr=>Ze(vr.target.value),placeholder:"e.g. 5"})]})]}),xr&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(Ne,{value:St,onChange:vr=>Yt(vr.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(Ne,{value:es,onChange:vr=>zs(vr.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Kr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:sr,onChange:vr=>ms(vr.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"})]})]}),mn&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(pr,{value:gt,onChange:vr=>Ut(vr.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),pn&&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(ce,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(Ne,{value:ht,onChange:vr=>Jt(vr.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(Ne,{value:Ms,onChange:vr=>ts(vr.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(Ne,{value:Xs,onChange:vr=>js(vr.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:En},{key:"social",label:"Social Media",icon:gu},{key:"video",label:"Video Scripts",icon:bn},{key:"email",label:"Email Marketing",icon:Ks}].map(vr=>{const Ca=vr.icon,Ji=$s===vr.key;return e.jsxs("button",{onClick:()=>Br(vr.key),className:zt("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",Ji?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(Ca,{className:"h-4 w-4"}),vr.label]},vr.key)})}),qt($s),e.jsxs(ke,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:zt("h-1 bg-gradient-to-r",Re.accent)}),e.jsxs(Pe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:zt("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",Re.accent),children:e.jsx(Nt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[Re.label,e.jsx(Xe,{variant:"outline",className:"text-[10px] font-normal",children:Re.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Sr[or]?`${Ft} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[Sr[or]&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>at(Sr[or]),children:[e.jsx(si,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(q,{onClick:()=>Ke(or),disabled:Yr[or],className:zt("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",Re.accent),size:"sm",children:Yr[or]?e.jsxs(e.Fragment,{children:[e.jsx(ls,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):Sr[or]?e.jsxs(e.Fragment,{children:[e.jsx(lo,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(p0,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),Sr[or]?e.jsx(pr,{value:Sr[or],onChange:vr=>Gr(Ca=>({...Ca,[or]:vr.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:zt("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",Re.accent),children:e.jsx(p0,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",Re.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 yO({delay:s,x:t,y:r,size:n}){return e.jsx(Zr.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:t,top:r,width:n,height:n},animate:{y:[0,-20,0],opacity:[.3,.7,.3],scale:[1,1.2,1]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeInOut"}})}function OYs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:m,videoUrl:f}=s,x=gD[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(Zr.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(Zr.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(yO,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(yO,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(yO,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(yO,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(yO,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(Zr.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(Zr.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(Zr.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(Zr.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(Zr.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:x.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Zr.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(Zr.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:x.title[0]}),x.title[1]&&e.jsx(Zr.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:x.title[1]}),e.jsxs(Zr.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:r}),n&&e.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:n})]}),e.jsx(Zr.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),m&&e.jsx(Zr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),f&&e.jsx(Zr.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:`${f}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zr.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||x.defaultMessage}),e.jsxs(Zr.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(Zr.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(Zr.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(Mn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zr.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(Ks,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zr.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 wje({delay:s,x:t,y:r,color:n,size:a}){return e.jsx(Zr.div,{className:`absolute rounded-full blur-2xl ${n}`,style:{left:t,top:r,width:a,height:a},animate:{scale:[1,1.4,1],opacity:[.2,.5,.2]},transition:{duration:5,delay:s,repeat:1/0,ease:"easeInOut"}})}function vO({delay:s,x:t,y:r}){return e.jsx(Zr.div,{className:"absolute text-white/30 text-lg",style:{left:t,top:r},animate:{opacity:[0,1,0],scale:[.5,1,.5],rotate:[0,180,360]},transition:{duration:3,delay:s,repeat:1/0,ease:"easeInOut"},children:"✦"})}const hYe={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 FYs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:m,videoUrl:f}=s,x=gD[t],y=hYe[t]||hYe.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(wje,{delay:0,x:"10%",y:"10%",color:y.orbs[0],size:200}),e.jsx(wje,{delay:1,x:"70%",y:"60%",color:y.orbs[1],size:180}),e.jsx(wje,{delay:2,x:"50%",y:"20%",color:y.orbs[2],size:150}),e.jsx(vO,{delay:0,x:"20%",y:"25%"}),e.jsx(vO,{delay:.8,x:"75%",y:"15%"}),e.jsx(vO,{delay:1.6,x:"85%",y:"65%"}),e.jsx(vO,{delay:2.4,x:"10%",y:"75%"}),e.jsx(vO,{delay:.4,x:"45%",y:"85%"}),e.jsxs(Zr.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(Zr.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(Zr.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(Zr.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(Zr.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:x.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zr.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(Zr.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(Zr.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:x.title[0]}),x.title[1]&&e.jsx(Zr.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:x.title[1]}),e.jsx(Zr.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:x.emojis.slice(0,3).join("")}),e.jsxs(Zr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:r}),n&&e.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(Pn,{className:"h-3.5 w-3.5"}),n]})]}),m&&e.jsx(Zr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),f&&e.jsx(Zr.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:`${f}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zr.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||x.defaultMessage})}),e.jsxs(Zr.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(Zr.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(Zr.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(Mn,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(Zr.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(Ks,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zr.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 zYs({emoji:s,delay:t,x:r,duration:n}){return e.jsx(Zr.div,{className:"absolute text-2xl pointer-events-none",style:{left:r,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:n,delay:t,repeat:1/0,ease:"easeOut"},children:s})}const mYe={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 BYs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:m,videoUrl:f}=s,x=gD[t],y=mYe[t]||mYe.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:[x.emojis.map((_,b)=>e.jsx(zYs,{emoji:_,delay:b*1.2,x:`${15+b*14}%`,duration:5+b%3},b)),e.jsx(Zr.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(Zr.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(Zr.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(Zr.div,{className:`h-28 bg-gradient-to-r ${y.header} relative overflow-hidden`,children:[e.jsx(Zr.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(Zr.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:x.emojis[0]}),e.jsx(Zr.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:x.emojis[1]}),e.jsx(Zr.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:x.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(Zr.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(Zr.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:x.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Zr.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(Zr.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(Zr.h1,{className:`text-3xl font-bold ${y.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[x.title.join(" ")," ",x.emojis[4]]}),e.jsxs(Zr.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:r}),n&&e.jsxs("p",{className:`text-sm ${y.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(Ma,{className:"h-3 w-3"}),n]})]}),m&&e.jsx(Zr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),f&&e.jsx(Zr.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:`${f}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zr.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||x.defaultMessage,'"']})}),e.jsxs(Zr.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(Zr.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(Zr.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(Mn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zr.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(Ks,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zr.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 OV({delay:s,x:t,y:r,size:n,color:a}){return e.jsx(Zr.div,{className:`absolute rounded-full ${a} blur-3xl`,style:{left:t,top:r,width:n,height:n},animate:{scale:[1,1.3,1],opacity:[.4,.7,.4],x:[0,20,-10,0],y:[0,-15,10,0]},transition:{duration:8,delay:s,repeat:1/0,ease:"easeInOut"}})}function jje({delay:s,x:t,y:r,size:n}){return e.jsx(Zr.div,{className:"absolute rounded-full border border-white/10",style:{left:t,top:r,width:n,height:n},animate:{scale:[1,1.2,1],opacity:[.1,.3,.1],rotate:[0,180,360]},transition:{duration:12,delay:s,repeat:1/0,ease:"linear"}})}const fYe={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 $Ys(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:m,videoUrl:f}=s,x=gD[t],y=fYe[t]||fYe.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(OV,{delay:0,x:"5%",y:"10%",size:300,color:y.mesh[0]}),e.jsx(OV,{delay:2,x:"60%",y:"50%",size:250,color:y.mesh[1]}),e.jsx(OV,{delay:4,x:"30%",y:"70%",size:200,color:y.mesh[2]}),e.jsx(OV,{delay:1,x:"80%",y:"15%",size:180,color:y.mesh[0]}),e.jsx(jje,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(jje,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(jje,{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(Zr.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(Zr.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(Zr.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(Zr.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(Zr.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(Zr.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:x.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zr.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(Zr.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(Zr.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:x.title[0]}),x.title[1]&&e.jsx(Zr.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:x.title[1]}),e.jsxs(Zr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:r}),n&&e.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(Ma,{className:"h-3 w-3"})," ",n]})]}),e.jsx(Zr.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),m&&e.jsx(Zr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),f&&e.jsx(Zr.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:`${f}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zr.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||x.defaultMessage,'"']})}),e.jsxs(Zr.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(Zr.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(Zr.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(Mn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zr.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(Ks,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zr.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 Nje({delay:s,x:t,angle:r,color:n}){return e.jsx(Zr.div,{className:`absolute h-[400px] w-[1px] ${n} origin-top`,style:{left:t,top:"-10%",transform:`rotate(${r}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:s,repeat:1/0,ease:"easeInOut"}})}function FV({delay:s,x:t}){return e.jsx(Zr.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 pYe={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 UYs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:m,videoUrl:f}=s,x=gD[t],y=pYe[t]||pYe.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(Nje,{delay:0,x:"20%",angle:15,color:y.stripe}),e.jsx(Nje,{delay:2,x:"75%",angle:-12,color:y.stripe}),e.jsx(Nje,{delay:4,x:"50%",angle:5,color:y.stripe}),e.jsx(FV,{delay:0,x:"30%"}),e.jsx(FV,{delay:1.5,x:"60%"}),e.jsx(FV,{delay:3,x:"45%"}),e.jsx(FV,{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(Zr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(Zr.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(Zr.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(Zr.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:x.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(Zr.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(Zr.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:x.title[0]})}),x.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(Zr.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:x.title[1]})}),e.jsxs(Zr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[e.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:r}),n&&e.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[e.jsx(Ma,{className:"h-3 w-3"})," ",n]})]}),e.jsxs(Zr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(Zr.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(Zr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(Zr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),m&&e.jsxs(Zr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),f&&e.jsx(Zr.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:`${f}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zr.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||x.defaultMessage}),e.jsxs(Zr.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(Zr.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(Zr.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(Mn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zr.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(Ks,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(Zr.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 $bt(){const{shareToken:s}=xo(),{data:t,isLoading:r,error:n}=pt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await U.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(k.useEffect(()=>{s&&U.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(n||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-El(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(FYs,{...i});case"warm":return e.jsx(BYs,{...i});case"glass":return e.jsx($Ys,{...i});case"cinematic":return e.jsx(UYs,{...i});case"elegant":default:return e.jsx(OYs,{...i})}}function qYs(){const s=xa();return pt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await U.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function VYs(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n}=await U.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(n){const{data:a,error:i}=await U.from("drip_settings").update(r).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await U.from("drip_settings").insert({user_id:s,is_globally_enabled:r.is_globally_enabled??!1,append_signature:r.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function HYs(){const s=qr(),{isGmailConnected:t,gmailEmail:r}=Cm(),{data:n,isLoading:a}=qYs(),i=VYs(),[l,o]=k.useState(!1),[c,d]=k.useState(!0),[u,m]=k.useState(!1);k.useEffect(()=>{n&&(o(n.is_globally_enabled),d(n.append_signature))},[n]);const f=async y=>{if(y&&!t){he.error("Connect your Gmail account first before enabling Smart Drips");return}o(y);try{await i.mutateAsync({is_globally_enabled:y}),he.success(y?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!y),he.error("Failed to update settings")}},x=async y=>{d(y);try{await i.mutateAsync({append_signature:y}),he.success(y?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!y),he.error("Failed to update settings")}};return e.jsxs(vs,{open:u,onOpenChange:m,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Bo,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(ys,{className:"sm:max-w-md",children:[e.jsxs(_s,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Bo,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(an,{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(Ks,{className:`h-4 w-4 ${t?"text-emerald-600":"text-destructive"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t?"Gmail Connected":"Gmail Not Connected"}),r&&e.jsx("p",{className:"text-xs text-muted-foreground",children:r})]})]}),t?e.jsxs(Xe,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(qn,{className:"h-3 w-3"}),"Active"]}):e.jsxs(q,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{m(!1),s("/mission-control/integrations")},children:[e.jsx(un,{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(cl,{}),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($F,{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(Rr,{checked:l,onCheckedChange:f,disabled:a||i.isPending})]}),e.jsx(cl,{}),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(zy,{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(Rr,{checked:c,onCheckedChange:x,disabled:a||i.isPending})]}),c&&e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{m(!1),s("/profile")},children:[e.jsx(zy,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function GYs(){const s=xa();return pt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function WYs(){const s=xa();return pt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function KYs(){const s=xa(),t=is();return Mt({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await U.from("drip_templates").insert({owner_user_id:s,stage_id:r.stage_id,title:r.title||"",subject:r.subject||"",body:r.body||"",video_url:r.video_url||null,channel:r.channel||"email",delay_type:r.delay_type||"instant",delay_minutes:r.delay_minutes||0,is_enabled:!1,deal_type:r.deal_type||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function YYs(){const s=is();return Mt({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await U.from("drip_templates").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function ZYs(){const s=is();return Mt({mutationFn:async t=>{const{error:r}=await U.from("drip_templates").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function XYs(){const s=xa(),t=is();return Mt({mutationFn:async({templateId:r,stageId:n})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("drip_templates").select("*").eq("id",r).single();if(i)throw i;const{data:l,error:o}=await U.from("drip_templates").insert({owner_user_id:s,stage_id:n,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const QYs=[{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 JYs({open:s,onOpenChange:t,campaignId:r,campaignName:n}){const{data:a,isLoading:i}=pzs(r||void 0),l=gzs(),o=X0t(),c=async(m,f)=>{try{await l.mutateAsync({id:m,status:f}),he.success(`Enrollment ${f}`)}catch{he.error("Failed to update")}},d=async m=>{if(r)try{const f=await o.mutateAsync({campaignId:r,contactIds:[m]});f.enrolled>0?he.success("Contact re-enrolled — first email queued"):f.skipped>0?he.message("Already active in this campaign"):he.error("Could not re-enroll")}catch{he.error("Failed to re-enroll")}},u=m=>{const f={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(Xe,{variant:"outline",className:`text-[10px] capitalize ${f[m]||""}`,children:m})};return e.jsx(vs,{open:s,onOpenChange:t,children:e.jsxs(ys,{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(bs,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-4 w-4 text-primary"}),"Enrollments — ",n||"Campaign"]}),e.jsx(an,{className:"text-xs mt-1",children:"Manage every contact currently in this campaign. Pause to take over, or exit to remove."})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-5",children:i?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(m=>e.jsx(dr,{className:"h-14"},m))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Dr,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No contacts enrolled yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Head to your contacts page and bulk-enroll to start nurturing."})]}):e.jsx("div",{className:"space-y-2",children:a.map(m=>{var f,x,y,_;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(f=m.contact)==null?void 0:f.first_name," ",(x=m.contact)==null?void 0:x.last_name]}),u(m.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((y=m.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ks,{className:"h-2.5 w-2.5"})," ",m.contact.email]}),e.jsxs("span",{children:["Step ",m.current_step]}),m.next_send_at&&m.status==="active"&&e.jsxs("span",{children:["Next: ",As(new Date(m.next_send_at),"MMM d, h:mma")]}),m.exit_reason&&e.jsxs("span",{children:["Exit: ",m.exit_reason]})]})]}),m.status==="active"&&e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"paused"),title:"Pause",children:e.jsx(Xf,{className:"h-3.5 w-3.5"})}),m.status==="paused"&&e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"active"),title:"Resume",children:e.jsx(Al,{className:"h-3.5 w-3.5"})}),(m.status==="active"||m.status==="paused")&&e.jsx(q,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"exited"),title:"Exit",children:e.jsx($r,{className:"h-3.5 w-3.5 text-destructive"})}),(m.status==="exited"||m.status==="completed")&&((_=m.contact)==null?void 0:_.id)&&e.jsxs(q,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>d(m.contact.id),disabled:o.isPending,children:[e.jsx(ev,{className:"h-3 w-3"}),"Re-enroll"]})]},m.id)})})})})]})})}function eZs(){var C;const{data:s,isLoading:t}=l6e(),{hasLeadSite:r}=hf(),n=uzs(),a=dzs(),i=Y0t(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,m]=k.useState(null),[f,x]=k.useState(null),y=(s||[]).filter(A=>!A.is_starter),_=(s||[]).filter(A=>A.is_starter).filter(A=>!A.requires_lead_site||r),b=async A=>{try{await n.mutateAsync(A),he.success("Campaign added to your library — customize and activate it!"),o(null)}catch(E){he.error(E.message||"Failed to copy campaign")}},j=async A=>{try{await i.mutateAsync({id:A.id,is_active:!A.is_active}),he.success(A.is_active?"Campaign paused":"Campaign activated")}catch{he.error("Failed to update")}},N=async A=>{if(confirm("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(A),he.success("Campaign deleted")}catch{he.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(dr,{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(a2,{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(Hu,{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(hn,{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(Dr,{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(q,{size:"sm",onClick:()=>{m(null),d(!0)},children:[e.jsx(Ys,{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(Ir,{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(q,{size:"sm",onClick:()=>{m(null),d(!0)},children:[e.jsx(Ys,{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(tZs,{campaign:A,onPreview:()=>o(A.id),onToggleActive:()=>j(A),onDelete:()=>N(A.id),onEdit:()=>{m(A.id),d(!0)},onViewEnrollments:()=>x(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(Ir,{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(Xe,{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(sZs,{campaign:A,onPreview:()=>o(A.id)},A.id))})]}),e.jsx(rZs,{campaignId:l,open:!!l,onOpenChange:A=>!A&&o(null),onClone:b,isCloning:n.isPending,onEdit:A=>{o(null),m(A),d(!0)}}),e.jsx(eyt,{open:c,onOpenChange:d,campaignId:u}),e.jsx(JYs,{open:!!f,onOpenChange:A=>!A&&x(null),campaignId:f,campaignName:(C=y.find(A=>A.id===f))==null?void 0:C.name})]})}function tZs({campaign:s,onPreview:t,onToggleActive:r,onDelete:n,onEdit:a,onViewEnrollments:i}){const o=xzs(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(Xe,{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(Xe,{variant:"outline",className:"text-[9px] mt-2",children:_ye[s.category]}),c&&e.jsxs("button",{onClick:r,className:"mt-2 w-full flex items-start gap-1.5 p-2 rounded-md bg-amber-500/10 border border-amber-500/30 text-left hover:bg-amber-500/15 transition-colors",children:[e.jsx(du,{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(q,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx(q,{size:"sm",variant:s.is_active?"secondary":"default",className:"h-7 text-xs",onClick:r,children:s.is_active?"Pause":"Activate"})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-[10px]",children:[e.jsx("button",{onClick:i,className:"text-primary hover:underline",children:"View enrollments"}),e.jsx("button",{onClick:t,className:"text-muted-foreground hover:underline",children:"Preview"}),e.jsx("button",{onClick:n,className:"text-muted-foreground hover:text-destructive",children:"Delete"})]})]})]})}function sZs({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(Xe,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(Ir,{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(Xe,{variant:"outline",className:"text-[9px] mt-2",children:_ye[s.category]})]})]})}function rZs({campaignId:s,open:t,onOpenChange:r,onClone:n,isCloning:a,onEdit:i}){const{data:l}=l6e(),{data:o}=Z0t(s||void 0),[c,d]=k.useState(new Set),u=l==null?void 0:l.find(x=>x.id===s);if(!u)return null;const m=x=>{d(y=>{const _=new Set(y);return _.has(x)?_.delete(x):_.add(x),_})},f=(x,y)=>{if(x.delay_type==="calendar_anchor"){const b=x.anchor_field==="birthday"?"birthday":"home anniversary",j=x.anchor_offset_days||0;return j===0?`On their ${b}`:j<0?`${Math.abs(j)} days before ${b}`:`${j} days after ${b}`}if(y===0&&x.delay_days===0&&x.delay_hours===0)return"Sends immediately";const _=[];return x.delay_days&&_.push(`${x.delay_days}d`),x.delay_hours&&_.push(`${x.delay_hours}h`),y===0?`After ${_.join(" ")}`:`+${_.join(" ")}`};return e.jsx(vs,{open:t,onOpenChange:r,children:e.jsxs(ys,{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(bs,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(an,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(Xe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:_ye[u.category]}),e.jsxs(Xe,{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((x,y)=>{const _=c.has(x.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}),ym(x.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:[x.delay_type==="calendar_anchor"?e.jsx(vn,{className:"h-3 w-3"}):e.jsx(jn,{className:"h-3 w-3"}),e.jsx("span",{children:f(x,y)}),e.jsx("span",{children:"·"}),e.jsx(Ks,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:x.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:x.subject}),(()=>{const b=x.body||"",j=/<\/?[a-z][\s\S]*>/i.test(b),N=j?b.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():b;return _?j?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:b}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:b}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:N})})(),x.body&&x.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:_?"Show less":"Show full email"})]})})]},x.id)})]})}),e.jsxs(fn,{className:"border-t p-4 shrink-0",children:[e.jsx(q,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!u.is_starter&&i&&e.jsxs(q,{variant:"secondary",onClick:()=>i(u.id),children:[e.jsx(Ua,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),u.is_starter&&e.jsxs(q,{onClick:()=>n(u.id),disabled:a,children:[a?e.jsx(ls,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(si,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}function nZs(){const s=xa(),t=qr(),{isGmailConnected:r,gmailEmail:n,isLoading:a}=Cm(),{data:i,isLoading:l}=GYs(),{data:o,isLoading:c}=WYs(),d=KYs(),u=YYs(),m=ZYs(),f=XYs(),[x,y]=k.useState(null),[_,b]=k.useState(null),j=(i==null?void 0:i.filter(O=>!O.is_starter&&O.owner_user_id===s))||[],N=(i==null?void 0:i.filter(O=>O.is_starter))||[],C=O=>j.filter(B=>B.stage_id===O),A=async O=>{try{await u.mutateAsync({id:O.id,is_enabled:!O.is_enabled}),he.success(O.is_enabled?"Drip disabled":"Drip enabled")}catch{he.error("Failed to update")}},E=async O=>{try{const B=o==null?void 0:o.find(K=>K.id===O);await d.mutateAsync({stage_id:O,title:`${(B==null?void 0:B.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),y(O),he.success("Drip template created")}catch{he.error("Failed to create template")}},D=async O=>{try{await m.mutateAsync(O),he.success("Template deleted")}catch{he.error("Failed to delete")}},R=async O=>{if(!o||o.length===0){he.error("No pipeline stages found");return}const B=o[0].id;try{await f.mutateAsync({templateId:O,stageId:B}),he.success("Template copied to your drips!")}catch{he.error("Failed to copy template")}},F=l||c;return e.jsx(ws,{children:e.jsxs("div",{className:"container max-w-4xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zh,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(Xe,{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(HYs,{})]}),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(a2,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:"How it works"}),e.jsxs("p",{children:["When a deal moves to a new stage in your pipeline, Smart Drips automatically sends your pre-written email to the client. Nothing sends until you create a template ",e.jsx("strong",{children:"and"})," toggle it on."]})]})]}),!a&&(r?e.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(Ks,{className:"h-4 w-4 text-emerald-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsxs("p",{className:"font-medium text-foreground mb-0.5",children:["Sending from your Gmail",n?` (${n})`:""]}),e.jsx("p",{className:"text-muted-foreground",children:"Drips will send directly from your connected Gmail for the most personal feel and best deliverability."})]})]}):e.jsxs("div",{className:"bg-amber-500/5 border border-amber-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(a2,{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(q,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(Ks,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(ta,{defaultValue:"my-drips",children:[e.jsxs(ea,{className:"grid grid-cols-3 w-full max-w-lg mb-6",children:[e.jsx(rs,{value:"my-drips",children:"Stage Drips"}),e.jsxs(rs,{value:"campaigns",children:["Campaigns",e.jsx(Xe,{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(rs,{value:"starters",children:["Stage Starters",N.length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:N.length})]})]}),e.jsx(fs,{value:"campaigns",children:e.jsx(eZs,{})}),e.jsx(fs,{value:"my-drips",children:F?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(O=>e.jsx(dr,{className:"h-16 w-full rounded-xl"},O))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(zh,{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(O=>!O.is_won_stage&&!O.is_lost_stage).map(O=>{const B=C(O.id),K=x===O.id,Z=B.some(Q=>Q.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>y(K?null:O.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:O.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:O.name}),B.length>0&&e.jsxs(Xe,{variant:"outline",className:`text-[10px] ${Z?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[B.length," drip",B.length!==1?"s":"",Z&&" · Active"]}),K?e.jsx(Co,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"})]}),K&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:B.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(q,{variant:"outline",size:"sm",onClick:()=>E(O.id),disabled:d.isPending,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[B.map(Q=>e.jsx(xYe,{template:Q,isEditing:_===Q.id,onToggleEdit:()=>b(_===Q.id?null:Q.id),onToggleEnabled:()=>A(Q),onUpdate:W=>u.mutateAsync({id:Q.id,...W}),onDelete:()=>D(Q.id),userId:s||""},Q.id)),e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>E(O.id),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},O.id)}),o.filter(O=>O.is_won_stage||O.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(O=>O.is_won_stage||O.is_lost_stage).map(O=>{const B=C(O.id),K=x===O.id,Z=B.some(Q=>Q.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>y(K?null:O.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:O.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:O.name}),B.length>0&&e.jsxs(Xe,{variant:"outline",className:`text-[10px] ${Z?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[B.length," drip",B.length!==1?"s":"",Z&&" · Active"]}),K?e.jsx(Co,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"})]}),K&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:B.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(q,{variant:"outline",size:"sm",onClick:()=>E(O.id),disabled:d.isPending,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[B.map(Q=>e.jsx(xYe,{template:Q,isEditing:_===Q.id,onToggleEdit:()=>b(_===Q.id?null:Q.id),onToggleEnabled:()=>A(Q),onUpdate:W=>u.mutateAsync({id:Q.id,...W}),onDelete:()=>D(Q.id),userId:s||""},Q.id)),e.jsxs(q,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>E(O.id),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},O.id)})]})]})}),e.jsx(fs,{value:"starters",children:N.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(Ir,{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:N.map(O=>e.jsx(aZs,{template:O,onCopy:()=>R(O.id),isCopying:f.isPending},O.id))})})]})]})})}function xYe({template:s,isEditing:t,onToggleEdit:r,onToggleEnabled:n,onUpdate:a,onDelete:i,userId:l}){const[o,c]=k.useState(s.title),[d,u]=k.useState(s.subject),[m,f]=k.useState(s.body),[x,y]=k.useState(s.video_url||""),[_,b]=k.useState(s.channel),[j,N]=k.useState(s.delay_type),[C,A]=k.useState(s.delay_minutes),[E,D]=k.useState(!1),R=async()=>{D(!0);try{await a({title:o,subject:d,body:m,video_url:x||null,channel:_,delay_type:j,delay_minutes:C}),he.success("Drip saved"),r()}catch{he.error("Failed to save")}finally{D(!1)}},F=O=>{f(B=>B+O)};return e.jsxs("div",{className:"border rounded-lg bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",role:"button",onClick:r,children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.title||"Untitled drip"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.channel==="sms"?e.jsx(Ui,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Ks,{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(bn,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(Rr,{checked:s.is_enabled,onCheckedChange:n})]}),t&&e.jsxs("div",{className:"border-t p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(Ne,{value:o,onChange:O=>c(O.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(ce,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(O=>e.jsxs("button",{onClick:()=>b(O),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 ${_===O?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[O==="sms"?e.jsx(Ui,{className:"h-3 w-3"}):e.jsx(Ks,{className:"h-3 w-3"}),O==="sms"?"SMS":"Email"]},O))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ce,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>N("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:()=>N("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(jn,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),j==="scheduled"&&e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ne,{type:"number",min:1,value:C>=60?Math.round(C/60):C,onChange:O=>{const B=parseInt(O.target.value)||0;A(C>=60?B*60:B)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:C<60?C:30},{label:"Hours",mins:C>=60?C:60},{label:"Days",mins:C>=1440?C:1440}].map(O=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${O.label==="Minutes"&&C<60||O.label==="Hours"&&C>=60&&C<1440||O.label==="Days"&&C>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{O.label==="Minutes"?A(30):O.label==="Hours"?A(60):A(1440)},children:O.label},O.label))})]})]}),_==="email"&&e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(Ne,{value:d,onChange:O=>u(O.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(ce,{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:O=>{O.target.value&&F(O.target.value),O.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),QYs.map(O=>e.jsx("option",{value:O.key,children:O.label},O.key))]})]})]}),e.jsx("textarea",{value:m,onChange:O=>f(O.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(ce,{className:"text-xs font-medium",children:"Attached Video"}),x?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(bn,{className:"h-3 w-3 inline mr-1 text-primary"}),x.length>50?x.slice(0,50)+"...":x]}),e.jsx(q,{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(dIe,{onVideoReady:O=>y(O)}),e.jsx(cM,{userId:l,onSelect:O=>y(O),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(q,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const O=prompt("Paste a YouTube or Loom URL:");O&&y(O)},children:[e.jsx(tl,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(q,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(zr,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{variant:"outline",size:"sm",className:"text-xs",onClick:r,children:"Cancel"}),e.jsx(q,{size:"sm",className:"text-xs",onClick:R,disabled:E,children:E?"Saving...":"Save Drip"})]})]})]})]})}function aZs({template:s,onCopy:t,isCopying:r}){const[n,a]=k.useState(!1),i=s.body.replace(/<[^>]+>/g,""),l=s.deal_type==="buyer"?"Buyer":s.deal_type==="seller"?"Seller":null,o=s.delay_type==="instant"?"Sends instantly":s.delay_minutes>=1440?`Sends after ${Math.round(s.delay_minutes/1440)} day${Math.round(s.delay_minutes/1440)!==1?"s":""}`:s.delay_minutes>=60?`Sends after ${Math.round(s.delay_minutes/60)} hour${Math.round(s.delay_minutes/60)!==1?"s":""}`:`Sends after ${s.delay_minutes} min`;return e.jsxs("div",{className:"border rounded-xl overflow-hidden transition-all hover:shadow-sm",children:[e.jsxs("button",{onClick:()=>a(!n),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!n&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(Xe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(Ui,{className:"h-3 w-3"}):e.jsx(Ks,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(Xe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(jn,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),n?e.jsx(Co,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground ml-1"})]})]}),n&&e.jsxs("div",{className:"border-t bg-muted/10 p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Subject Line"}),e.jsx("p",{className:"text-sm font-medium",children:s.subject})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Email Body"}),e.jsx("div",{className:"text-sm text-foreground/80 bg-background rounded-lg border p-4 prose prose-sm max-w-none [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:my-0.5 [&_p]:my-2 [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:s.body}})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(q,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:r,children:[e.jsx(si,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const Ubt=()=>{const s=vc();return k.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",s.pathname)},[s.pathname]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),e.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),e.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function iZs(){return k.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(eme,{children:[e.jsx(xs,{path:"/c/:shareToken",element:e.jsx($bt,{})}),e.jsx(xs,{path:"*",element:e.jsx(Ubt,{})})]})}const kje={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function qbt({slugOverride:s}){const t=xo(),r=s||t.slug,[n,a]=k.useState("types"),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,u]=k.useState(null),[m,f]=k.useState(new Date),[x,y]=k.useState({name:"",email:"",phone:"",message:""}),[_,b]=k.useState(!1),{data:j,isLoading:N}=pt({queryKey:["public-booking-settings",r],queryFn:async()=>{const{data:W,error:te}=await U.from("agent_booking_settings").select("*").eq("slug",r).eq("is_active",!0).single();if(te)throw te;return W},enabled:!!r}),{data:C}=pt({queryKey:["public-booking-profile",j==null?void 0:j.user_id],queryFn:async()=>{const{data:W,error:te}=await U.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",j.user_id).single();if(te)throw te;return W},enabled:!!(j!=null&&j.user_id)}),{data:A=[]}=pt({queryKey:["public-booking-types",j==null?void 0:j.user_id],queryFn:async()=>{const{data:W,error:te}=await U.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(te)throw te;return W},enabled:!!(j!=null&&j.user_id)}),{data:E=[]}=pt({queryKey:["public-availability",j==null?void 0:j.user_id],queryFn:async()=>{const{data:W,error:te}=await U.from("agent_availability_slots").select("day_of_week, start_time, end_time").eq("user_id",j.user_id).eq("is_active",!0);if(te)throw te;return W},enabled:!!(j!=null&&j.user_id)}),{data:D=[]}=pt({queryKey:["public-blocked-dates",j==null?void 0:j.user_id],queryFn:async()=>{const{data:W,error:te}=await U.from("agent_blocked_dates").select("blocked_date").eq("user_id",j.user_id);if(te)throw te;return W.map(ne=>ne.blocked_date)},enabled:!!(j!=null&&j.user_id)}),{data:R=[]}=pt({queryKey:["public-existing-bookings",j==null?void 0:j.user_id,o],queryFn:async()=>{if(!o)return[];const W=As(o,"yyyy-MM-dd"),{data:te,error:ne}=await U.from("bookings").select("start_time, end_time").eq("agent_user_id",j.user_id).eq("booking_date",W).eq("status","confirmed");if(ne)throw ne;return te},enabled:!!(j!=null&&j.user_id)&&!!o}),F=k.useMemo(()=>[...new Set(E.map(W=>W.day_of_week))],[E]),O=W=>{const te=Ax(new Date),ne=Dc(te,(j==null?void 0:j.max_advance_days)||30),ae=Dc(te,0);return gS(W,ae)||xS(W,ne)||D.includes(As(W,"yyyy-MM-dd"))?!1:F.includes(W.getDay())},B=k.useMemo(()=>{if(!o||!i||!j)return[];const W=E.filter(de=>de.day_of_week===o.getDay()),te=i.duration_minutes,ne=j.buffer_minutes||0,ae=[],ue=new Date,me=(j.min_notice_hours||2)*60*60*1e3;for(const de of W){const[fe,je]=de.start_time.split(":").map(Number),[xe,Ee]=de.end_time.split(":").map(Number);let Me=h7(u7(o,fe),je);const Oe=h7(u7(o,xe),Ee);for(;vI(Me,te)<=Oe;){const Ie=As(Me,"HH:mm"),ze=As(vI(Me,te),"HH:mm");Me.getTime()-ue.getTime()>=me&&(R.some(Le=>{const $e=Le.start_time.slice(0,5),ve=Le.end_time.slice(0,5);return Ie$e})||ae.push(Ie)),Me=vI(Me,te+ne)}}return ae},[o,i,E,j,R]),K=k.useMemo(()=>{const W=m.getFullYear(),te=m.getMonth(),ne=new Date(W,te,1),ae=new Date(W,te+1,0),ue=ne.getDay(),me=[];for(let de=0;de{if(!(!i||!o||!d||!x.name||!j)){b(!0);try{const W=As(vI(h7(u7(new Date,parseInt(d.split(":")[0])),parseInt(d.split(":")[1])),i.duration_minutes),"HH:mm"),{error:te}=await U.from("bookings").insert({agent_user_id:j.user_id,booking_type_id:i.id,booking_date:As(o,"yyyy-MM-dd"),start_time:d,end_time:W,guest_name:x.name,guest_email:x.email||null,guest_phone:x.phone||null,guest_message:x.message||null});if(te)throw te;U.functions.invoke("booking-notify",{body:{agentUserId:j.user_id,guestName:x.name,guestEmail:x.email||null,guestPhone:x.phone||null,guestMessage:x.message||null,bookingTypeName:i.name,bookingDate:As(o,"yyyy-MM-dd"),startTime:d,endTime:W,durationMinutes:i.duration_minutes,meetingLink:j.meeting_link||null}}).catch(ne=>console.error("Booking notify error:",ne)),a("confirmed")}catch(W){he.error("Failed to book: "+W.message)}finally{b(!1)}}},Q=W=>{const[te,ne]=W.split(":").map(Number),ae=te>=12?"PM":"AM";return`${te%12||12}:${ne.toString().padStart(2,"0")} ${ae}`};return N?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:[C!=null&&C.avatar_url?e.jsx("img",{src:C.avatar_url,alt:(C==null?void 0:C.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(qi,{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:(C==null?void 0:C.name)||"Agent"}),(C==null?void 0:C.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:C.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(C==null?void 0:C.phone)&&e.jsxs("a",{href:`tel:${C.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(Mn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:C.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(C==null?void 0:C.email)&&e.jsxs("a",{href:`mailto:${C.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(Ks,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:C.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[n==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:A.map(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:kje[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(jn,{className:"h-3 w-3"}),W.duration_minutes,"m"]})]})})},W.id))})]}),n==="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(Aa,{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:kje[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(jn,{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:As(m,"MMMM yyyy")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>f(new Date(m.getFullYear(),m.getMonth()-1)),children:e.jsx(jl,{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:()=>f(new Date(m.getFullYear(),m.getMonth()+1)),children:e.jsx(Ia,{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)),K.map((W,te)=>{if(!W)return e.jsx("div",{},`pad-${te}`);const ne=O(W),ae=o&&pc(W,o),ue=pc(W,new Date);return e.jsx("button",{disabled:!ne,onClick:()=>{c(W),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${ae?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":ne?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${ue&&!ae?"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(xu,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:As(o,"EEEE, MMMM d")})]}),B.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(jn,{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:B.map(W=>{const te=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 ${te?"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:Q(W)},W)})}),d&&e.jsx(q,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>a("form"),children:"Continue to Details"})]})]}),n==="form"&&i&&o&&d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>a("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(Aa,{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:kje[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(xu,{className:"h-3.5 w-3.5 text-[#406E71]"}),As(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{className:"h-3.5 w-3.5 text-[#406E71]"}),Q(d)," · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(Ne,{value:x.name,onChange:W=>y({...x,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(ce,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ks,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(Ne,{type:"email",value:x.email,onChange:W=>y({...x,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(ce,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(Mn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(Ne,{type:"tel",value:x.phone,onChange:W=>y({...x,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(ce,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(pr,{value:x.message,onChange:W=>y({...x,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(q,{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:!x.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"})]}),n==="confirmed"&&e.jsxs("div",{className:"text-center space-y-5 py-6",children:[e.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),e.jsx("div",{className:"relative w-20 h-20 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:e.jsx(qn,{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 ",(C==null?void 0:C.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&&As(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[d&&Q(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."}),((C==null?void 0:C.phone)||(C==null?void 0:C.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:[(C==null?void 0:C.phone)&&e.jsxs("a",{href:`tel:${C.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(Mn,{className:"h-3.5 w-3.5"})," Call"]}),(C==null?void 0:C.email)&&e.jsxs("a",{href:`mailto:${C.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(Ks,{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(xu,{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 oZs(){const t=vc().pathname.slice(1).split("/")[0];return k.useEffect(()=>{document.body.classList.add("booking-page");const r=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("booking-page"),n.forEach(clearTimeout)}},[]),t?e.jsx(qbt,{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 lZs(){const t=vc().pathname.slice(1);return k.useEffect(()=>{document.body.classList.add("connect-page");const r=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("connect-page"),n.forEach(clearTimeout)}},[]),!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),e.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):e.jsx(Tct,{slugOverride:t})}function cZs(s){try{const t=document.createElement("canvas"),r=t.width=Math.min(s.naturalWidth,64),n=t.height=Math.min(s.naturalHeight,64),a=t.getContext("2d");if(!a)return!0;a.drawImage(s,0,0,r,n);const i=a.getImageData(0,0,r,n).data,l=[[0,0],[r-1,0],[0,n-1],[r-1,n-1],[Math.floor(r/2),0],[Math.floor(r/2),n-1],[0,Math.floor(n/2)],[r-1,Math.floor(n/2)]];for(const[o,c]of l)if(i[(c*r+o)*4+3]<250)return!0;return!1}catch{return!0}}const dZs={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function uZs({page:s,fields:t,answers:r,setAnswers:n,onSubmit:a,isSubmitting:i,renderField:l}){const o=s.accent_color||"#E8B84A",c=s.primary_color||"#0F1B3D",d=dZs[s.heading_font||"playfair"],u=s.eyebrow||null,m=s.headline_accent||null,f=Array.isArray(s.trust_pills)?s.trust_pills:[],x=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(hZs,{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,m&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{style:{color:o,fontStyle:"italic"},children:m})]})]}),s.hero_subtext&&e.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:s.hero_subtext}),s.agent_name&&e.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[s.agent_photo_url&&e.jsx("img",{src:s.agent_photo_url,alt:s.agent_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/30"}),e.jsxs("div",{className:"text-white/90",children:[e.jsx("p",{className:"font-semibold text-sm",children:s.agent_name}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[s.agent_phone&&e.jsxs("a",{href:`tel:${s.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(Mn,{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(Ks,{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:[x.map(y=>e.jsxs("div",{children:[e.jsxs(ce,{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,r,n,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"})]}),f.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:f.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 hZs({src:s}){const[t,r]=k.useState(null),n=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>r(cZs(a.currentTarget)),onError:()=>r(!0)});return t===!1?e.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:n}):e.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:n})}function mZs(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 fZs(s,t,r){const n=new Date(t),a=new Date(n.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(n)}/${i(a)}`),r&&l.searchParams.set("location",r),l.toString()}function pZs(s,t,r){const n=new Date(t),a=new Date(n.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(n)}`,`DTEND:${i(a)}`,`SUMMARY:${s}`,r?`LOCATION:${r}`:"","END:VEVENT","END:VCALENDAR"].filter(Boolean).join(`\r `);return`data:text/calendar;charset=utf-8,${encodeURIComponent(l)}`}function xZs({startsAt:s,locationName:t,address:r,title:n,accent:a}){const[i,l]=k.useState(Date.now());k.useEffect(()=>{const x=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(x)},[]);const o=new Date(s).getTime();if(!Number.isFinite(o))return null;const c=mZs(o-i),d=o-i<=0,u=new Date(s).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),m=[t,r].filter(Boolean).join(" · "),f=r?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(r)}`: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(x=>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(x.v).padStart(2,"0")}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:x.l})]},x.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(jn,{className:"h-3.5 w-3.5"})," ",u]}),m&&e.jsxs("a",{href:f||"#",target:f?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[e.jsx(Ma,{className:"h-3.5 w-3.5"})," ",m]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:fZs(n,s,m||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(vn,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:pZs(n,s,m||null),download:`${n.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(vn,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function gZs(){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 Vbt({slugOverride:s}){var K;const{slug:t}=xo(),r=s||t,[n,a]=k.useState(!1),[i,l]=k.useState({}),[o,c]=k.useState(0),[d,u]=k.useState(!1),[m,f]=k.useState(""),[x]=k.useState(()=>Date.now()),y=k.useState(()=>gZs())[0],{data:_,isLoading:b}=pt({queryKey:["public-landing-page",r],queryFn:async()=>{const{data:Z,error:Q}=await U.from("landing_pages").select("*").eq("slug",r).eq("is_published",!0).single();if(Q)throw Q;return Z},enabled:!!r}),{data:j=[]}=pt({queryKey:["public-landing-page-fields",_==null?void 0:_.id],queryFn:async()=>{const{data:Z,error:Q}=await U.from("landing_page_fields").select("*").eq("page_id",_.id).order("sort_order");if(Q)throw Q;return Z},enabled:!!(_!=null&&_.id)});k.useEffect(()=>{_!=null&&_.id&&U.from("landing_pages").update({view_count:(_.view_count||0)+1}).eq("id",_.id).then(()=>{})},[_==null?void 0:_.id]),k.useEffect(()=>{if(!(_!=null&&_.id))return;const Z=new URLSearchParams(window.location.search);U.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 N=Mt({mutationFn:async()=>{const Z=j.find(fe=>fe.field_type==="text"&&fe.label.toLowerCase().includes("name")),Q=j.find(fe=>fe.field_type==="email"),W=j.find(fe=>fe.field_type==="phone"),te=Z?String(i[Z.label]||""):null,ne=Q?String(i[Q.label]||""):null,ae=W?String(i[W.label]||""):null,ue=new URLSearchParams(window.location.search),{data:me,error:de}=await U.functions.invoke("landing-page-submit",{body:{page_id:_.id,answers:JSON.parse(JSON.stringify(i)),contact_name:te,contact_email:ne,contact_phone:ae,session_id:y,honeypot:m,rendered_at:x,utm_source:ue.get("utm_source"),utm_medium:ue.get("utm_medium"),utm_campaign:ue.get("utm_campaign"),referrer:document.referrer||null}});if(de)throw de;return me},onSuccess:Z=>{a(!0),Z!=null&&Z.redirect_url&&setTimeout(()=>{window.location.href=Z.redirect_url},1500)}}),C=Z=>{Z.preventDefault(),!(j.filter(W=>W.is_required&&!i[W.label]).length>0)&&N.mutate()};if(b)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",D=_,R=_.page_type==="lead_magnet",F=_.page_type==="just_listed"||_.page_type==="just_sold",O=Array.isArray(D.property_photos)?D.property_photos:[],B=D.lead_magnet_file_url||D.lead_magnet_external_url;if(n)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(qn,{className:"h-16 w-16 mx-auto mb-4",style:{color:A}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:R?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:_.success_message}),R&&B&&e.jsxs("a",{href:B,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(li,{className:"h-5 w-5"}),"Download ",D.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(Mn,{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(Ks,{className:"h-3 w-3"})," ",_.agent_email]})]})]})});if(F){const Z=Q=>{const W=parseFloat(Q.replace(/[^0-9.]/g,""));return isNaN(W)?Q: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&&O.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($r,{className:"h-8 w-8"})}),e.jsx("button",{onClick:Q=>{Q.stopPropagation(),c(W=>W===0?O.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(jl,{className:"h-6 w-6"})}),e.jsx("img",{src:O[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:Q=>Q.stopPropagation()}),e.jsx("button",{onClick:Q=>{Q.stopPropagation(),c(W=>W===O.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(Ia,{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," / ",O.length]})]}),O.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:D.property_status==="just_sold"?"#e74c3c":A},children:D.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),O.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),u(!0)},children:[e.jsx("img",{src:O[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(mS,{className:"h-4 w-4"})," View"]})]}):O.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:O.slice(0,2).map((Q,W)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(W),u(!0)},children:e.jsx("img",{src:Q,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:O[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),O.slice(1,5).map((Q,W)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(W+1),u(!0)},children:[e.jsx("img",{src:Q,alt:`Property ${W+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),W===3&&O.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",O.length-5," more"]})]},W))]}),O.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(mS,{className:"h-4 w-4"})," View all ",O.length," photos"]})]}),O.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:[D.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:A},children:Z(D.property_price)}),D.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(Ma,{className:"h-5 w-5 shrink-0"})," ",D.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[D.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(k0,{className:"h-5 w-5",style:{color:A}})," ",D.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),D.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(of,{className:"h-5 w-5",style:{color:A}})," ",D.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),D.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(m2,{className:"h-5 w-5",style:{color:A}})," ",Number(D.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),D.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:D.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:D.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(Mn,{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(Ks,{className:"h-3 w-3"})," ",_.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:C,className:"space-y-3",children:[j.map(Q=>e.jsxs("div",{children:[e.jsxs(ce,{className:"text-xs font-medium",children:[Q.label,Q.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Sje(Q,i,l)]},Q.id)),e.jsx(q,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:N.isPending,children:N.isPending?"Submitting...":"Submit"}),N.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"&&!R?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:m,onChange:Z=>f(Z.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(uZs,{page:_,fields:j,answers:i,setAnswers:l,onSubmit:C,isSubmitting:N.isPending,renderField:Sje}),_.page_type==="event_registration"&&((K=_.settings)==null?void 0:K.event_starts_at)&&e.jsx(xZs,{startsAt:_.settings.event_starts_at,locationName:_.settings.event_location_name,address:_.settings.event_address,title:_.hero_headline||_.title,accent:_.accent_color||_.primary_color||"#406E71"}),N.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}),R&&D.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(li,{className:"h-4 w-4"}),"Free Download: ",D.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:[R&&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(Mn,{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(Ks,{className:"h-3 w-3"})," ",_.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:C,className:"space-y-4",children:[j.map(Z=>e.jsxs("div",{children:[e.jsxs(ce,{className:"text-sm font-medium",children:[Z.label,Z.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Sje(Z,i,l)]},Z.id)),e.jsx(q,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:N.isPending,children:N.isPending?"Submitting...":R?"Get My Free Download":"Submit"}),N.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 Sje(s,t,r,n){const a=t[s.label]||"",i=Array.isArray(s.options)?s.options:[];switch(s.field_type){case"text":case"email":case"phone":return e.jsx(Ne,{type:s.field_type==="email"?"email":s.field_type==="phone"?"tel":"text",value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",className:"mt-1"});case"textarea":return e.jsx(pr,{value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(Ds,{value:String(a),onValueChange:l=>r(o=>({...o,[s.label]:l})),children:[e.jsx(Ps,{className:"mt-1",children:e.jsx(Fs,{placeholder:"Select..."})}),e.jsx(Ls,{children:i.map(l=>e.jsx(lt,{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(Ri,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(u=>u!==l);r(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(Rr,{checked:!!a,onCheckedChange:l=>r(o=>({...o,[s.label]:l?"Yes":"No"}))}),e.jsx("span",{className:"text-sm text-gray-600",children:a?"Yes":"No"})]});default:return e.jsx(Ne,{value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function yZs(){const t=vc().pathname.slice(1).split("/")[0];return k.useEffect(()=>{document.body.classList.add("landing-page-public");const r=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("landing-page-public"),n.forEach(clearTimeout)}},[]),t?e.jsx(Vbt,{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 vZs=[{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}],bar={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"},_ar={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"},gYe={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 war(s){return gYe[s]||gYe.basic}function bZs(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(r=>typeof r=="string"?{type:r,enabled:!0}:{enabled:!0,...r}):vZs,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 _Zs(){const t=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return t?t[1]:null}function wZs(){const s=_Zs(),{data:t,isLoading:r,error:n}=pt({queryKey:["lead-site",s],queryFn:async()=>{var u;if(!s)return null;const{data:a,error:i}=await U.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 U.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",a.agent_id).single();let o=null;if(a.show_team_logo)if(a.team_logo_url)o=a.team_logo_url;else{const{data:m}=await U.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",a.agent_id).limit(1).maybeSingle();m&&((u=m.teams)!=null&&u.avatar_url)&&(o=m.teams.avatar_url)}const c={id:a.id,agentId:a.agent_id,subdomainSlug:a.subdomain_slug,mlsProviderId:a.mls_provider_id,siteTitle:a.site_title,siteTagline:a.site_tagline,leadRegistrationMode:a.lead_registration_mode||"disabled",registrationTriggerCount:a.registration_trigger_count??1,themeConfig:a.theme_config||{},isActive:a.is_active,brokerageLegalName:a.brokerage_legal_name||null,brokerageLicenseNumber:a.brokerage_license_number||null,agentLicenseNumber:a.agent_license_number||null,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(m=>m&&typeof m=="object"&&m.text).map(m=>({name:String(m.name||"Client"),text:String(m.text),rating:typeof m.rating=="number"?m.rating:5,location:m.location?String(m.location):void 0})):[],seoMetaTitle:a.seo_meta_title||null,seoMetaDescription:a.seo_meta_description||null},d=bZs(a);return{siteConfig:c,themeConfig:d}},enabled:!!s,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1});return{siteConfig:(t==null?void 0:t.siteConfig)??null,themeConfig:(t==null?void 0:t.themeConfig)??null,isLoading:r,error:n,slug:s}}async function jZs(s,t){try{await U.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(r){console.warn("Lead notification failed:",r)}}const Hbt=k.createContext(null);function Yye(){const s=k.useContext(Hbt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function NZs({siteConfig:s,children:t}){const[r,n]=k.useState(null),[a,i]=k.useState(null),[l,o]=k.useState(!0);k.useEffect(()=>{const{data:{subscription:m}}=U.auth.onAuthStateChange(async(f,x)=>{const y=(x==null?void 0:x.user)??null;if(n(y),y){const{data:_}=await U.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 U.auth.getSession().then(({data:{session:f}})=>{n((f==null?void 0:f.user)??null),f!=null&&f.user?U.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",f.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:x})=>{x&&i({...x,email:f.user.email||""}),o(!1)}):o(!1)}),()=>m.unsubscribe()},[s.id]);const c=k.useCallback(async m=>{const f=m.email.toLowerCase().trim(),x=m.phone.replace(/\D/g,""),{data:y,error:_}=await U.auth.signUp({email:f,password:x,options:{data:{full_name:m.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(_){if(_.message.includes("already registered")){await d(f,x);return}throw _}if(y.user){const{error:b}=await U.from("lead_site_consumer_profiles").insert({user_id:y.user.id,lead_site_id:s.id,name:m.name.trim(),phone:m.phone.trim()});b&&console.warn("Consumer profile insert error:",b);const{error:j}=await U.from("lead_site_leads").insert({lead_site_id:s.id,name:m.name.trim(),email:f,phone:m.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),jZs(s.id,{name:m.name.trim(),email:f,phone:m.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=k.useCallback(async(m,f)=>{const x=f.replace(/\D/g,""),{error:y}=await U.auth.signInWithPassword({email:m.toLowerCase().trim(),password:x});if(y)throw y},[]),u=k.useCallback(async()=>{await U.auth.signOut(),n(null),i(null)},[]);return e.jsx(Hbt.Provider,{value:{user:r,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const kZs=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),SZs=new Set(["tomlois"]);function Gbt(s,t){var r;return s?(t==null?void 0:t.referralMode)===!0||((r=s.themeConfig)==null?void 0:r.referralMode)===!0||s.noMlsMode===!0||kZs.has(s.id||"")||SZs.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function jar(s){return`Contact ${s.split(" ")[0]||"Me"}`}function vIe({open:s,mode:t,siteConfig:r,onComplete:n,onSkip:a,theme:i="default",accentColor:l}){var Q;const{signUp:o,signIn:c}=Yye(),[d,u]=k.useState(!1),[m,f]=k.useState(""),[x,y]=k.useState(""),[_,b]=k.useState(""),[j,N]=k.useState(!1),[C,A]=k.useState(""),E=t==="required",D=i==="luxury",R=l||(D?"#c9a96e":"#2563eb"),F=((Q=r.agent)==null?void 0:Q.full_name)||"the agent",O={borderColor:`${R}66`,"--tw-ring-color":`${R}66`},B=async W=>{var ne;if(W.preventDefault(),A(""),!x.trim()||!_.trim()){A("Email and phone number are required.");return}if(!d&&!m.trim()){A("Name is required.");return}if(_.replace(/\D/g,"").length<7){A("Please enter a valid phone number.");return}N(!0);try{d?await c(x,_):await o({name:m,email:x,phone:_}),n()}catch(ae){(ne=ae==null?void 0:ae.message)!=null&&ne.includes("Invalid login")?A("Invalid email or phone number. Please try again."):A((ae==null?void 0:ae.message)||"Something went wrong. Please try again.")}finally{N(!1)}},K=D?"w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2":"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",Z=D?O:void 0;return e.jsx(vs,{open:s,onOpenChange:E?void 0:W=>{W||a()},children:e.jsxs(ys,{className:`sm:max-w-md ${D?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:E?W=>W.preventDefault():void 0,onEscapeKeyDown:E?W=>W.preventDefault():void 0,children:[e.jsxs(_s,{children:[e.jsx(bs,{className:"text-xl",style:D?{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(an,{className:D?"text-[#5f5145]":void 0,children:d?"Sign in with your email and phone number.":`Create a free account to save favorites, get alerts, and connect with ${F}.`})]}),e.jsxs("form",{onSubmit:B,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:m,onChange:W=>f(W.target.value),className:K,style:Z}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:x,onChange:W=>y(W.target.value),className:K,style:Z}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:_,onChange:W=>b(W.target.value),className:K,style:Z}),e.jsx("p",{className:`text-xs mt-1 ${D?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),C&&e.jsx("p",{className:"text-red-600 text-sm",children:C}),e.jsx("button",{type:"submit",disabled:j,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${D?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:D?{backgroundColor:R}:void 0,children: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:R},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 ${D?"text-[#7a6758] hover:text-[#201915]":"text-gray-500 hover:text-gray-700"}`,children:"Skip for now"})]}),e.jsx("p",{className:`text-xs text-center mt-1 ${D?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function bIe({siteConfig:s,pagePath:t}){const r=s.agent;if(!r)return null;const n=`https://${s.subdomainSlug}.thelocalmove.com`,i=(r.areas_served||"").split(/,|;|\|/).map(C=>C.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],u=[...new Set(d.map(C=>C.toUpperCase()))],m=s.testimonials||[],f=m.length?{"@type":"AggregateRating",ratingValue:(m.reduce((C,A)=>C+(A.rating||5),0)/m.length).toFixed(1),reviewCount:m.length,bestRating:5,worstRating:1}:void 0,x=[r.facebook_url,r.instagram_url,r.linkedin_url].filter(Boolean),y={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${n}/#agent`,name:r.full_name,url:n,image:r.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||r.avatar_url||void 0,email:r.email,telephone:r.phone||void 0,jobTitle:r.title||"Real Estate Agent",description:r.bio||`${r.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...x.length&&{sameAs:x},...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(C=>{const[A,E]=C.split(/,\s*/);return{"@type":"City",name:A,...E&&{containedInPlace:{"@type":"State",name:E}}}})},...f&&{aggregateRating:f},...m.length&&{review:m.slice(0,10).map(C=>({"@type":"Review",author:{"@type":"Person",name:C.name},reviewBody:C.text,reviewRating:{"@type":"Rating",ratingValue:C.rating||5,bestRating:5,worstRating:1},...C.location&&{locationCreated:{"@type":"Place",name:C.location}}}))}},_={"@context":"https://schema.org","@type":"Person","@id":`${n}/#person`,name:r.full_name,jobTitle:r.title||"Real Estate Agent",description:r.bio||void 0,image:r.avatar_url||void 0,url:n,email:r.email,telephone:r.phone||void 0,...x.length&&{sameAs:x},...r.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...u.length&&{hasCredential:u.map(C=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:C}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},b={"@context":"https://schema.org","@type":"WebSite","@id":`${n}/#website`,name:s.siteTitle||`${r.full_name} Real Estate`,url:n,publisher:{"@id":`${n}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${n}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},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 ${r.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${r.full_name} for buying, selling, or relocation help.`,path:"/contact"}],N={"@context":"https://schema.org","@type":"ItemList","@id":`${n}/#nav`,name:"Main Navigation",itemListElement:j.map((C,A)=>({"@type":"SiteNavigationElement",position:A+1,name:C.name,description:C.description,url:`${n}${C.path}`}))};return e.jsxs(Yo,{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(b)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(N)})]})}function Nar({items:s,siteConfig:t}){const r=`https://${t.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${r}${a.path}`}))};return e.jsx(Yo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function kar({listing:s,siteConfig:t}){var a;const r=`https://${t.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${r}/listing/${s.mlsNumber}`,image:((a=s.photos)==null?void 0:a[0])||void 0,numberOfRooms:s.bedrooms,numberOfBathroomsTotal:s.bathrooms,floorSize:s.sqft?{"@type":"QuantitativeValue",value:s.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:s.address,addressLocality:s.city,addressRegion:s.state,postalCode:s.zip},...s.latitude&&s.longitude&&{geo:{"@type":"GeoCoordinates",latitude:s.latitude,longitude:s.longitude}},offers:{"@type":"Offer",price:s.price,priceCurrency:"USD",availability:s.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...s.yearBuilt&&{yearBuilt:s.yearBuilt}};return e.jsx(Yo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function CZs({faqs:s}){if(!s.length)return null;const t={"@context":"https://schema.org","@type":"FAQPage",mainEntity:s.map(r=>({"@type":"Question",name:r.question,acceptedAnswer:{"@type":"Answer",text:r.answer}}))};return e.jsx(Yo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function Sar({title:s,description:t,publishedAt:r,imageUrl:n,slug:a,siteConfig:i}){const l=`https://${i.subdomainSlug}.thelocalmove.com`,o=i.agent,c={"@context":"https://schema.org","@type":"Article",headline:s,description:t,url:`${l}/blog/${a}`,datePublished:r,...n&&{image:n},author:o?{"@type":"Person",name:o.full_name,url:l}:void 0,publisher:{"@type":"Organization",name:i.siteTitle||(o==null?void 0:o.full_name)||"Agent",url:l}};return e.jsx(Yo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function _Ie({siteConfig:s}){var x;const t=s.agent;if(!t)return null;const r=t.full_name,n=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((x=a.split(/,|;|\|/)[0])==null?void 0:x.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)||[],m=[...new Set(u.map(y=>y.toUpperCase()))],f=[{question:`Who is ${r}?`,answer:`${r} is a ${t.title||"REALTOR®"} with ${n}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${r} serve?`,answer:`${r} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${r.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${r}?`,answer:`You can reach ${r} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...m.length?[{question:`What real estate designations does ${r} hold?`,answer:`${r} holds the following professional designations: ${m.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${r} a licensed real estate agent?`,answer:`Yes, ${r} is a fully licensed real estate professional (License #${d}) with ${n}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${r} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${r.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${r}. ${r.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(CZs,{faqs:f})}const yYe="ls_visitor_geo",TZs=1e3*60*60,Cje="lu_lc_attrib_v1",EZs=1e3*60*60*24*90;function AZs(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 MZs(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"sell":return"Sell Your Home";case"blog":return"Blog";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"dashboard":return"My Dashboard";default:return s}}async function IZs(){try{const s=localStorage.getItem(yYe);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,IZs().then(l=>{a.current=l}))},[]),k.useEffect(()=>{if(!(s!=null&&s.id))return;const l=r.pathname;if(l===n.current)return;n.current=l;const o=AZs(l),c=MZs(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,u=a.current;(async()=>{const f=new URLSearchParams(r.search),x=f.get("luc");if(x&&/^[0-9a-f-]{36}$/i.test(x)){try{localStorage.setItem(Cje,JSON.stringify({contact_id:x,ts:Date.now()}))}catch{}return x}const y=f.get("lc");if(y&&/^[0-9a-f-]{36}$/i.test(y)){const{data:_}=await U.from("listing_email_recipients").select("contact_id").eq("id",y).maybeSingle(),b=_==null?void 0:_.contact_id;if(b){try{localStorage.setItem(Cje,JSON.stringify({contact_id:b,ts:Date.now()}))}catch{}return b}}try{const _=localStorage.getItem(Cje);if(_){const b=JSON.parse(_);if(b!=null&&b.contact_id&&Date.now()-(b.ts||0){U.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,contact_id:f,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:x})=>{x&&console.error("[PageTracking] insert failed:",x.message)})})},[r.pathname,r.search,s==null?void 0:s.id,t])}const PZs=3e4;function jIe(s,t){const r=vc(),n=k.useRef(null),a=k.useRef(null),i=k.useRef(0),l=r.pathname,o=LZs(l),c=DZs(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;k.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const u=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,m=async()=>{const{data:f,error:x}=await U.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!x&&f&&(n.current=f.id,i.current>=2&&!f.notified_agent&&U.functions.invoke("lead-site-presence-notify",{body:{visitor_id:f.id,lead_site_id:s.id}}).catch(()=>{}))};return m(),a.current&&clearInterval(a.current),a.current=setInterval(m,PZs),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),k.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{n.current&&U.from("lead_site_active_visitors").delete().eq("id",n.current).then(()=>{})};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[s==null?void 0:s.id,t])}function LZs(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 DZs(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");default:return s}}const Sa=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},RZs=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=OZs},OZs=Number.MAX_SAFE_INTEGER||9007199254740991;let di=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}({}),kr=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}({}),_t=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 Jo={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},$a={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class H6{constructor(t,r=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=n}sample(t,r){const n=Math.pow(this.alpha_,t);this.estimate_=r*(1-n)+n*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class FZs{constructor(t,r,n,a=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new H6(t),this.fast_=new H6(r),this.defaultTTFB_=a,this.ttfb_=new H6(t)}update(t,r){const{slow_:n,fast_:a,ttfb_:i}=this;n.halfLife!==t&&(this.slow_=new H6(t,n.getEstimate(),n.getTotalWeight())),a.halfLife!==r&&(this.fast_=new H6(r,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new H6(t,i.getEstimate(),i.getTotalWeight()))}sample(t,r){t=Math.max(t,this.minDelayMs_);const n=8*r,a=t/1e3,i=n/a;this.fast_.sample(a,i),this.slow_.sample(a,i)}sampleTTFB(t){const r=t/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(n,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function zZs(s,t,r){return(t=$Zs(t))in s?Object.defineProperty(s,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):s[t]=r,s}function Ac(){return Ac=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):mk}function bYe(s,t,r){return t[s]?t[s].bind(t):qZs(s,r)}const VCe=qCe();function VZs(s,t,r){const n=qCe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{n[i]=bYe(i,s,r)});try{n.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return qCe()}a.forEach(i=>{VCe[i]=bYe(i,s)})}else Ac(VCe,n);return n}const fc=VCe;function US(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function HZs(s){return typeof self<"u"&&s===self.ManagedMediaSource}function Wbt(s,t){const r=Object.keys(s),n=Object.keys(t),a=r.length,i=n.length;return!a||!i||a===i&&!r.some(l=>n.indexOf(l)===-1)}function O0(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 r=s.length;let n,a,i,l="",o=0;for(;o>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:a=s[o++],l+=String.fromCharCode((n&31)<<6|a&63);break;case 14:a=s[o++],i=s[o++],l+=String.fromCharCode((n&15)<<12|(a&63)<<6|(i&63)<<0);break}}return l}function Of(s){let t="";for(let r=0;r1||a===1&&(r=this.levelkeys[n[0]])!=null&&r.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!Sa(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return oh(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const r=this.levelkeys;if(r){var n;const a=r[t];a&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=a.getDecryptData(this.sn,r))}}abortRequests(){var t,r;(t=this.loader)==null||t.abort(),(r=this.keyLoader)==null||r.abort()}setElementaryStreamInfo(t,r,n,a,i,l=!1){const{elementaryStreams:o}=this,c=o[t];if(!c){o[t]={startPTS:r,endPTS:n,startDTS:a,endDTS:i,partial:l};return}c.startPTS=Math.min(c.startPTS,r),c.endPTS=Math.max(c.endPTS,n),c.startDTS=Math.min(c.startDTS,a),c.endDTS=Math.max(c.endDTS,i)}}class KZs extends Ybt{constructor(t,r,n,a,i){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=r,this.index=a;const l=t.enumeratedString("BYTERANGE");l&&this.setByteRange(l,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function Zbt(s,t){const r=Object.getPrototypeOf(s);if(r){const n=Object.getOwnPropertyDescriptor(r,t);return n||Zbt(r,t)}}function YZs(s,t){const r=Zbt(s,t);r&&(r.enumerable=!0,Object.defineProperty(s,t,r))}const wYe=Math.pow(2,32)-1,ZZs=[].push,Xbt={video:1,audio:2,id3:3,text:4};function am(s){return String.fromCharCode.apply(null,s)}function Qbt(s,t){const r=s[t]<<8|s[t+1];return r<0?65536+r:r}function io(s,t){const r=Jbt(s,t);return r<0?4294967296+r:r}function jYe(s,t){let r=io(s,t);return r*=Math.pow(2,32),r+=io(s,t+4),r}function Jbt(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function XZs(s){const t=s.byteLength;for(let r=0;r8&&s[r+4]===109&&s[r+5]===111&&s[r+6]===111&&s[r+7]===102)return!0;r=n>1?r+n:t}return!1}function Fo(s,t){const r=[];if(!t.length)return r;const n=s.byteLength;for(let a=0;a1?a+i:n;if(l===t[0])if(t.length===1)r.push(s.subarray(a+8,o));else{const c=Fo(s.subarray(a+8,o),t.slice(1));c.length&&ZZs.apply(r,c)}a=o}return r}function QZs(s){const t=[],r=s[0];let n=8;const a=io(s,n);n+=4;let i=0,l=0;r===0?(i=io(s,n),l=io(s,n+4),n+=8):(i=jYe(s,n),l=jYe(s,n+8),n+=16),n+=2;let o=s.length+l;const c=Qbt(s,n);n+=2;for(let d=0;d>>31===1)return fc.warn("SIDX has hierarchical references (not supported)"),null;const y=io(s,u);u+=4,t.push({referenceSize:f,subsegmentDuration:y,info:{duration:y/a,start:o,end:o+f-1}}),o+=f,u+=4,n=u}return{earliestPresentationTime:i,timescale:a,version:r,referencesCount:c,references:t}}function e_t(s){const t=[],r=Fo(s,["moov","trak"]);for(let a=0;a{const i=io(a,4),l=t[i];l&&(l.default={duration:io(a,12),flags:io(a,20)})}),t}function JZs(s){const t=s.subarray(8),r=t.subarray(86),n=am(t.subarray(4,8));let a=n,i;const l=n==="enca"||n==="encv";if(l){const d=Fo(t,[n])[0].subarray(n==="enca"?28:78);Fo(d,["sinf"]).forEach(m=>{const f=Fo(m,["schm"])[0];if(f){const x=am(f.subarray(4,8));if(x==="cbcs"||x==="cenc"){const y=Fo(m,["frma"])[0];y&&(a=am(y))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Fo(r,["avcC"])[0];c&&c.length>3&&(a+="."+BV(c[1])+BV(c[2])+BV(c[3]),i=zV(o==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const c=Fo(t,[n])[0],d=Fo(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=Aje(d,u),u+=2;const m=d[u++];if(m&128&&(u+=2),m&64&&(u+=d[u++]),d[u++]!==4)break;u=Aje(d,u);const f=d[u++];if(f===64)a+="."+BV(f);else break;if(u+=12,d[u++]!==5)break;u=Aje(d,u);const x=d[u++];let y=(x&248)>>3;y===31&&(y+=1+((x&7)<<3)+((d[u]&224)>>5)),a+="."+y}break}case"hvc1":case"hev1":{const c=Fo(r,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],m=d&31,f=io(c,2),x=(d&32)>>5?"H":"L",y=c[12],_=c.subarray(6,12);a+="."+u+m,a+="."+eXs(f).toString(16).toUpperCase(),a+="."+x+y;let b="";for(let j=_.length;j--;){const N=_[j];(N||b)&&(b="."+N.toString(16).toUpperCase()+b)}a+=b}i=zV(o=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=zV(a,r)||a;break}case"vp09":{const c=Fo(r,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],m=c[6]>>4&15;a+="."+Zb(d)+"."+Zb(u)+"."+Zb(m)}break}case"av01":{const c=Fo(r,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,u=c[1]&31,m=c[2]>>>7?"H":"M",f=(c[2]&64)>>6,x=(c[2]&32)>>5,y=d===2&&f?x?12:10:f?10:8,_=(c[2]&16)>>4,b=(c[2]&8)>>3,j=(c[2]&4)>>2,N=c[2]&3;a+="."+d+"."+Zb(u)+m+"."+Zb(y)+"."+_+"."+b+j+N+"."+Zb(1)+"."+Zb(1)+"."+Zb(1)+"."+0,i=zV("dav1",r)}break}}return{codec:a,encrypted:l,supplemental:i}}function zV(s,t){const r=Fo(t,["dvvC"]),n=r.length?r[0]:Fo(t,["dvcC"])[0];if(n){const a=n[2]>>1&127,i=n[2]<<5&32|n[3]>>3&31;return s+"."+Zb(a)+"."+Zb(i)}}function eXs(s){let t=0;for(let r=0;r<32;r++)t|=(s>>r&1)<<31-r;return t>>>0}function Aje(s,t){const r=t+5;for(;s[t++]&128&&t{const i=n.subarray(8,24);i.some(l=>l!==0)||(fc.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${Of(i)} -> ${Of(r)}`),n.set(r,8))})}function sXs(s){const t=[];return t_t(s,r=>t.push(r.subarray(8,24))),t}function t_t(s,t){Fo(s,["moov","trak"]).forEach(n=>{const a=Fo(n,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=Fo(i,["enca"]);const o=l.length>0;o||(l=Fo(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);Fo(d,["sinf"]).forEach(m=>{const f=s_t(m);f&&t(f,o)})})})}function s_t(s){const t=Fo(s,["schm"])[0];if(t){const r=am(t.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=Fo(s,["schi","tenc"])[0];if(n)return n}}}function rXs(s,t,r){const n={},a=Fo(s,["moof","traf"]);for(let i=0;in[i].duration)){let i=1/0,l=0;const o=Fo(s,["sidx"]);for(let c=0;cm+f.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&Sa(l)&&Object.keys(n).forEach(c=>{n[c].duration||(n[c].duration=l*n[c].timescale-n[c].start)})}return n}function nXs(s){const t={valid:null,remainder:null},r=Fo(s,["moof"]);if(r.length<2)return t.remainder=s,t;const n=r[r.length-1];return t.valid=s.slice(0,n.byteOffset-8),t.remainder=s.slice(n.byteOffset-8),t}function dv(s,t){const r=new Uint8Array(s.length+t.length);return r.set(s),r.set(t,s.length),r}function NYe(s,t){const r=[],n=t.samples,a=t.timescale,i=t.id;let l=!1;return Fo(n,["moof"]).map(c=>{const d=c.byteOffset-8;Fo(c,["traf"]).map(m=>{const f=Fo(m,["tfdt"]).map(x=>{const y=x[0];let _=io(x,4);return y===1&&(_*=Math.pow(2,32),_+=io(x,8)),_/a})[0];return f!==void 0&&(s=f),Fo(m,["tfhd"]).map(x=>{const y=io(x,4),_=io(x,0)&16777215,b=(_&1)!==0,j=(_&2)!==0,N=(_&8)!==0;let C=0;const A=(_&16)!==0;let E=0;const D=(_&32)!==0;let R=8;y===i&&(b&&(R+=8),j&&(R+=4),N&&(C=io(x,R),R+=4),A&&(E=io(x,R),R+=4),D&&(R+=4),t.type==="video"&&(l=Zye(t.codec)),Fo(m,["trun"]).map(F=>{const O=F[0],B=io(F,0)&16777215,K=(B&1)!==0;let Z=0;const Q=(B&4)!==0,W=(B&256)!==0;let te=0;const ne=(B&512)!==0;let ae=0;const ue=(B&1024)!==0,me=(B&2048)!==0;let de=0;const fe=io(F,4);let je=8;K&&(Z=io(F,je),je+=4),Q&&(je+=4);let xe=Z+d;for(let Ee=0;Ee>1&63;return r===39||r===40}else return(t&31)===6}function SIe(s,t,r,n){const a=r_t(s);let i=0;i+=t;let l=0,o=0,c=0;for(;i=a.length)break;c=a[i++],l+=c}while(c===255);o=0;do{if(i>=a.length)break;c=a[i++],o+=c}while(c===255);const d=a.length-i;let u=i;if(od){fc.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const f=Qbt(a,u);if(u+=2,f===49){const x=io(a,u);if(u+=4,x===1195456820){const y=a[u++];if(y===3){const _=a[u++],b=31&_,j=64&_,N=j?2+b*3:0,C=new Uint8Array(N);if(j){C[0]=_;for(let A=1;A16){const m=[];for(let y=0;y<16;y++){const _=a[u++].toString(16);m.push(_.length==1?"0"+_:_),(y===3||y===5||y===7||y===9)&&m.push("-")}const f=o-16,x=new Uint8Array(f);for(let y=0;y>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=n&255,i.set(s,4),a=0,n=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return r.byteLength>0&&new DataView(l.buffer).setUint32(0,r.byteLength,!1),oXs([112,115,115,104],new Uint8Array([n,0,0,0]),s,i,a,l,r)}function cXs(s){const t=[];if(s instanceof ArrayBuffer){const r=s.byteLength;let n=0;for(;n+32>>24;if(i!==0&&i!==1)return{offset:r,size:t};const l=s.buffer,o=Of(new Uint8Array(l,r+12,16));let c=null,d=null,u=0;if(i===0)u=28;else{const f=s.getUint32(28);if(!f||n<32+f*16)return{offset:r,size:t};c=[];for(let x=0;x/\(Windows.+Firefox\//i.test(navigator.userAgent),o8={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 CIe(s,t){const r=o8[t];return!!r&&!!r[s.slice(0,4)]}function Fz(s,t,r=!0){return!s.split(",").some(n=>!TIe(n,t,r))}function TIe(s,t,r=!0){var n;const a=US(r);return(n=a==null?void 0:a.isTypeSupported(zz(s,t)))!=null?n:!1}function zz(s,t){return`${t}/mp4;codecs=${s}`}function kYe(s){if(s){const t=s.substring(0,4);return o8.video[t]}return 2}function Gpe(s){const t=n_t();return s.split(",").reduce((r,n)=>{const i=t&&Zye(n)?9:o8.video[n];return i?(i*2+r)/(r?3:2):(o8.audio[n]+r)/(r?2:1)},0)}const Mje={};function uXs(s,t=!0){if(Mje[s])return Mje[s];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;auXs(r.toLowerCase(),t))}function mXs(s,t){const r=[];if(s){const n=s.split(",");for(let a=0;a4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(SYe(s,"audio")||SYe(s,"video")))return s;if(t){const r=t.split(",");if(r.length>1){if(s){for(let n=r.length;n--;)if(r[n].substring(0,4)===s.substring(0,4))return r[n]}return r[0]}}return t||s}function SYe(s,t){return CIe(s,t)&&TIe(s,t)}function fXs(s){const t=s.split(",");for(let r=0;r2&&n[0]==="avc1"&&(t[r]=`avc1.${parseInt(n[1]).toString(16)}${("000"+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(",")}function pXs(s){if(s.startsWith("av01.")){const t=s.split("."),r=["0","111","01","01","01","0"];for(let n=t.length;n>4&&n<10;n++)t[n]=r[n-4];return t.join(".")}return s}function CYe(s){const t=US(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 HCe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const xXs={supported:!0,powerEfficient:!0,smooth:!0},gXs={supported:!1,smooth:!1,powerEfficient:!1},a_t={supported:!0,configurations:[],decodingInfoResults:[xXs]};function i_t(s,t){return{supported:!1,configurations:t,decodingInfoResults:[gXs],error:s}}function yXs(s,t,r,n,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,u=d?parseInt(d):c?1/0:2;let m=null;if(o!=null&&o.length)try{o.length===1&&o[0]?m=t.groups[o[0]].channels:m=o.reduce((f,x)=>{if(x){const y=t.groups[x];if(!y)throw new Error(`Audio track group ${x} not found`);Object.keys(y.channels).forEach(_=>{f[_]=(f[_]||0)+y.channels[_]})}return f},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(f=>Zye(f))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(n,30)||s.videoRange!=="SDR"&&s.videoRange!==r||s.bitrate>Math.max(a,8e6))||!!m&&Sa(u)&&Object.keys(m).some(f=>parseInt(f)>u)}function o_t(s,t,r,n={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!r)return Promise.resolve(a_t);const i=[],l=vXs(s),o=l.length,c=bXs(s,t,o>0),d=c.length;for(let u=o||1*d||1;u--;){const m={type:"media-source"};if(o&&(m.video=l[u%o]),d){m.audio=c[u%d];const f=m.audio.bitrate;m.video&&f&&(m.video.bitrate-=f)}i.push(m)}if(a){const u=navigator.userAgent;if(a.split(",").some(m=>Zye(m))&&n_t())return Promise.resolve(i_t(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const m=wXs(u);return n[m]||(n[m]=r.decodingInfo(u))})).then(u=>({supported:!u.some(m=>!m.supported),configurations:i,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:i,decodingInfoResults:[],error:u}))}function vXs(s){var t;const r=(t=s.videoCodec)==null?void 0:t.split(","),n=l_t(s),a=s.width||640,i=s.height||480,l=s.frameRate||30,o=s.videoRange.toLowerCase();return r?r.map(c=>{const d={contentType:zz(pXs(c),"video"),width:a,height:i,bitrate:n,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function bXs(s,t,r){var n;const a=(n=s.audioCodec)==null?void 0:n.split(","),i=l_t(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((u,m)=>{if(m.groupId===o){const f=parseFloat(m.channels||"");a.forEach(x=>{const y={contentType:zz(x,"audio"),bitrate:r?_Xs(x,i):i};f&&(y.channels=""+f),u.push(y)})}return u},l):l},[]):[]}function _Xs(s,t){if(t<=1)return 1;let r=128e3;return s==="ec-3"?r=768e3:s==="ac-3"&&(r=64e4),Math.min(t/2,r)}function l_t(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function wXs(s){let t="";const{audio:r,video:n}=s;if(n){const a=HCe(n.contentType);t+=`${a}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){const a=HCe(r.contentType);t+=`${n?"_":""}${a}_c${r.channels}`}return t}const GCe=["NONE","TYPE-0","TYPE-1",null];function jXs(s){return GCe.indexOf(s)>-1}const Kpe=["SDR","PQ","HLG"];function NXs(s){return!!s&&Kpe.indexOf(s)>-1}var fhe={No:"",Yes:"YES",v2:"v2"};function TYe(s){const{canSkipUntil:t,canSkipDateRanges:r,age:n}=s,a=n!!n).map(n=>n.substring(0,4)).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;const n=(r=t.supplemental)==null?void 0:r.videoCodec;n&&n!==t.videoCodec&&(this.codecSet+=`,${n.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return AYe(this._audioGroups,t)}hasSubtitleGroup(t){return AYe(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,r){if(r){if(t==="audio"){let n=this._audioGroups;n||(n=this._audioGroups=[]),n.indexOf(r)===-1&&n.push(r)}else if(t==="text"){let n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),n.indexOf(r)===-1&&n.push(r)}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function AYe(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function kXs(){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 SXs(s,t){let r=!1,n=[];if(s&&(r=s!=="SDR",n=[s]),t){n=t.allowedVideoRanges||Kpe.slice(0);const a=n.join("")!=="SDR"&&!t.videoCodec;r=t.preferHDR!==void 0?t.preferHDR:a&&kXs(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const CXs=s=>{const t=new WeakSet;return(r,n)=>{if(s&&(n=s(r,n)),typeof n=="object"&&n!==null){if(t.has(n))return;t.add(n)}return n}},Hc=(s,t)=>JSON.stringify(s,CXs(t));function TXs(s,t,r,n,a){const i=Object.keys(s),l=n==null?void 0:n.channels,o=n==null?void 0:n.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let u=!1,m=!1,f=1/0,x=1/0,y=1/0,_=1/0,b=0,j=[];const{preferHDR:N,allowedVideoRanges:C}=SXs(t,a);for(let F=i.length;F--;){const O=s[i[F]];u||(u=O.channels[2]>0),f=Math.min(f,O.minHeight),x=Math.min(x,O.minFramerate),y=Math.min(y,O.minBitrate),C.filter(K=>O.videoRanges[K]>0).length>0&&(m=!0)}f=Sa(f)?f:0,x=Sa(x)?x:0;const A=Math.max(1080,f),E=Math.max(30,x);y=Sa(y)?y:r,r=Math.max(y,r),m||(t=void 0);const D=i.length>1;return{codecSet:i.reduce((F,O)=>{const B=s[O];if(O===F)return F;if(j=m?C.filter(K=>B.videoRanges[K]>0):[],D){if(B.minBitrate>r)return Fb(O,`min bitrate of ${B.minBitrate} > current estimate of ${r}`),F;if(!B.hasDefaultAudio)return Fb(O,"no renditions with default or auto-select sound found"),F;if(o&&O.indexOf(o.substring(0,4))%5!==0)return Fb(O,`audio codec preference "${o}" not found`),F;if(l&&!d){if(!B.channels[l])return Fb(O,`no renditions with ${l} channel sound found (channels options: ${Object.keys(B.channels)})`),F}else if((!o||d)&&u&&B.channels[2]===0)return Fb(O,"no renditions with stereo sound found"),F;if(B.minHeight>A)return Fb(O,`min resolution of ${B.minHeight} > maximum of ${A}`),F;if(B.minFramerate>E)return Fb(O,`min framerate of ${B.minFramerate} > maximum of ${E}`),F;if(!j.some(K=>B.videoRanges[K]>0))return Fb(O,`no variants with VIDEO-RANGE of ${Hc(j)} found`),F;if(c&&O.indexOf(c.substring(0,4))%5!==0)return Fb(O,`video codec preference "${c}" not found`),F;if(B.maxScore=Gpe(F)||B.fragmentError>s[F].fragmentError)?F:(_=B.minIndex,b=B.maxScore,O)},void 0),videoRanges:j,preferHDR:N,minFramerate:x,minBitrate:y,minIndex:_}}function Fb(s,t){fc.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function c_t(s){return s.reduce((t,r)=>{let n=t.groups[r.groupId];n||(n=t.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const a=r.channels||"2";return n.channels[a]=(n.channels[a]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(t.hasDefaultAudio=!0),n.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function EXs(s,t,r,n){return s.slice(r,n+1).reduce((a,i,l)=>{if(!i.codecSet)return a;const o=i.audioGroups;let c=a[i.codecSet];c||(a[i.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:l,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,i.bitrate);const d=Math.min(i.height,i.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,i.frameRate),c.minIndex=Math.min(c.minIndex,l),c.maxScore=Math.max(c.maxScore,i.score),c.fragmentError+=i.fragmentError,c.videoRanges[i.videoRange]=(c.videoRanges[i.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const m=t.groups[u];m&&(c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?m.hasDefault:m.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(m.channels).forEach(f=>{c.channels[f]=(c.channels[f]||0)+m.channels[f]}))}),a},{})}function MYe(s){if(!s)return s;const{lang:t,assocLang:r,characteristics:n,channels:a,audioCodec:i}=s;return{lang:t,assocLang:r,characteristics:n,channels:a,audioCodec:i}}function x_(s,t,r){if("attrs"in s){const n=t.indexOf(s);if(n!==-1)return n}for(let n=0;nn.indexOf(a)===-1)}function BT(s,t){const{audioCodec:r,channels:n}=s;return(r===void 0||(t.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(t.channels||"2"))}function IXs(s,t,r,n,a){const i=t[n],o=t.reduce((f,x,y)=>{const _=x.uri;return(f[_]||(f[_]=[])).push(y),f},{})[i.uri];o.length>1&&(n=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,u=i.codecSet.substring(0,4),m=IYe(t,n,f=>{if(f.videoRange!==c||f.frameRate!==d||f.codecSet.substring(0,4)!==u)return!1;const x=f.audioGroups,y=r.filter(_=>!x||x.indexOf(_.groupId)!==-1);return x_(s,y,a)>-1});return m>-1?m:IYe(t,n,f=>{const x=f.audioGroups,y=r.filter(_=>!x||x.indexOf(_.groupId)!==-1);return x_(s,y,a)>-1})}function IYe(s,t,r){for(let n=t;n>-1;n--)if(r(s[n]))return n;for(let n=t+1;n{var n;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),u=i?i.stats:a.stats,m=i?i.duration:a.duration,f=d-u.loading.start,x=l.minAutoLevel,y=a.level,_=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||y<=x){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const b=_>-1&&_!==y,j=!!r||b;if(!j&&(c.paused||!c.playbackRate||!c.readyState))return;const N=l.mainForwardBufferInfo;if(!j&&N===null)return;const C=this.bwEstimator.getEstimateTTFB(),A=Math.abs(c.playbackRate);if(f<=Math.max(C,1e3*(m/(A*2))))return;const E=N?N.len/A:0,D=u.loading.first?u.loading.first-u.loading.start:-1,R=u.loaded&&D>-1,F=this.getBwEstimate(),O=l.levels,B=O[y],K=Math.max(u.loaded,Math.round(m*(a.bitrate||B.averageBitrate)/8));let Z=R?f-D:f;Z<1&&R&&(Z=Math.min(f,u.loaded*8/F));const Q=R?u.loaded*1e3/Z:0,W=C/1e3,te=Q?(K-u.loaded)/Q:K*8/F+W;if(te<=E)return;const ne=Q?Q*8:F,ae=((n=(r==null?void 0:r.details)||this.hls.latestLevelDetails)==null?void 0:n.live)===!0,ue=this.hls.config.abrBandWidthUpFactor;let me=Number.POSITIVE_INFINITY,de;for(de=y-1;de>x;de--){const Ee=O[de].maxBitrate,Me=!O[de].details||ae;if(me=this.getTimeToLoadFrag(W,ne,m*Ee,Me),me=te||me>m*10)return;R?this.bwEstimator.sample(f-Math.min(C,D),u.loaded):this.bwEstimator.sampleTTFB(f);const fe=O[de].maxBitrate;this.getBwEstimate()*ue>fe&&this.resetEstimator(fe);const je=this.findBestLevel(fe,x,de,0,E,1,1);je>-1&&(de=je),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: ${te.toFixed(3)} s Estimated load time for down switch fragment: ${me.toFixed(3)} s TTFB estimate: ${D|0} ms Current BW estimate: ${Sa(F)?F|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${de} @ ${fe|0} bps`),l.nextLoadLevel=l.nextAutoLevel=de,this.clearTimer();const xe=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===de&&de>0){const Ee=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${de>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${Ee.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,de>x){let Me=this.findBestLevel(this.hls.levels[x].bitrate,x,de,0,Ee,1,1);Me===-1&&(Me=x),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Me,this.resetEstimator(this.hls.levels[Me].bitrate)}}};b||te>me*2?xe():this.timer=self.setInterval(xe,me*1e3),l.trigger(_t.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 FZs(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.FRAG_LOADING,this.onFragLoading,this),t.on(_t.FRAG_LOADED,this.onFragLoaded,this),t.on(_t.FRAG_BUFFERED,this.onFragBuffered,this),t.on(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_t.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.FRAG_LOADING,this.onFragLoading,this),t.off(_t.FRAG_LOADED,this.onFragLoaded,this),t.off(_t.FRAG_BUFFERED,this.onFragBuffered,this),t.off(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_t.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(_t.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,r){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,r){const n=r.frag;if(!this.ignoreFragment(n)){if(!n.bitrateTest){var a;this.fragCurrent=n,this.partCurrent=(a=r.part)!=null?a:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,r){this.clearTimer()}onError(t,r){if(!r.fatal)switch(r.details){case kr.BUFFER_ADD_CODEC_ERROR:case kr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case kr.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:a,partCurrent:i}=this;if(n&&a&&n.sn===a.sn&&n.level===a.level){const l=performance.now(),o=i?i.stats:n.stats,c=l-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const m=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(m,d),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(t,r,n,a){const i=t+n/r,l=a?t+this.lastLevelLoadSec:0;return i+l}onLevelLoaded(t,r){const n=this.hls.config,{loading:a}=r.stats,i=a.end-a.first;Sa(i)&&(this.lastLevelLoadSec=i/1e3),r.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(r.levelInfo)}onFragLoaded(t,{frag:r,part:n}){const a=n?n.stats:r.stats;if(r.type===$a.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const i=n?n.duration:r.duration,l=this.hls.levels[r.level],o=(l.loaded?l.loaded.bytes:0)+a.loaded,c=(l.loaded?l.loaded.duration:0)+i;l.loaded={bytes:o,duration:c},l.realBitrate=Math.round(8*o/c)}if(r.bitrateTest){const i={stats:a,frag:r,part:n,id:r.type};this.onFragBuffered(_t.FRAG_BUFFERED,i),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(t,r){const{frag:n,part:a}=r,i=a!=null&&a.stats.loaded?a.stats:n.stats;if(i.aborted||this.ignoreFragment(n))return;const l=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(l,i.loaded),i.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=l/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==$a.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:r}=this.hls,n=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,i=this.findBestLevel(n,r,t,0,a,1,1);if(i>-1)return i;const l=this.hls.firstLevel,o=Math.min(Math.max(l,r),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!n||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=n&&a?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const l=this.hls.levels;if(l.length>Math.max(t,i)&&l[t].loadError<=l[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:r,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=n,o=r?r.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let u=i.abrBandWidthFactor,m=i.abrBandWidthUpFactor;if(d){const b=this.findBestLevel(c,l,a,d,0,u,m);if(b>=0)return this.rebufferNotice=-1,b}let f=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const b=this.bitrateTestDelay;b&&(f=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-b,this.info(`bitrate test took ${Math.round(1e3*b)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),u=m=1)}const x=this.findBestLevel(c,l,a,d,f,u,m);if(this.rebufferNotice!==x&&(this.rebufferNotice=x,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${x}`)),x>-1)return x;const y=n.levels[l],_=n.loadLevelObj;return _&&(y==null?void 0:y.bitrate)<_.bitrate?l:n.loadLevel}getStarvationDelay(){const t=this.hls,r=t.media;if(!r)return 1/0;const n=r&&r.playbackRate!==0?Math.abs(r.playbackRate):1,a=t.mainForwardBufferInfo;return(a?a.len:0)/n}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,r,n,a,i,l,o){var c;const d=a+i,u=this.lastLoadedFragLevel,m=u===-1?this.hls.firstLevel:u,{fragCurrent:f,partCurrent:x}=this,{levels:y,allAudioTracks:_,loadLevel:b,config:j}=this.hls;if(y.length===1)return 0;const N=y[m],C=!!((c=this.hls.latestLevelDetails)!=null&&c.live),A=b===-1||u===-1;let E,D="SDR",R=(N==null?void 0:N.frameRate)||0;const{audioPreference:F,videoPreference:O}=j,B=this.audioTracksByGroup||(this.audioTracksByGroup=c_t(_));let K=-1;if(A){if(this.firstSelection!==-1)return this.firstSelection;const ne=this.codecTiers||(this.codecTiers=EXs(y,B,r,n)),ae=TXs(ne,D,t,F,O),{codecSet:ue,videoRanges:me,minFramerate:de,minBitrate:fe,minIndex:je,preferHDR:xe}=ae;K=je,E=ue,D=xe?me[me.length-1]:me[0],R=de,t=Math.max(t,fe),this.log(`picked start tier ${Hc(ae)}`)}else E=N==null?void 0:N.codecSet,D=N==null?void 0:N.videoRange;const Z=x?x.duration:f?f.duration:0,Q=this.bwEstimator.getEstimateTTFB()/1e3,W=[];for(let ne=n;ne>=r;ne--){var te;const ae=y[ne],ue=ne>m;if(!ae)continue;if(j.useMediaCapabilities&&!ae.supportedResult&&!ae.supportedPromise){const Me=navigator.mediaCapabilities;typeof(Me==null?void 0:Me.decodingInfo)=="function"&&yXs(ae,B,D,R,t,F)?(ae.supportedPromise=o_t(ae,B,Me,this.supportedCache),ae.supportedPromise.then(Oe=>{if(!this.hls)return;ae.supportedResult=Oe;const Ie=this.hls.levels,ze=Ie.indexOf(ae);Oe.error?this.warn(`MediaCapabilities decodingInfo error: "${Oe.error}" for level ${ze} ${Hc(Oe)}`):Oe.supported?Oe.decodingInfoResults.some(Ve=>Ve.smooth===!1||Ve.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ze} not smooth or powerEfficient: ${Hc(Oe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ze} ${Hc(Oe)}`),ze>-1&&Ie.length>1&&(this.log(`Removing unsupported level ${ze}`),this.hls.removeLevel(ze),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Oe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Oe}`)})):ae.supportedResult=a_t}if((E&&ae.codecSet!==E||D&&ae.videoRange!==D||ue&&R>ae.frameRate||!ue&&R>0&&RMe.smooth===!1))&&(!A||ne!==K)){W.push(ne);continue}const me=ae.details,de=(x?me==null?void 0:me.partTarget:me==null?void 0:me.averagetargetduration)||Z;let fe;ue?fe=o*t:fe=l*t;const je=Z&&a>=Z*2&&i===0?ae.averageBitrate:ae.maxBitrate,xe=this.getTimeToLoadFrag(Q,fe,je*de,me===void 0);if(fe>=je&&(ne===u||ae.loadError===0&&ae.fragmentError===0)&&(xe<=Q||!Sa(xe)||C&&!this.bitrateTestDelay||xe${ne} adjustedbw(${Math.round(fe)})-bitrate=${Math.round(fe-je)} ttfb:${Q.toFixed(1)} avgDuration:${de.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${xe.toFixed(1)} firstSelection:${A} codecSet:${ae.codecSet} videoRange:${ae.videoRange} hls.loadLevel:${b}`)),A&&(this.firstSelection=ne),ne}}return-1}set nextAutoLevel(t){const r=this.deriveNextAutoLevel(t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}deriveNextAutoLevel(t){const{maxAutoLevel:r,minAutoLevel:n}=this.hls;return Math.min(Math.max(t,n),r)}}const d_t={search:function(s,t){let r=0,n=s.length-1,a=null,i=null;for(;r<=n;){a=(r+n)/2|0,i=s[a];const l=t(i);if(l>0)r=a+1;else if(l<0)n=a-1;else return i}return null}};function LXs(s,t,r){if(t===null||!Array.isArray(s)||!s.length||!Sa(t))return null;const n=s[0].programDateTime;if(t<(n||0))return null;const a=s[s.length-1].endProgramDateTime;if(t>=(a||0))return null;for(let i=0;i0&&o<15e-7&&(r+=15e-7),i&&s.level!==i.level&&i.end<=s.end&&(i=t[2+s.sn-t[0].sn]||null)}else r===0&&t[0].start===0&&(i=t[0]);if(i&&((!s||s.level===i.level)&&PYe(r,n,i)===0||DXs(i,s,Math.min(a,n))))return i;const l=d_t.search(t,PYe.bind(null,r,n));return l&&(l!==s||!i)?l:i}function DXs(s,t,r){if(t&&t.start===0&&t.level0){const n=t.tagList.reduce((a,i)=>(i[0]==="INF"&&(a+=parseFloat(i[1])),a),r);return s.start<=n}return!1}function PYe(s=0,t=0,r){if(r.start<=s&&r.start+r.duration>s)return 0;const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=s?1:r.start-n>s&&r.start?-1:0}function RXs(s,t,r){const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>s}function u_t(s,t,r){if(s&&s.startCC<=t&&s.endCC>=t){let n=s.fragments;const{fragmentHint:a}=s;a&&(n=n.concat(a));let i;return d_t.search(n,l=>l.cct?-1:(i=l,l.end<=r?1:l.start>r?-1:0)),i||null}return null}function Zpe(s){switch(s.details){case kr.FRAG_LOAD_TIMEOUT:case kr.KEY_LOAD_TIMEOUT:case kr.LEVEL_LOAD_TIMEOUT:case kr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function h_t(s){return s.details.startsWith("key")}function m_t(s){return h_t(s)&&!!s.frag&&!s.frag.decryptdata}function LYe(s,t){const r=Zpe(t);return s.default[`${r?"timeout":"error"}Retry`]}function EIe(s,t){const r=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(r*s.retryDelayMs,s.maxRetryDelayMs)}function DYe(s){return uc(uc({},s),{errorRetry:null,timeoutRetry:null})}function Xpe(s,t,r,n){if(!s)return!1;const a=n==null?void 0:n.code,i=t499)}function WCe(s){return s===0&&navigator.onLine===!1}var Rf={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},c0={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class FXs extends yv{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(_t.ERROR,this.onError,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(_t.ERROR,this.onError,this),t.off(_t.ERROR,this.onErrorOut,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.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)===$a.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const r=this.hls,n=r.currentLevel;return(t=r.loadLevelObj)!=null&&t.details||n===-1?r.loadLevel:n}variantHasKey(t,r){if(t){var n;if((n=t.details)!=null&&n.hasKey(r))return!0;const a=t.audioGroups;if(a)return this.hls.allAudioTracks.filter(l=>a.indexOf(l.groupId)>=0).some(l=>{var o;return(o=l.details)==null?void 0:o.hasKey(r)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,r){var n;if(r.fatal)return;const a=this.hls,i=r.context;switch(r.details){case kr.FRAG_LOAD_ERROR:case kr.FRAG_LOAD_TIMEOUT:case kr.KEY_LOAD_ERROR:case kr.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case kr.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction=RP();return}case kr.FRAG_GAP:case kr.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=Rf.SendAlternateToPenaltyBox;return}case kr.LEVEL_EMPTY_ERROR:case kr.LEVEL_PARSING_ERROR:{var l;const c=r.parent===$a.MAIN?r.level:a.loadLevel;r.details===kr.LEVEL_EMPTY_ERROR&&((l=r.context)!=null&&(l=l.levelDetails)!=null&&l.live)?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,c):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,c))}return;case kr.LEVEL_LOAD_ERROR:case kr.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.level));return;case kr.AUDIO_TRACK_LOAD_ERROR:case kr.AUDIO_TRACK_LOAD_TIMEOUT:case kr.SUBTITLE_LOAD_ERROR:case kr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===Jo.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===Jo.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,a.loadLevel),r.errorAction.action=Rf.SendAlternateToPenaltyBox,r.errorAction.flags=c0.MoveAllAlternatesMatchingHost;return}}return;case kr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.errorAction={action:Rf.SendAlternateToPenaltyBox,flags:c0.MoveAllAlternatesMatchingHDCP};return;case kr.KEY_SYSTEM_SESSION_UPDATE_FAILED:case kr.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case kr.KEY_SYSTEM_NO_SESSION:r.errorAction={action:Rf.SendAlternateToPenaltyBox,flags:c0.MoveAllAlternatesMatchingKey};return;case kr.BUFFER_ADD_CODEC_ERROR:case kr.REMUX_ALLOC_ERROR:case kr.BUFFER_APPEND_ERROR:if(!r.errorAction){var o;r.errorAction=this.getLevelSwitchAction(r,(o=r.level)!=null?o:a.loadLevel)}return;case kr.INTERNAL_EXCEPTION:case kr.BUFFER_APPENDING_ERROR:case kr.BUFFER_FULL_ERROR:case kr.LEVEL_SWITCH_ERROR:case kr.BUFFER_STALLED_ERROR:case kr.BUFFER_SEEK_OVER_HOLE:case kr.BUFFER_NUDGE_ON_STALL:r.errorAction=RP();return}r.type===di.KEY_SYSTEM_ERROR&&(r.levelRetry=!1,r.errorAction=RP())}getPlaylistRetryOrSwitchAction(t,r){const n=this.hls,a=LYe(n.config.playlistLoadPolicy,t),i=this.playlistError++;if(Xpe(a,i,Zpe(t),t.response))return{action:Rf.RetryRequest,flags:c0.None,retryConfig:a,retryCount:i};const o=this.getLevelSwitchAction(t,r);return a&&(o.retryConfig=a,o.retryCount=i),o}getFragRetryOrSwitchAction(t){const r=this.hls,n=this.getVariantLevelIndex(t.frag),a=r.levels[n],{fragLoadPolicy:i,keyLoadPolicy:l}=r.config,o=LYe(h_t(t)?l:i,t),c=r.levels.reduce((u,m)=>u+m.fragmentError,0);if(a&&(t.details!==kr.FRAG_GAP&&a.fragmentError++,!m_t(t)&&Xpe(o,c,Zpe(t),t.response)))return{action:Rf.RetryRequest,flags:c0.None,retryConfig:o,retryCount:c};const d=this.getLevelSwitchAction(t,n);return o&&(d.retryConfig=o,d.retryCount=c),d}getLevelSwitchAction(t,r){const n=this.hls;r==null&&(r=n.loadLevel);const a=this.hls.levels[r];if(a){var i,l;const d=t.details;a.loadError++,d===kr.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:m,loadLevel:f,minAutoLevel:x,maxAutoLevel:y}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const _=(i=t.frag)==null?void 0:i.type,j=(_===$a.AUDIO&&d===kr.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===kr.BUFFER_ADD_CODEC_ERROR||d===kr.BUFFER_APPEND_ERROR))&&m.some(({audioCodec:D})=>a.audioCodec!==D),C=t.sourceBufferName==="video"&&(d===kr.BUFFER_ADD_CODEC_ERROR||d===kr.BUFFER_APPEND_ERROR)&&m.some(({codecSet:D,audioCodec:R})=>a.codecSet!==D&&a.audioCodec===R),{type:A,groupId:E}=(l=t.context)!=null?l:{};for(let D=m.length;D--;){const R=(D+f)%m.length;if(R!==f&&R>=x&&R<=y&&m[R].loadError===0){var o,c;const F=m[R];if(d===kr.FRAG_GAP&&_===$a.MAIN&&t.frag){const O=m[R].details;if(O){const B=VA(t.frag,O.fragments,t.frag.start);if(B!=null&&B.gap)continue}}else{if(A===Jo.AUDIO_TRACK&&F.hasAudioGroup(E)||A===Jo.SUBTITLE_TRACK&&F.hasSubtitleGroup(E))continue;if(_===$a.AUDIO&&(o=a.audioGroups)!=null&&o.some(O=>F.hasAudioGroup(O))||_===$a.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(O=>F.hasSubtitleGroup(O))||j&&a.audioCodec===F.audioCodec||C&&a.codecSet===F.codecSet||!j&&a.codecSet!==F.codecSet)continue}u=R;break}}if(u>-1&&n.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:Rf.SendAlternateToPenaltyBox,flags:c0.None,nextAutoLevel:u}}return{action:Rf.SendAlternateToPenaltyBox,flags:c0.MoveAllAlternatesMatchingHost}}onErrorOut(t,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case Rf.DoNothing:break;case Rf.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==kr.FRAG_GAP?r.fatal=!0:/MediaSource readyState: ended/.test(r.error.message)&&(this.warn(`MediaSource ended after "${r.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(r.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const r=this.hls,n=t.errorAction;if(!n)return;const{flags:a}=n,i=n.nextAutoLevel;switch(a){case c0.None:this.switchLevel(t,i);break;case c0.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(t.frag),d=r.levels[c],u=d==null?void 0:d.attrs["HDCP-LEVEL"];if(n.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){r.maxHdcpLevel=GCe[GCe.indexOf(u)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}}case c0.MoveAllAlternatesMatchingKey:{const c=t.decryptdata;if(c){const d=this.hls.levels,u=d.length;for(let f=u;f--;)if(this.variantHasKey(d[f],c)){var l,o;this.log(`Banned key found in level ${f} (${d[f].bitrate}bps) or audio group "${(l=d[f].audioGroups)==null?void 0:l.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${Of(c.keyId||[])}`),d[f].fragmentError++,d[f].loadError++,this.log(`Removing level ${f} with key error (${t.error})`),this.hls.removeLevel(f)}const m=t.frag;if(this.hls.levels.length{const c=this.fragments[o];if(!c||l>=c.body.sn)return;if(!c.buffered&&(!c.loaded||i)){c.body.type===n&&this.removeFragment(c.body);return}const d=c.range[t];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(u=>{const m=!this.isTimeBuffered(u.startPTS,u.endPTS,r);return m&&this.removeFragment(c.body),m})}})}detectPartialFragments(t){const r=this.timeRanges;if(!r||t.frag.sn==="initSegment")return;const n=t.frag,a=G6(n),i=this.fragments[a];if(!i||i.buffered&&n.gap)return;const l=!n.relurl;Object.keys(r).forEach(o=>{const c=n.elementaryStreams[o];if(!c)return;const d=r[o],u=l||c.partial===!0;i.range[o]=this.getBufferedTimes(n,t.part,u,d)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,n),$V(i)||this.removeParts(n.sn-1,n.type)):this.removeFragment(i.body)}bufferedEnd(t,r){t.buffered=!0,(t.body.endList=r.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,r){const n=this.activePartLists[r];n&&(this.activePartLists[r]=RYe(n,a=>a.fragment.sn>=t))}fragBuffered(t,r){const n=G6(t);let a=this.fragments[n];!a&&r&&(a=this.fragments[n]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t))}getBufferedTimes(t,r,n,a){const i={time:[],partial:n},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let u=0;u=m&&c<=f){i.time.push({startPTS:Math.max(l,a.start(u)),endPTS:Math.min(o,a.end(u))});break}else if(lm){const x=Math.max(l,a.start(u)),y=Math.min(o,a.end(u));y>x&&(i.partial=!0,i.time.push({startPTS:x,endPTS:y}))}else if(o<=m)break}return i}getPartialFragment(t){let r=null,n,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const u=c[d];u&&$V(u)&&(a=u.body.start-o,i=u.body.end+o,t>=a&&t<=i&&(n=Math.min(t-a,i-t),l<=n&&(r=u.body,l=n)))}),r}isEndListAppended(t){const r=this.endListFragments[t];return r!==void 0&&(r.buffered||$V(r))}getState(t){const r=G6(t),n=this.fragments[r];return n?n.buffered?$V(n)?lm.PARTIAL:lm.OK:lm.APPENDING:lm.NOT_LOADED}isTimeBuffered(t,r,n){let a,i;for(let l=0;l=a&&r<=i)return!0;if(r<=a)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,r){if(r.frag.sn==="initSegment"||r.frag.bitrateTest)return;const n=r.frag,a=r.part?null:r,i=G6(n);this.fragments[i]={body:n,appendedPTS:null,loaded:a,buffered:!1,range:Object.create(null)}}onBufferAppended(t,r){const{frag:n,part:a,timeRanges:i,type:l}=r;if(n.sn==="initSegment")return;const o=n.type;if(a){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(a)}this.timeRanges=i;const c=i[l];this.detectEvictedFragments(l,c,o,a)}onFragBuffered(t,r){this.detectPartialFragments(r)}hasFragment(t){const r=G6(t);return!!this.fragments[r]}hasFragments(t){const{fragments:r}=this,n=Object.keys(r);if(!t)return n.length>0;for(let a=n.length;a--;){const i=r[n[a]];if((i==null?void 0:i.body.type)===t)return!0}return!1}hasParts(t){var r;return!!((r=this.activePartLists[t])!=null&&r.length)}removeFragmentsInRange(t,r,n,a,i){a&&!this.hasGaps||Object.keys(this.fragments).forEach(l=>{const o=this.fragments[l];if(!o)return;const c=o.body;c.type!==n||a&&!c.gap||c.startt&&(o.buffered||i)&&this.removeFragment(c)})}removeFragment(t){const r=G6(t);t.clearElementaryStreamInfo();const n=this.activePartLists[t.type];if(n){const a=t.sn;this.activePartLists[t.type]=RYe(n,i=>i.fragment.sn!==a)}delete this.fragments[r],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const r=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;r&&r.forEach(n=>n.clearElementaryStreamInfo())}}function $V(s){var t,r,n;return s.buffered&&!!(s.body.gap||(t=s.range.video)!=null&&t.partial||(r=s.range.audio)!=null&&r.partial||(n=s.range.audiovideo)!=null&&n.partial)}function G6(s){return`${s.type}_${s.level}_${s.sn}`}function RYe(s,t){return s.filter(r=>{const n=t(r);return n||r.clearElementaryStreamInfo(),n})}var qS={cbc:0,ctr:1};class BXs{constructor(t,r,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=n}decrypt(t,r){switch(this.aesMode){case qS.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,t);case qS.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},r,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function $Xs(s){const t=s.byteLength,r=t&&new DataView(s.buffer).getUint8(t-1);return r?s.slice(0,t-r):s}class UXs{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const r=new DataView(t),n=new Uint32Array(4);for(let a=0;a<4;a++)n[a]=r.getUint32(a*4);return n}initTable(){const t=this.sBox,r=this.invSBox,n=this.subMix,a=n[0],i=n[1],l=n[2],o=n[3],c=this.invSubMix,d=c[0],u=c[1],m=c[2],f=c[3],x=new Uint32Array(256);let y=0,_=0,b=0;for(b=0;b<256;b++)b<128?x[b]=b<<1:x[b]=b<<1^283;for(b=0;b<256;b++){let j=_^_<<1^_<<2^_<<3^_<<4;j=j>>>8^j&255^99,t[y]=j,r[j]=y;const N=x[y],C=x[N],A=x[C];let E=x[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^C*65537^N*257^y*16843008,d[j]=E<<24|E>>>8,u[j]=E<<16|E>>>16,m[j]=E<<8|E>>>24,f[j]=E,y?(y=N^x[x[x[A^N]]],_^=x[x[_]]):y=_=1}}expandKey(t){const r=this.uint8ArrayToUint32Array_(t);let n=!0,a=0;for(;a{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,r,n,a);const c=this.flush();c?i(c.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),r,n,a)}softwareDecrypt(t,r,n,a){const{currentIV:i,currentResult:l,remainderData:o}=this;if(a!==qS.cbc||r.byteLength!==16)return fc.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=dv(o,t),this.remainderData=null);const c=this.getValidChunk(t);if(!c.length)return null;i&&(n=i);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new UXs),d.expandKey(r);const u=l;return this.currentResult=d.decrypt(c.buffer,0,n),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(t,r,n,a){if(this.key!==r||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,r,n,a));this.key=r,this.fastAesKey=new qXs(this.subtle,r,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new BXs(this.subtle,new Uint8Array(n),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(fc.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,r,n,a)))}onWebCryptoError(t,r,n,a){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,r,n,a);const l=this.flush();if(l)return l.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let r=t;const n=t.length-t.length%HXs;return n!==t.length&&(r=t.slice(0,n),this.remainderData=t.slice(n)),r}logOnce(t){this.logEnabled&&(fc.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const OYe=Math.pow(2,17);class GXs{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,r){const n=t.url;if(!n)return Promise.reject(new Pj({type:di.NETWORK_ERROR,details:kr.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(y=>y[0]==="GAP")){c(zYe(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=FYe(t);t.loader=d;const m=DYe(a.fragLoadPolicy.default),f={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:OYe};t.stats=d.stats;const x={onSuccess:(y,_,b,j)=>{this.resetLoader(t,d);let N=y.data;b.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(N.slice(0,16)),N=N.slice(16)),o({frag:t,part:null,payload:N,networkDetails:j})},onError:(y,_,b,j)=>{this.resetLoader(t,d),c(new Pj({type:di.NETWORK_ERROR,details:kr.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:uc({url:n,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:b,stats:j}))},onAbort:(y,_,b)=>{this.resetLoader(t,d),c(new Pj({type:di.NETWORK_ERROR,details:kr.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:b,stats:y}))},onTimeout:(y,_,b)=>{this.resetLoader(t,d),c(new Pj({type:di.NETWORK_ERROR,details:kr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:b,stats:y}))}};r&&(x.onProgress=(y,_,b,j)=>r({frag:t,part:null,payload:b,networkDetails:j})),d.load(u,f,x)})}loadPart(t,r,n){this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap||r.gap){c(zYe(t,r));return}const d=this.loader=i?new i(a):new l(a),u=FYe(t,r);t.loader=d;const m=DYe(a.fragLoadPolicy.default),f={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:OYe};r.stats=d.stats,d.load(u,f,{onSuccess:(x,y,_,b)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,r);const j={frag:t,part:r,payload:x.data,networkDetails:b};n(j),o(j)},onError:(x,y,_,b)=>{this.resetLoader(t,d),c(new Pj({type:di.NETWORK_ERROR,details:kr.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:r,response:uc({url:u.url,data:void 0},x),error:new Error(`HTTP Error ${x.code} ${x.text}`),networkDetails:_,stats:b}))},onAbort:(x,y,_)=>{t.stats.aborted=r.stats.aborted,this.resetLoader(t,d),c(new Pj({type:di.NETWORK_ERROR,details:kr.INTERNAL_ABORTED,fatal:!1,frag:t,part:r,error:new Error("Aborted"),networkDetails:_,stats:x}))},onTimeout:(x,y,_)=>{this.resetLoader(t,d),c(new Pj({type:di.NETWORK_ERROR,details:kr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:r,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:_,stats:x}))}})})}updateStatsFromPart(t,r){const n=t.stats,a=r.stats,i=a.total;if(n.loaded+=a.loaded,i){const c=Math.round(t.duration/r.duration),d=Math.min(Math.round(n.loaded/i),c),m=(c-d)*Math.round(n.loaded/d);n.total=n.loaded+m}else n.total=Math.max(n.loaded,n.total);const l=n.loading,o=a.loading;l.start?l.first+=o.first-o.start:(l.start=o.start,l.first=o.first),l.end=o.end}resetLoader(t,r){t.loader=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}function FYe(s,t=null){const r=t||s,n={frag:s,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=r.byteRangeStartOffset,i=r.byteRangeEndOffset;if(Sa(a)&&Sa(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&WXs((l=s.decryptdata)==null?void 0:l.method)){const d=i-a;d%16&&(c=i+(16-d%16)),a!==0&&(n.resetIV=!0,o=a-16)}n.rangeStart=o,n.rangeEnd=c}return n}function zYe(s,t){const r=new Error(`GAP ${s.gap?"tag":"attribute"} found`),n={type:di.MEDIA_ERROR,details:kr.FRAG_GAP,fatal:!1,frag:s,error:r,networkDetails:null};return t&&(n.part=t),(t||s).stats.aborted=!0,new Pj(n)}function WXs(s){return s==="AES-128"||s==="AES-256"}class Pj extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class f_t extends yv{constructor(t,r){super(t,r),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class MIe{constructor(t,r,n,a=0,i=-1,l=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=UV(),this.buffering={audio:UV(),video:UV(),audiovideo:UV()},this.level=t,this.sn=r,this.id=n,this.size=a,this.part=i,this.partial=l}}function UV(){return{start:0,executeStart:0,executeEnd:0,end:0}}const BYe={length:0,start:()=>0,end:()=>0};class po{static isBuffered(t,r){if(t){const n=po.getBuffered(t);for(let a=n.length;a--;)if(r>=n.start(a)&&r<=n.end(a))return!0}return!1}static bufferedRanges(t){if(t){const r=po.getBuffered(t);return po.timeRangesToArray(r)}return[]}static timeRangesToArray(t){const r=[];for(let n=0;n1&&t.sort((u,m)=>u.start-m.start||m.end-u.end);let a=-1,i=[];if(n)for(let u=0;u=t[u].start&&r<=t[u].end&&(a=u);const m=i.length;if(m){const f=i[m-1].end;t[u].start-ff&&(i[m-1].end=t[u].end):i.push(t[u])}else i.push(t[u])}else i=t;let l=0,o,c=r,d=r;for(let u=0;u=m&&r<=f&&(a=u),r+n>=m&&r{const a=n.substring(2,n.length-1),i=r==null?void 0:r[a];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${a}"`)),n):i})}return t}function UYe(s,t,r){let n=s.variableList;n||(s.variableList=n={});let a,i;if("QUERYPARAM"in t){a=t.QUERYPARAM;try{const l=new self.URL(r).searchParams;if(l.has(a))i=l.get(a);else throw new Error(`"${a}" does not match any query parameter in URI: "${r}"`)}catch(l){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${l.message}`))}}else a=t.NAME,i=t.VALUE;a in n?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${a}"`)):n[a]=i||""}function KXs(s,t,r){const n=t.IMPORT;if(r&&n in r){let a=s.variableList;a||(s.variableList=a={}),a[n]=r[n]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const YXs=/^(\d+)x(\d+)$/,qYe=/(.+?)=(".*?"|.*?)(?:,|$)/g;class nu{constructor(t,r){typeof t=="string"&&(t=nu.parseAttrList(t,r)),Ac(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const r=parseInt(this[t],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(t){if(this[t]){let r=(this[t]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let a=0;aNumber.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,r){const n=this[t];return n?parseFloat(n):r}enumeratedString(t){return this[t]}enumeratedStringList(t,r){const n=this[t];return(n?n.split(/[ ,]+/):[]).reduce((a,i)=>(a[i.toLowerCase()]=!0,a),r)}bool(t){return this[t]==="YES"}decimalResolution(t){const r=YXs.exec(this[t]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(t,r){let n;const a={},i='"';for(qYe.lastIndex=0;(n=qYe.exec(t))!==null;){const l=n[1].trim();let o=n[2];const c=o.indexOf(i)===0&&o.lastIndexOf(i)===o.length-1;let d=!1;if(c)o=o.slice(1,-1);else switch(l){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(r&&(c||d))o=KCe(r,o);else if(!d&&!c)switch(l){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":fc.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const ZXs="com.apple.hls.interstitial";function XXs(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function QXs(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class x_t{constructor(t,r,n=0){var a;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(r==null?void 0:r.tagAnchor)||null,this.tagOrder=(a=r==null?void 0:r.tagOrder)!=null?a:n,r){const i=r.attr;for(const l in i)if(Object.prototype.hasOwnProperty.call(t,l)&&t[l]!==i[l]){fc.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=Ac(new nu({}),i,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=(r==null?void 0:r.endDate)||new Date(this.attr["END-DATE"]);Sa(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?(fc.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const r=this.duration;return r!==null?this._dateAtEnd=new Date(this._startDate.getTime()+r*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Sa(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===ZXs}get isValid(){return!!this.id&&!this._badValueForSameId&&Sa(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 JXs=10;class eQs{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const r=this.lastPartSn-t.lastPartSn,n=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!n||!!r||!this.live,this.advanced=this.endSN>t.endSN||r>0||r===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(r=>{let n=r.decryptdata;return n||(r.setKeyFormat(t.keyFormat),n=r.decryptdata),!!n&&t.matches(n)})}get hasProgramDateTime(){return this.fragments.length?Sa(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||JXs}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const r=this.lastPartIndex;if(r!==-1){for(let n=t.length;n--;)if(t[n].index>r)return t[n].index;return r}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function Qpe(s,t){return s.length===t.length?!s.some((r,n)=>r!==t[n]):!1}function VYe(s,t){return!s&&!t?!0:!s||!t?!1:Qpe(s,t)}function OP(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function IIe(s){switch(s){case"AES-128":case"AES-256":return qS.cbc;case"AES-256-CTR":return qS.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function PIe(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function YCe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function tQs(s){const t=YCe(s).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}function g_t(s){const t=function(n,a,i){const l=n[a];n[a]=n[i],n[i]=l};t(s,0,3),t(s,1,2),t(s,4,5),t(s,6,7)}function y_t(s){const t=s.split(":");let r=null;if(t[0]==="data"&&t.length===2){const n=t[1].split(";"),a=n[n.length-1].split(",");if(a.length===2){const i=a[0]==="base64",l=a[1];i?(n.splice(-1,1),r=PIe(l)):r=tQs(l)}}return r}const Jpe=typeof self<"u"?self:void 0;var uu={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},$f={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function phe(s){switch(s){case $f.FAIRPLAY:return uu.FAIRPLAY;case $f.PLAYREADY:return uu.PLAYREADY;case $f.WIDEVINE:return uu.WIDEVINE;case $f.CLEARKEY:return uu.CLEARKEY}}function Ije(s){switch(s){case uu.FAIRPLAY:return $f.FAIRPLAY;case uu.PLAYREADY:return $f.PLAYREADY;case uu.WIDEVINE:return $f.WIDEVINE;case uu.CLEARKEY:return $f.CLEARKEY}}function YO(s){const{drmSystems:t,widevineLicenseUrl:r}=s,n=t?[uu.FAIRPLAY,uu.WIDEVINE,uu.PLAYREADY,uu.CLEARKEY].filter(a=>!!t[a]):[];return!n[uu.WIDEVINE]&&r&&n.push(uu.WIDEVINE),n}const v_t=function(s){return Jpe!=null&&(s=Jpe.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function sQs(s,t,r,n){let a;switch(s){case uu.FAIRPLAY:a=["cenc","sinf"];break;case uu.WIDEVINE:case uu.PLAYREADY:a=["cenc"];break;case uu.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return rQs(a,t,r,n)}function rQs(s,t,r,n){return[{initDataTypes:s,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function nQs(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(r=>r==="persistent-license")))}function b_t(s){const t=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),n=r.substring(r.indexOf("<"),r.length),l=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(l){const o=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(o){const c=PIe(o).subarray(0,16);return g_t(c),c}}return null}let W6={};class SS{static clearKeyUriToKeyIdMap(){W6={}}static setKeyIdForUri(t,r){W6[t]=r}static addKeyIdForUri(t){const r=Object.keys(W6).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),W6[t]=n,n}constructor(t,r,n,a=[1],i=null,l){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=r,this.keyFormat=n,this.keyFormatVersions=a,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!OP(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(Kbt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Qpe(t.keyFormatVersions,this.keyFormatVersions)&&VYe(t.iv,this.iv)&&VYe(t.keyId,this.keyId)}isSupported(){if(this.method){if(OP(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case $f.FAIRPLAY:case $f.WIDEVINE:case $f.PLAYREADY:case $f.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,r){if(!this.encrypted||!this.uri)return null;if(OP(this.method)){let i=this.iv;return i||(typeof t!="number"&&(fc.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=iQs(t)),new SS(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=W6[this.uri];if(i&&!Qpe(this.keyId,i)&&SS.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=y_t(this.uri);if(n)switch(this.keyFormat){case $f.WIDEVINE:if(this.pssh=n,!this.keyId){const i=cXs(n.buffer);if(i.length){var a;const l=i[0];this.keyId=(a=l.kids)!=null&&a.length?l.kids[0]:null}}this.keyId||(this.keyId=HYe(r));break;case $f.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=lXs(i,null,n),this.keyId=b_t(n);break}default:{let i=n.subarray(0,16);if(i.length!==16){const l=new Uint8Array(16);l.set(i,16-i.length),i=l}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=aQs(r),i||(i=HYe(r),i||(i=W6[this.uri])),i&&(this.keyId=i,SS.setKeyIdForUri(this.uri,i))}return this}}function aQs(s){const t=s==null?void 0:s[$f.WIDEVINE];return t?t.keyId:null}function HYe(s){const t=s==null?void 0:s[$f.PLAYREADY];if(t){const r=y_t(t.uri);if(r)return b_t(r)}return null}function iQs(s){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=s>>8*(15-r)&255;return t}const GYe=/#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,WYe=/#EXT-X-MEDIA:(.*)/g,oQs=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pje=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),lQs=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 g_{static findGroup(t,r){for(let n=0;n0&&i.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:l.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(WYe.lastIndex=0;(a=WYe.exec(t))!==null;){const d=new nu(a[1],n),u=d.TYPE;if(u){const m=o[u],f=i[u]||[];i[u]=f;const x=d.LANGUAGE,y=d["ASSOC-LANGUAGE"],_=d.CHANNELS,b=d.CHARACTERISTICS,j=d["INSTREAM-ID"],N={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||x||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:x,url:d.URI?g_.resolve(d.URI,r):""};if(y&&(N.assocLang=y),_&&(N.channels=_),b&&(N.characteristics=b),j&&(N.instreamId=j),m!=null&&m.length){const C=g_.findGroup(m,N.groupId)||m[0];XYe(N,C,"audioCodec"),XYe(N,C,"textCodec")}f.push(N)}}return i}static parseLevelPlaylist(t,r,n,a,i,l){var o;const c={url:r},d=new eQs(r),u=d.fragments,m=[];let f=null,x=0,y=0,_=0,b=0,j=0,N=null,C=new Eje(a,c),A,E,D,R=-1,F=!1,O=null,B;if(Pje.lastIndex=0,d.m3u8=t,d.hasVariableRefs=$Ye(t),((o=Pje.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=Pje.exec(t))!==null;){F&&(F=!1,C=new Eje(a,c),C.playlistOffset=_,C.setStart(_),C.sn=x,C.cc=b,j&&(C.bitrate=j),C.level=n,f&&(C.initSegment=f,f.rawProgramDateTime&&(C.rawProgramDateTime=f.rawProgramDateTime,f.rawProgramDateTime=null),O&&(C.setByteRange(O),O=null)));const W=A[1];if(W){C.duration=parseFloat(W);const te=(" "+A[2]).slice(1);C.title=te||null,C.tagList.push(te?["INF",W,te]:["INF",W])}else if(A[3]){if(Sa(C.duration)){C.playlistOffset=_,C.setStart(_),D&&JYe(C,D,d),C.sn=x,C.level=n,C.cc=b,u.push(C);const te=(" "+A[3]).slice(1);C.relurl=KCe(d,te),ZCe(C,N,m),N=C,_+=C.duration,x++,y=0,F=!0}}else{if(A=A[0].match(lQs),!A){fc.warn("No matches on slow regex match for level playlist!");continue}for(E=1;E0&&eZe(d,te,A),x=d.startSN=parseInt(ne);break;case"SKIP":{d.skippedSegments&&wj(d,te,A);const ue=new nu(ne,d),me=ue.decimalInteger("SKIPPED-SEGMENTS");if(Sa(me)){d.skippedSegments+=me;for(let fe=me;fe--;)u.push(null);x+=me}const de=ue.enumeratedString("RECENTLY-REMOVED-DATERANGES");de&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(de.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&wj(d,te,A),d.targetduration=Math.max(parseInt(ne),1);break;case"VERSION":d.version!==null&&wj(d,te,A),d.version=parseInt(ne);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||wj(d,te,A),d.live=!1;break;case"#":(ne||ae)&&C.tagList.push(ae?[ne,ae]:[ne]);break;case"DISCONTINUITY":b++,C.tagList.push(["DIS"]);break;case"GAP":C.gap=!0,C.tagList.push([te]);break;case"BITRATE":C.tagList.push([te,ne]),j=parseInt(ne)*1e3,Sa(j)?C.bitrate=j:j=0;break;case"DATERANGE":{const ue=new nu(ne,d),me=new x_t(ue,d.dateRanges[ue.ID],d.dateRangeTagCount);d.dateRangeTagCount++,me.isValid||d.skippedSegments?d.dateRanges[me.id]=me:fc.warn(`Ignoring invalid DATERANGE tag: "${ne}"`),C.tagList.push(["EXT-X-DATERANGE",ne]);break}case"DEFINE":{{const ue=new nu(ne,d);"IMPORT"in ue?KXs(d,ue,l):UYe(d,ue,r)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?wj(d,te,A):u.length>0&&eZe(d,te,A),d.startCC=b=parseInt(ne);break;case"KEY":{const ue=KYe(ne,r,d);if(ue.isSupported()){if(ue.method==="NONE"){D=void 0;break}D||(D={});const me=D[ue.keyFormat];me!=null&&me.matches(ue)||(me&&(D=Ac({},D)),D[ue.keyFormat]=ue)}else fc.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${ne}"`);break}case"START":d.startTimeOffset=YYe(ne);break;case"MAP":{const ue=new nu(ne,d);if(C.duration){const me=new Eje(a,c);QYe(me,ue,n,D),f=me,C.initSegment=f,f.rawProgramDateTime&&!C.rawProgramDateTime&&(C.rawProgramDateTime=f.rawProgramDateTime)}else{const me=C.byteRangeEndOffset;if(me){const de=C.byteRangeStartOffset;O=`${me-de}@${de}`}else O=null;QYe(C,ue,n,D),f=C,F=!0}f.cc=b;break}case"SERVER-CONTROL":{B&&wj(d,te,A),B=new nu(ne),d.canBlockReload=B.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=B.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&B.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=B.optionalFloat("PART-HOLD-BACK",0),d.holdBack=B.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&wj(d,te,A);const ue=new nu(ne);d.partTarget=ue.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ue=d.partList;ue||(ue=d.partList=[]);const me=y>0?ue[ue.length-1]:void 0,de=y++,fe=new nu(ne,d),je=new KZs(fe,C,c,de,me);ue.push(je),C.duration+=je.duration;break}case"PRELOAD-HINT":{const ue=new nu(ne,d);d.preloadHint=ue;break}case"RENDITION-REPORT":{const ue=new nu(ne,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ue);break}default:fc.warn(`line parsed but not handled: ${A}`);break}}}N&&!N.relurl?(u.pop(),_-=N.duration,d.partList&&(d.fragmentHint=N)):d.partList&&(ZCe(C,N,m),C.cc=b,d.fragmentHint=C,D&&JYe(C,D,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const K=u.length,Z=u[0],Q=u[K-1];if(_+=d.skippedSegments*d.targetduration,_>0&&K&&Q){d.averagetargetduration=_/K;const W=Q.sn;d.endSN=W!=="initSegment"?W:0,d.live||(Q.endList=!0),R>0&&(dQs(u,R),Z&&m.unshift(Z))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,m.length&&d.dateRangeTagCount&&Z&&__t(m,d),d.endCC=b,d}}function __t(s,t){let r=s.length;if(!r)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),r++}else return;const n=s[r-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=n.ref;for(let u=r;u--;){var l;if(((l=s[u])==null?void 0:l.sn)=o||n===0){var l;const c=(((l=r[n+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=r[n].sn-s.startSN;if(d<0)return-1;const u=s.fragments;if(u.length>r.length){const f=(r[n+1]||u[u.length-1]).sn-s.startSN;for(let x=f;x>d;x--){const y=u[x].programDateTime;if(t>=y&&tn);["video","audio","text"].forEach(n=>{const a=r.filter(i=>CIe(i,n));a.length&&(t[`${n}Codec`]=a.map(i=>i.split("/")[0]).join(","),r=r.filter(i=>a.indexOf(i)===-1))}),t.unknownCodecs=r}function XYe(s,t,r){const n=t[r];n&&(s[r]=n)}function dQs(s,t){let r=s[t];for(let n=t;n--;){const a=s[n];if(!a)return;a.programDateTime=r.programDateTime-a.duration*1e3,r=a}}function ZCe(s,t,r){s.rawProgramDateTime?r.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function QYe(s,t,r,n){s.relurl=t.URI,t.BYTERANGE&&s.setByteRange(t.BYTERANGE),s.level=r,s.sn="initSegment",n&&(s.levelkeys=n),s.initSegment=null}function JYe(s,t,r){s.levelkeys=t;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==t)&&Object.keys(t).some(a=>t[a].isCommonEncryption)&&n.push(s)}function wj(s,t,r){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function eZe(s,t,r){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function Lje(s,t){const r=t.startPTS;if(Sa(r)){let n=0,a;t.sn>s.sn?(n=r-s.start,a=s):(n=s.start-r,a=t),a.duration!==n&&a.setDuration(n)}else t.sn>s.sn?s.cc===t.cc&&s.minEndPTS?t.setStart(s.start+(s.minEndPTS-s.start)):t.setStart(s.start+s.duration):t.setStart(Math.max(s.start-t.duration,0))}function w_t(s,t,r,n,a,i,l){n-r<=0&&(l.warn("Fragment should have a positive duration",t),n=r+t.duration,i=a+t.duration);let c=r,d=n;const u=t.startPTS,m=t.endPTS;if(Sa(u)){const j=Math.abs(u-r);s&&j>s.totalduration?l.warn(`media timestamps and playlist times differ by ${j}s for level ${t.level} ${s.url}`):Sa(t.deltaPTS)?t.deltaPTS=Math.max(j,t.deltaPTS):t.deltaPTS=j,c=Math.max(r,u),r=Math.min(r,u),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(n,m),n=Math.max(n,m),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const f=r-t.start;t.start!==0&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=c,t.startDTS=a,t.endPTS=n,t.minEndPTS=d,t.endDTS=i;const x=t.sn;if(!s||xs.endSN)return 0;let y;const _=x-s.startSN,b=s.fragments;for(b[_]=t,y=_;y>0;y--)Lje(b[y],b[y-1]);for(y=_;y=0;u--){const m=a[u].initSegment;if(m){n=m;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;fQs(s,t,(u,m,f,x)=>{if((!t.startCC||t.skippedSegments)&&m.cc!==u.cc){const y=u.cc-m.cc;for(let _=f;_{var m;u&&(!u.initSegment||u.initSegment.relurl===((m=n)==null?void 0:m.relurl))&&(u.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(u=>!u),t.deltaUpdateFailed){r.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=hQs(s.dateRanges,t,r));const u=s.fragments.filter(m=>m.rawProgramDateTime);if(s.hasProgramDateTime&&!t.hasProgramDateTime)for(let m=1;m{m.elementaryStreams=u.elementaryStreams,m.stats=u.stats}),i?w_t(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,r):j_t(s,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=s.driftStartTime,t.driftStart=s.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const u=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=u),t.driftEndTime=d,t.driftEnd=u}else t.driftEndTime=s.driftEndTime,t.driftEnd=s.driftEnd,t.advancedDateTime=s.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=s.requestScheduled)}function hQs(s,t,r){const{dateRanges:n,recentlyRemovedDateranges:a}=t,i=Ac({},s);a&&a.forEach(c=>{delete i[c]});const o=Object.keys(i).length;return o?(Object.keys(n).forEach(c=>{const d=i[c],u=new x_t(n[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Hc(n[c].attr)}"`)}),i):n}function mQs(s,t,r){if(s&&t){let n=0;for(let a=0,i=s.length;a<=i;a++){const l=s[a],o=t[a+n];l&&o&&l.index===o.index&&l.fragment.sn===o.fragment.sn?r(l,o):n--}}}function fQs(s,t,r){const n=t.skippedSegments,a=Math.max(s.startSN,t.startSN)-t.startSN,i=(s.fragmentHint?1:0)+(n?t.endSN:Math.min(s.endSN,t.endSN))-t.startSN,l=t.startSN-s.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=a;d<=i;d++){const u=c[l+d];let m=o[d];if(n&&!m&&u&&(m=t.fragments[d]=u),u&&m){r(u,m,d,o);const f=u.relurl,x=m.relurl;if(f&&pQs(f,x)){t.playlistParsingError=tZe(`media sequence mismatch ${m.sn}:`,s,t,u,m);return}else if(u.cc!==m.cc){t.playlistParsingError=tZe(`discontinuity sequence mismatch (${u.cc}!=${m.cc})`,s,t,u,m);return}}}}function tZe(s,t,r,n,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${r.startSN} ${r.m3u8}`)}function j_t(s,t,r=!0){const n=t.startSN+t.skippedSegments-s.startSN,a=s.fragments,i=n>=0;let l=0;if(i&&nt){const i=n[n.length-1].duration*1e3;i{var n;(n=t.details)==null||n.fragments.forEach(a=>{a.level=r,a.initSegment&&(a.initSegment.level=r)})})}function pQs(s,t){return s!==t&&t?rZe(s)!==rZe(t):!1}function rZe(s){return s.replace(/\?[^?]*$/,"")}function Z7(s,t){for(let n=0,a=s.length;ns.startCC)}function nZe(s,t){const r=s.start+t;s.startPTS=r,s.setStart(r),s.endPTS=r+s.duration}function T_t(s,t){const r=t.fragments;for(let n=0,a=r.length;n{const{config:l,fragCurrent:o,media:c,mediaBuffer:d,state:u}=this,m=c?c.currentTime:0,f=po.bufferInfo(d||c,m,l.maxBufferHole),x=!f.len;if(this.log(`Media seeking to ${Sa(m)?m.toFixed(3):m}, state: ${u}, ${x?"out of":"in"} buffer`),this.state===rn.ENDED)this.resetLoadingState();else if(o){const y=l.maxFragLookUpTolerance,_=o.start-y,b=o.start+o.duration+y;if(x||bf.end){const j=m>b;(m<_||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(m,1/0,this.playlistType,!0);const y=this.lastCurrentTime;if(m>y&&(this.lastCurrentTime=m),!this.loadingParts){const _=Math.max(f.end,m),b=this.shouldLoadParts(this.getLevelDetails(),_);b&&(this.log(`LL-Part loading ON after seeking to ${m.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=b)}}this.hls.hasEnoughToStart||(this.log(`Setting ${x?"startPosition":"nextLoadPosition"} to ${m} for seek without enough to start`),this.nextLoadPosition=m,x&&(this.startPosition=m)),x&&this.state===rn.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 GXs(t.config),this.keyLoader=n,this.fragmentTracker=r,this.config=t.config,this.decrypter=new AIe(t.config)}registerListeners(){const{hls:t}=this;t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_t.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===rn.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=rn.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:r}=this;return r===-1&&t?t:r}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,r){if(r.live||!this.media)return!1;const n=t.end||0,a=this.config.timelineOffset||0;if(n<=a)return!1;const i=t.buffered;this.config.maxBufferHole&&i&&i.length>1&&(t=po.bufferedInfo(i,t.start,0));const l=t.nextStart;if(l&&l>a&&l{const l=i.frag;if(this.fragContextChanged(l)){this.warn(`${l.type} sn: ${l.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(l,!1,i.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(l);return}l.stats.chunkCount++,this._handleFragmentLoadProgress(i)};this._doFragLoad(t,r,n,a).then(i=>{if(!i)return;const l=this.state,o=i.frag;if(this.fragContextChanged(o)){(l===rn.FRAG_LOADING||!this.fragCurrent&&l===rn.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=rn.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(_t.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===rn.STOPPED||this.state===rn.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var r;const{fragmentTracker:n}=this;if(n.getState(t)===lm.APPENDING){const i=t.type,l=this.getFwdBufferInfo(this.mediaBuffer,i),o=Math.max(t.duration,l?l.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?t.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,t.duration))&&n.removeFragment(t)}else((r=this.mediaBuffer)==null?void 0:r.buffered.length)===0?n.removeAllFragments():n.hasParts(t.type)&&(n.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),n.getState(t)===lm.PARTIAL&&n.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const r=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const r=t.details;return(r==null?void 0:r.live)&&r.type!=="EVENT"&&(this.levelLastLoaded!==t||r.expired)}flushMainBuffer(t,r,n=null){if(!(t-r))return;const a={startOffset:t,endOffset:r,type:n};this.hls.trigger(_t.BUFFER_FLUSHING,a)}_loadInitSegment(t,r){this._doFragLoad(t,r).then(n=>{const a=n==null?void 0:n.frag;if(!a||this.fragContextChanged(a)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:a}=this,{frag:i,payload:l}=n,o=i.decryptdata;if(l&&l.byteLength>0&&o!=null&&o.key&&o.iv&&OP(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,IIe(o.method)).catch(d=>{throw a.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(_t.FRAG_DECRYPTED,{frag:i,payload:d,stats:{tstart:c,tdecrypt:u}}),n.payload=d,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===rn.STOPPED||this.state===rn.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:r}=this;if(!r)throw new Error("init load aborted, missing levels");const n=t.frag.stats;this.state!==rn.STOPPED&&(this.state=rn.IDLE),t.frag.data=new Uint8Array(t.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,r){var n,a;const i=t.tracks;if(i&&!r.encrypted&&((n=i.audio)!=null&&n.encrypted||(a=i.video)!=null&&a.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const l=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(r)} (media ${l?"attached mediaKeys: "+l.mediaKeys:"detached"})`);return this.warn(o.message),!l||l.mediaKeys?!1:(this.hls.trigger(_t.ERROR,{type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:r}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:r}=this;return!t||!r||t.sn!==r.sn||t.level!==r.level}fragBufferedComplete(t,r){const n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${r?" part: "+r.index:""} of ${this.fragInfo(t,!1,r)} > buffer:${n?yQs.toString(po.getBuffered(n)):"(detached)"})`),oh(t)){var a;if(t.type!==$a.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=rn.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=rn.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:a,partsLoaded:i}=t,l=!i||i.length===0||i.some(c=>!c),o=new MIe(n.level,n.sn,n.stats.chunkCount+1,0,a?a.index:-1,!l);r.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,r,n=null,a){var i;this.fragCurrent=t;const l=r.details;if(!this.levels||!l)throw new Error(`frag load aborted, missing level${l?"":" detail"}s`);let o=null;if(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${t.sn} of [${l.startSN}-${l.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=rn.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(f=>{if(!this.fragContextChanged(f.frag))return this.hls.trigger(_t.KEY_LOADED,f),this.state===rn.KEY_LOADING&&(this.state=rn.IDLE),f}),this.hls.trigger(_t.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(oh(t)&&(!c||t.sn!==c.sn)){const f=this.shouldLoadParts(r.details,t.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${t.sn}`),this.loadingParts=f)}if(n=Math.max(t.start,n||0),this.loadingParts&&oh(t)){const f=l.partList;if(f&&a){n>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const x=this.getNextPart(f,t,n);if(x>-1){const y=f[x];t=this.fragCurrent=y.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${y.index} (${x}/${f.length-1}) of ${this.fragInfo(t,!1,y)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=y.start+y.duration,this.state=rn.FRAG_LOADING;let _;return o?_=o.then(b=>!b||this.fragContextChanged(b.frag)?null:this.doFragPartsLoad(t,y,r,a)).catch(b=>this.handleFragLoadError(b)):_=this.doFragPartsLoad(t,y,r,a).catch(b=>this.handleFragLoadError(b)),this.hls.trigger(_t.FRAG_LOADING,{frag:t,part:y,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):_}else if(!t.url||this.loadedEndOfParts(f,n))return Promise.resolve(null)}}if(oh(t)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(d=l.partList)==null?void 0:d.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(n.toFixed(3))}`),Sa(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=rn.FRAG_LOADING;const u=this.config.progressive&&t.type!==$a.SUBTITLE;let m;return u&&o?m=o.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(t,a)).catch(f=>this.handleFragLoadError(f)):m=Promise.all([this.fragmentLoader.load(t,u?a:void 0),o]).then(([f])=>(!u&&a&&a(f),f)).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(_t.FRAG_LOADING,{frag:t,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):m}doFragPartsLoad(t,r,n,a){return new Promise((i,l)=>{var o;const c=[],d=(o=n.details)==null?void 0:o.partList,u=m=>{this.fragmentLoader.loadPart(t,m,a).then(f=>{c[m.index]=f;const x=f.part;this.hls.trigger(_t.FRAG_LOADED,f);const y=sZe(n.details,t.sn,m.index+1)||S_t(d,t.sn,m.index+1);if(y)u(y);else return i({frag:t,part:x,partsLoaded:c})}).catch(l)};u(r)})}handleFragLoadError(t){if("data"in t){const r=t.data;r.frag&&r.details===kr.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):r.frag&&r.type===di.KEY_SYSTEM_ERROR?(r.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(r.frag)):this.hls.trigger(_t.ERROR,r)}else this.hls.trigger(_t.ERROR,{type:di.OTHER_ERROR,details:kr.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const r=this.getCurrentContext(t);if(!r||this.state!==rn.PARSING){!this.fragCurrent&&this.state!==rn.STOPPED&&this.state!==rn.ERROR&&(this.state=rn.IDLE);return}const{frag:n,part:a,level:i}=r,l=self.performance.now();n.stats.parsing.end=l,a&&(a.stats.parsing.end=l);const o=this.getLevelDetails(),d=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(n,a,i,t.partial)}shouldLoadParts(t,r){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var n;const i=t.partList[0];if(i.fragment.type===$a.SUBTITLE)return!1;const l=i.end+(((n=t.fragmentHint)==null?void 0:n.duration)||0);if(r>=l){var a;if((this.hls.hasEnoughToStart?((a=this.media)==null?void 0:a.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:r,fragCurrent:n}=this,{level:a,sn:i,part:l}=t;if(!(r!=null&&r[a]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${a}. The current chunk will not be buffered.`),null;const o=r[a],c=o.details,d=l>-1?sZe(c,i,l):null,u=d?d.fragment:k_t(c,i,n);return u?(n&&n!==u&&(u.stats=n.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(t,r,n,a,i){if(this.state!==rn.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=dv(l,o)),!c.length)return;const d=this.initPTS[r.cc],u=d?-d.baseTime/d.timescale:void 0,m={type:t.type,frag:r,part:n,chunkMeta:a,offset:u,parent:r.type,data:c};if(this.hls.trigger(_t.BUFFER_APPENDING,m),t.dropped&&t.independent&&!n){if(i)return;this.flushBufferGap(r)}}flushBufferGap(t){const r=this.media;if(!r)return;if(!po.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,t.start);return}const n=r.currentTime,a=po.bufferInfo(r,n,0),i=t.duration,l=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-l,a.end-l),n+l);t.start-o>l&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,r){var n;const a=this.getLoadPosition();if(!Sa(a))return null;const l=this.lastCurrentTime>a||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,a,r,l)}getFwdBufferInfoAtPos(t,r,n,a){const i=po.bufferInfo(t,r,a);if(i.len===0&&i.nextStart!==void 0){const l=this.fragmentTracker.getBufferedFrag(r,n);if(l&&(i.nextStart<=l.end||l.gap)){const o=Math.max(Math.min(i.nextStart,l.end)-r,a);return po.bufferInfo(t,r,o)}}return i}getMaxBufferLength(t){const{config:r}=this;let n;return t?n=Math.max(8*r.maxBufferSize/t,r.maxBufferLength):n=r.maxBufferLength,Math.min(n,r.maxMaxBufferLength)}exceedsMaxBuffer(t,r,n){const a=t.nextStart;if(a&&n.start>a){const i=t.buffered;if(i){let l=t.len;const o=t.bufferedIndex;for(let c=i.length-1;c>o;c--)i[c].start=r}}return!1}reduceMaxBufferLength(t,r){const n=this.config,a=Math.max(Math.min(t-r,n.maxBufferLength),r),i=Math.max(t-r*3,n.maxMaxBufferLength/2,a);return i>=a?(n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(t,r=$a.MAIN){const n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,r):null;return n&&"fragment"in n?n.fragment:n}getNextFragment(t,r){const n=r.fragments,a=n.length;if(!a)return null;const{config:i}=this,l=r.fragmentStart,o=i.lowLatencyMode&&!!r.partList;let c=null;if(r.live){const m=i.initialLiveManifestSize;if(a=l?(b=x,j=x===f?"config":"next load start"):y!==null?(b=y,j="live edge"):(b=t,j="buffer pos"),b<_&&(b=_,j="live frag start"),b=i){const c=l.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${a}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,l}get primaryPrefetch(){if(aZe(this.config)){var t;if((t=this.hls.interstitialsManager)==null||(t=t.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,r){if(!t)return t;if(aZe(this.config)&&t.type!==$a.SUBTITLE){const n=this.hls.interstitialsManager,a=n==null?void 0:n.bufferingItem;if(a){const l=a.event;if(l){if(l.appendInPlace||Math.abs(t.start-a.start)>1||a.start===0)return null}else if(t.end<=a.start&&(r==null?void 0:r.live)===!1||t.start>a.end&&a.nextEvent&&(a.nextEvent.appendInPlace||t.start-a.end>1))return null}const i=n==null?void 0:n.playerQueue;if(i)for(let l=i.length;l--;){const o=i[l].interstitial;if(o.appendInPlace&&t.start>=o.startTime&&t.end<=o.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!t.initSegment.data&&!this.bitrateTest?t.initSegment:t}getNextPart(t,r,n){let a=-1,i=!1,l=!0;for(let o=0,c=t.length;o-1&&nn.start)return!0}return!1}getInitialLiveFragment(t){const r=t.fragments,n=this.fragPrevious;let a=null;if(n){if(t.hasProgramDateTime&&(a=LXs(r,n.endProgramDateTime,this.config.maxFragLookUpTolerance),a&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!a){const i=n.sn+1;if(i>=t.startSN&&i<=t.endSN){const l=r[i-t.startSN];n.cc===l.cc&&(a=l,this.log(`Live playlist, switching playlist, load frag with next SN: ${a.sn}`))}a||(a=u_t(t,n.cc,n.end),a&&this.log(`Live playlist, switching playlist, load frag with same CC: ${a.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(a=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return a}getFragmentAtPosition(t,r,n){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=n;const{fragmentHint:c}=n,{maxFragLookUpTolerance:d}=a,u=n.partList,m=!!(this.loadingParts&&u!=null&&u.length&&c);m&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn);let f;if(tr-d||(x=this.media)!=null&&x.paused||!this.startFragRequested?0:d;f=VA(i,l,t,_)}else f=l[l.length-1];if(f){const y=f.sn-n.startSN,_=this.fragmentTracker.getState(f);if((_===lm.OK||_===lm.PARTIAL&&f.gap)&&(i=f),i&&f.sn===i.sn&&(!m||u[0].fragment.sn>f.sn||!n.live)&&f.level===i.level){const j=l[y+1];f.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,r){let n=this.startPosition;n=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(t,r){this.transmuxer&&t.type===this.playlistType&&oh(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${r?" part "+r.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==rn.FRAG_LOADING_WAITING_RETRY)&&(this.state=rn.IDLE)}onFragmentOrKeyLoadError(t,r){var n;if(r.chunkMeta&&!r.frag){const j=this.getCurrentContext(r.chunkMeta);j&&(r.frag=j.frag)}const a=r.frag;if(!a||a.type!==t||!this.levels)return;if(this.fragContextChanged(a)){var i;this.warn(`Frag load error must match current frag to retry ${a.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const l=r.details===kr.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=r.errorAction;if(!o){this.state=rn.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:m}=o,f=!!m,x=f&&c===Rf.RetryRequest,y=f&&!o.resolved&&d===c0.MoveAllAlternatesMatchingHost,_=(n=this.hls.latestLevelDetails)==null?void 0:n.live;if(!x&&y&&oh(a)&&!a.endList&&_&&!m_t(r))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((x||y)&&u=r||n&&!WCe(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=rn.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===rn.PARSING||this.state===rn.PARSED){const r=t.frag,n=t.parent,a=this.getFwdBufferInfo(this.mediaBuffer,n),i=a&&a.len>.5;i&&this.reduceMaxBufferLength(a.len,(r==null?void 0:r.duration)||10);const l=!i;return l&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${n} buffer`),r&&(this.fragmentTracker.removeFragment(r),this.nextLoadPosition=r.start),this.resetLoadingState(),l}return!1}resetFragmentErrors(t){t===$a.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==rn.STOPPED&&(this.state=rn.IDLE)}afterBufferFlushed(t,r,n){if(!t)return;const a=po.getBuffered(t);this.fragmentTracker.detectEvictedFragments(r,a,n),this.state===rn.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==rn.STOPPED&&(this.state=rn.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,r=t?t.details:null;r!=null&&r.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(r,r.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,r,n,a){const i=n.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((c,d)=>{const u=t.elementaryStreams[d];if(u){const m=u.endPTS-u.startPTS;if(m<=0)return this.warn(`Could not parse fragment ${t.sn} ${d} duration reliably (${m})`),c||!1;const f=a?0:w_t(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(_t.LEVEL_PTS_UPDATED,{details:i,level:n,drift:f,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((n.fragmentError===0||c&&(n.fragmentError<2||t.endList))&&this.treatAsGap(t,n),c){const d=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=rn.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${r?" part: "+r.index:""} of ${this.fragInfo(t,!1,r)})`),this.hls.trigger(_t.FRAG_PARSED,{frag:t,part:r})}playlistLabel(){return this.playlistType===$a.MAIN?"level":"track"}fragInfo(t,r=!0,n){var a,i;return`${this.playlistLabel()} ${t.level} (${n?"part":"frag"}:[${((a=r&&!n?t.startPTS:(n||t).start)!=null?a:NaN).toFixed(3)}-${((i=r&&!n?t.endPTS:(n||t).end)!=null?i:NaN).toFixed(3)}]${n&&t.type==="main"?"INDEPENDENT="+(n.independent?"YES":"NO"):""}`}treatAsGap(t,r){r&&r.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const r=this._state;r!==t&&(this._state=t,this.log(`${r}->${t}`))}get state(){return this._state}}function aZe(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class A_t{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:r}=this;let n;if(t.length)t.length===1?n=t[0]:n=vQs(t,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function vQs(s,t){const r=new Uint8Array(t);let n=0;for(let a=0;a0)return s.subarray(r,r+n)}function SQs(s,t,r,n){const a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[r+2],l=i>>2&15;if(l>12){const x=new Error(`invalid ADTS sampling index:${l}`);s.emit(_t.ERROR,_t.ERROR,{type:di.MEDIA_ERROR,details:kr.FRAG_PARSING_ERROR,fatal:!0,error:x,reason:x.message});return}const o=(i>>6&3)+1,c=t[r+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,u=a[l];let m=l;(o===5||o===29)&&(m-=3);const f=[o<<3|(m&14)>>1,(m&1)<<7|c<<3];return fc.log(`manifest codec:${n}, parsed codec:${d}, channels:${c}, rate:${u} (ADTS object type:${o} sampling index:${l})`),{config:f,samplerate:u,channelCount:c,codec:d,parsedCodec:d,manifestCodec:n}}function I_t(s,t){return s[t]===255&&(s[t+1]&246)===240}function P_t(s,t){return s[t+1]&1?7:9}function OIe(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function CQs(s,t){return t+5=s.length)return!1;const n=OIe(s,t);if(n<=r)return!1;const a=t+n;return a===s.length||txe(s,a)}return!1}function L_t(s,t,r,n,a){if(!s.samplerate){const i=SQs(t,r,n,a);if(!i)return;Ac(s,i)}}function D_t(s){return 1024*9e4/s}function AQs(s,t){const r=P_t(s,t);if(t+r<=s.length){const n=OIe(s,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}function R_t(s,t,r,n,a){const i=D_t(s.samplerate),l=n+a*i,o=AQs(t,r);let c;if(o){const{frameLength:m,headerLength:f}=o,x=f+m,y=Math.max(0,r+x-t.length);y?(c=new Uint8Array(x-f),c.set(t.subarray(r+f,t.length),0)):c=t.subarray(r+f,r+x);const _={unit:c,pts:l};return y||s.samples.push(_),{sample:_,length:x,missing:y}}const d=t.length-r;return c=new Uint8Array(d),c.set(t.subarray(r,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function MQs(s,t){return RIe(s,t)&&Xye(s,t+6)+10<=s.length-t}function IQs(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Rje(s,t=0,r=1/0){return PQs(s,t,r,Uint8Array)}function PQs(s,t,r,n){const a=LQs(s);let i=1;"BYTES_PER_ELEMENT"in n&&(i=n.BYTES_PER_ELEMENT);const l=DQs(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(r,0),o));return new n(a,d,u-d)}function LQs(s){return s instanceof ArrayBuffer?s:s.buffer}function DQs(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function RQs(s){const t={key:s.type,description:"",data:"",mimeType:null,pictureType:null},r=3;if(s.size<2)return;if(s.data[0]!==r){console.log("Ignore frame with unrecognized character encoding");return}const n=s.data.subarray(1).indexOf(0);if(n===-1)return;const a=O0(Rje(s.data,1,n)),i=s.data[2+n],l=s.data.subarray(3+n).indexOf(0);if(l===-1)return;const o=O0(Rje(s.data,3+n,l));let c;return a==="-->"?c=O0(Rje(s.data,4+n+l)):c=IQs(s.data.subarray(4+n+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function OQs(s){if(s.size<2)return;const t=O0(s.data,!0),r=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:r.buffer}}function FQs(s){if(s.size<2)return;if(s.type==="TXXX"){let r=1;const n=O0(s.data.subarray(r),!0);r+=n.length+1;const a=O0(s.data.subarray(r));return{key:s.type,info:n,data:a}}const t=O0(s.data.subarray(1));return{key:s.type,info:"",data:t}}function zQs(s){if(s.type==="WXXX"){if(s.size<2)return;let r=1;const n=O0(s.data.subarray(r),!0);r+=n.length+1;const a=O0(s.data.subarray(r));return{key:s.type,info:n,data:a}}const t=O0(s.data);return{key:s.type,info:"",data:t}}function BQs(s){return s.type==="PRIV"?OQs(s):s.type[0]==="W"?zQs(s):s.type==="APIC"?RQs(s):FQs(s)}function $Qs(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),r=Xye(s,4),n=10;return{type:t,size:r,data:s.subarray(n,n+r)}}const qV=10,UQs=10;function O_t(s){let t=0;const r=[];for(;RIe(s,t);){const n=Xye(s,t+6);s[t+5]>>6&1&&(t+=qV),t+=qV;const a=t+n;for(;t+UQs0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:y0.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Sa(s))return s*90;const n=r?r.baseTime*9e4/r.timescale:0;return t*9e4+n};let VV=null;const HQs=[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],GQs=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],WQs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],KQs=[0,1,1,4];function z_t(s,t,r,n,a){if(r+24>t.length)return;const i=B_t(t,r);if(i&&r+i.frameLength<=t.length){const l=i.samplesPerFrame*9e4/i.sampleRate,o=n+a*l,c={unit:t.subarray(r,r+i.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=i.channelCount,s.samplerate=i.sampleRate,s.samples.push(c),{sample:c,length:i.frameLength,missing:0}}}function B_t(s,t){const r=s[t+1]>>3&3,n=s[t+1]>>1&3,a=s[t+2]>>4&15,i=s[t+2]>>2&3;if(r!==1&&a!==0&&a!==15&&i!==3){const l=s[t+2]>>1&1,o=s[t+3]>>6,c=r===3?3-n:n===3?3:4,d=HQs[c*14+a-1]*1e3,m=GQs[(r===3?0:r===2?1:2)*3+i],f=o===3?1:2,x=WQs[r][n],y=KQs[n],_=x*8*y,b=Math.floor(x*d/m+l)*y;if(VV===null){const C=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);VV=C?parseInt(C[1]):0}return!!VV&&VV<=87&&n===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:m,channelCount:f,frameLength:b,samplesPerFrame:_}}}function BIe(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function $_t(s,t){return t+1{let r=0,n=5;t+=n;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;n>0;){l[0]=s[t];const o=Math.min(n,8),c=8-o;i[0]=4278190080>>>24+c<>c,r=r?r<t.length||t[r]!==11||t[r+1]!==119)return-1;const i=t[r+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[r+4]&63,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(r+u>t.length)return-1;const m=t[r+6]>>5;let f=0;m===2?f+=2:(m&1&&m!==1&&(f+=2),m&4&&(f+=2));const x=(t[r+6]<<8|t[r+7])>>12-f&1,_=[2,1,2,3,3,4,4,5][m]+x,b=t[r+5]>>3,j=t[r+5]&7,N=new Uint8Array([i<<6|b<<1|j>>2,(j&3)<<6|m<<3|x<<2|c>>4,c<<4&224]),C=1536/o*9e4,A=n+a*C,E=t.subarray(r,r+u);return s.config=N,s.channelCount=_,s.samplerate=o,s.samples.push({unit:E,pts:A}),u}class QQs extends zIe{resetInitSegment(t,r,n,a){super.resetInitSegment(t,r,n,a),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:a,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const r=Uz(t,0);let n=(r==null?void 0:r.length)||0;if(r&&t[n]===11&&t[n+1]===119&&FIe(r)!==void 0&&q_t(t,n)<=16)return!1;for(let a=t.length;n{const l=iXs(i);if(JQs.test(l.schemeIdUri)){const o=oZe(l,r);let c=l.eventDuration===4294967295?Number.POSITIVE_INFINITY:l.eventDuration/l.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=l.payload;n.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:y0.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=oZe(l,r);n.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:y0.misbklv,duration:Number.POSITIVE_INFINITY})}})}return n}demuxSampleAes(t,r,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function oZe(s,t){return Sa(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class tJs{constructor(t,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new AIe(r,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,qS.cbc)}decryptAacSample(t,r,n){const a=t[r].unit;if(a.length<=16)return;const i=a.subarray(16,a.length-a.length%16),l=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(l).then(o=>{const c=new Uint8Array(o);a.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(t,r+1,n)}).catch(n)}decryptAacSamples(t,r,n){for(;;r++){if(r>=t.length){n();return}if(!(t[r].unit.length<32)&&(this.decryptAacSample(t,r,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const r=Math.floor((t.length-48)/160)*16+16,n=new Int8Array(r);let a=0;for(let i=32;i{i.data=this.getAvcDecryptedUnit(l,c),this.decrypter.isSync()||this.decryptAvcSamples(t,r,n+1,a)}).catch(a)}decryptAvcSamples(t,r,n,a){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;r++,n=0){if(r>=t.length){a();return}const i=t[r].units;for(;!(n>=i.length);n++){const l=i[n];if(!(l.data.length<=48||l.type!==1&&l.type!==5)&&(this.decryptAvcSample(t,r,n,a,l),!this.decrypter.isSync()))return}}}}class H_t{constructor(){this.VideoSample=null}createVideoSample(t,r,n){return{key:t,frame:!1,pts:r,dts:n,units:[],length:0}}getLastNalUnit(t){var r;let n=this.VideoSample,a;if((!n||n.units.length===0)&&(n=t[t.length-1]),(r=n)!=null&&r.units){const i=n.units;a=i[i.length-1]}return a}pushAccessUnit(t,r){if(t.units.length&&t.frame){if(t.pts===void 0){const n=r.samples,a=n.length;if(a){const i=n[a-1];t.pts=i.pts,t.dts=i.dts}else{r.dropped++;return}}r.samples.push(t)}}parseNALu(t,r,n){const a=r.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,u,m,f=-1,x=0;for(i===-1&&(f=0,x=this.getNALuType(r,0),i=0,c=1);c=0){const y={data:r.subarray(f,u),type:x};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=dv(y.data,r.subarray(0,u)),y.state=0))}c=0&&i>=0){const y={data:r.subarray(f,a),type:x,state:i};o.push(y)}if(o.length===0){const y=this.getLastNalUnit(t.samples);y&&(y.data=dv(y.data,r))}return t.naluState=i,o}}class X7{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,r=this.bytesAvailable,n=t.byteLength-r,a=new Uint8Array(4),i=Math.min(4,r);if(i===0)throw new Error("no bytes available");a.set(t.subarray(n,n+i)),this.word=new DataView(a.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(t){let r;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,r=t>>3,t-=r<<3,this.bytesAvailable-=r,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let r=Math.min(this.bitsAvailable,t);const n=this.word>>>32-r;if(t>32&&fc.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=r,this.bitsAvailable>0)this.word<<=r;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return r=t-r,r>0&&this.bitsAvailable?n<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class sJs extends H_t{parsePES(t,r,n,a){const i=this.parseNALu(t,n.data,a);let l=this.VideoSample,o,c=!1;n.data=null,l&&i.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(d=>{var u,m;switch(d.type){case 1:{let _=!1;o=!0;const b=d.data;if(c&&b.length>4){const j=this.readSliceType(b);(j===2||j===4||j===7||j===9)&&(_=!0)}if(_){var f;(f=l)!=null&&f.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.frame=!0,l.key=_;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,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 6:{o=!0,SIe(d.data,1,n.pts,r.samples);break}case 7:{var x,y;o=!0,c=!0;const _=d.data,b=this.readSPS(_);if(!t.sps||t.width!==b.width||t.height!==b.height||((x=t.pixelRatio)==null?void 0:x[0])!==b.pixelRatio[0]||((y=t.pixelRatio)==null?void 0:y[1])!==b.pixelRatio[1]){t.width=b.width,t.height=b.height,t.pixelRatio=b.pixelRatio,t.sps=[_];const j=_.subarray(1,4);let N="avc1.";for(let C=0;C<3;C++){let A=j[C].toString(16);A.length<2&&(A="0"+A),N+=A}t.codec=N}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,r){return t[r]&31}readSliceType(t){const r=new X7(t);return r.readUByte(),r.readUEG(),r.readUEG()}skipScalingList(t,r){let n=8,a=8,i;for(let l=0;l{var u,m;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),l.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var f;(f=l)!=null&&f.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:o=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 39:o=!0,SIe(d.data,2,n.pts,r.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=Ac(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 x=this.readSPS(d.data);t.width=x.width,t.height=x.height,t.pixelRatio=x.pixelRatio,t.codec=x.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const y in x.params)t.params[y]=x.params[y]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const x=this.readPPS(d.data);for(const y in x)t.params[y]=x[y]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,r,n){(n&&n[0]===this.initVPS||!n&&!t.length)&&t.push(r)}getNALuType(t,r){return(t[r]&126)>>>1}ebsp2rbsp(t){const r=new Uint8Array(t.byteLength);let n=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(r[n]=t[a],n++);return new Uint8Array(r.buffer,0,n)}pushAccessUnit(t,r){super.pushAccessUnit(t,r),this.initVPS&&(this.initVPS=null)}readVPS(t){const r=new X7(t);r.readUByte(),r.readUByte(),r.readBits(4),r.skipBits(2),r.readBits(6);const n=r.readBits(3),a=r.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:a}}readSPS(t){const r=new X7(this.ebsp2rbsp(t));r.readUByte(),r.readUByte(),r.readBits(4);const n=r.readBits(3);r.readBoolean();const a=r.readBits(2),i=r.readBoolean(),l=r.readBits(5),o=r.readUByte(),c=r.readUByte(),d=r.readUByte(),u=r.readUByte(),m=r.readUByte(),f=r.readUByte(),x=r.readUByte(),y=r.readUByte(),_=r.readUByte(),b=r.readUByte(),j=r.readUByte(),N=[],C=[];for(let Se=0;Se0)for(let Se=n;Se<8;Se++)r.readBits(2);for(let Se=0;Se1&&r.readEG();for(let et=0;et0&&Ze<16?(je=rt[Ze-1],xe=ct[Ze-1]):Ze===255&&(je=r.readBits(16),xe=r.readBits(16))}if(r.readBoolean()&&r.readBoolean(),r.readBoolean()&&(r.readBits(3),r.readBoolean(),r.readBoolean()&&(r.readUByte(),r.readUByte(),r.readUByte())),r.readBoolean()&&(r.readUEG(),r.readUEG()),r.readBoolean(),r.readBoolean(),r.readBoolean(),Ie=r.readBoolean(),Ie&&(r.skipUEG(),r.skipUEG(),r.skipUEG(),r.skipUEG()),r.readBoolean()&&(Me=r.readBits(32),Oe=r.readBits(32),r.readBoolean()&&r.readUEG(),r.readBoolean())){const ct=r.readBoolean(),vt=r.readBoolean();let kt=!1;(ct||vt)&&(kt=r.readBoolean(),kt&&(r.readUByte(),r.readBits(5),r.readBoolean(),r.readBits(5)),r.readBits(4),r.readBits(4),kt&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let St=0;St<=n;St++){Ee=r.readBoolean();const Yt=Ee||r.readBoolean();let es=!1;Yt?r.readEG():es=r.readBoolean();const zs=es?1:r.readUEG()+1;if(ct)for(let sr=0;sr>Se&1)<<31-Se)>>>0;let we=Qe.toString(16);return l===1&&we==="2"&&(we="6"),{codecString:`hvc1.${$e}${l}.${we}.${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:[m,f,x,y,_,b],general_level_idc:j,bit_depth:Z+8,bit_depth_luma_minus8:Z,bit_depth_chroma_minus8:Q,min_spatial_segmentation_idc:fe,chroma_format_idc:A,frame_rate:{fixed:Ee,fps:Oe/Me}},width:Ve,height:Le,pixelRatio:[je,xe]}}readPPS(t){const r=new X7(this.ebsp2rbsp(t));r.readUByte(),r.readUByte(),r.skipUEG(),r.skipUEG(),r.skipBits(2),r.skipBits(3),r.skipBits(2),r.skipUEG(),r.skipUEG(),r.skipEG(),r.skipBits(2),r.readBoolean()&&r.skipUEG(),r.skipEG(),r.skipEG(),r.skipBits(4);const a=r.readBoolean(),i=r.readBoolean();let l=1;return i&&a?l=0:i?l=3:a&&(l=2),{parallelismType:l}}matchSPS(t,r){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,r).substr(3)}}const Km=188;class fk{constructor(t,r,n,a){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=r,this.typeSupported=n,this.logger=a,this.videoParser=null}static probe(t,r){const n=fk.syncOffset(t);return n>0&&r.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(t){const r=t.length;let n=Math.min(Km*5,r-Km)+1,a=0;for(;a1&&(l===0&&o>2||c+Km>n))return l}else{if(o)return-1;break}a++}return-1}static createTrack(t,r){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Xbt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?r:void 0}}resetInitSegment(t,r,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=fk.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=fk.createTrack("audio",a),this._id3Track=fk.createTrack("id3"),this._txtTrack=fk.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:r,_id3Track:n}=this;t&&(t.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,r,n=!1,a=!1){n||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let u=l.pid,m=l.pesData,f=o.pid,x=c.pid,y=o.pesData,_=c.pesData,b=null,j=this.pmtParsed,N=this._pmtId,C=t.length;if(this.remainderData&&(t=dv(this.remainderData,t),C=t.length,this.remainderData=null),C>4;let K;if(B>1){if(K=R+5+t[R+4],K===R+Km)continue}else K=R+4;switch(O){case u:F&&(m&&(i=K6(m,this.logger))&&(this.readyVideoParser(l.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(l,d,i,!1)),m={data:[],size:0}),m&&(m.data.push(t.subarray(K,R+Km)),m.size+=R+Km-K);break;case f:if(F){if(y&&(i=K6(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(K,R+Km)),y.size+=R+Km-K);break;case x:F&&(_&&(i=K6(_,this.logger))&&this.parseID3PES(c,i),_={data:[],size:0}),_&&(_.data.push(t.subarray(K,R+Km)),_.size+=R+Km-K);break;case 0:F&&(K+=t[K]+1),N=this._pmtId=nJs(t,K);break;case N:{F&&(K+=t[K]+1);const Z=aJs(t,K,this.typeSupported,n,this.observer,this.logger);u=Z.videoPid,u>0&&(l.pid=u,l.segmentCodec=Z.segmentVideoCodec),f=Z.audioPid,f>0&&(o.pid=f,o.segmentCodec=Z.segmentAudioCodec),x=Z.id3Pid,x>0&&(c.pid=x),b!==null&&!j&&(this.logger.warn(`MPEG-TS PMT found at ${R} after unknown PID '${b}'. Backtracking to sync byte @${A} to parse all TS packets.`),b=null,R=A-188),j=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=O;break}}else E++;E>0&&JCe(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=m,o.pesData=y,c.pesData=_;const D={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(D),D}flush(){const{remainderData:t}=this;this.remainderData=null;let r;return t?r=this.demux(t,-1,!1,!0):r={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(t){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:i}=t,l=n.pesData,o=r.pesData,c=a.pesData;let d;if(l&&(d=K6(l,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,i,d,!0),n.pesData=null)):n.pesData=l,o&&(d=K6(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,d);break;case"mp3":this.parseMPEGPES(r,d);break;case"ac3":this.parseAC3PES(r,d);break}r.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;c&&(d=K6(c,this.logger))?(this.parseID3PES(a,d),a.pesData=null):a.pesData=c}demuxSampleAes(t,r,n){const a=this.demux(t,n,!0,!this.config.progressive),i=this.sampleAes=new tJs(this.observer,this.config,r);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new sJs:t==="hevc"&&(this.videoParser=new rJs))}decrypt(t,r){return new Promise(n=>{const{audioTrack:a,videoTrack:i}=t;a.samples&&a.segmentCodec==="aac"?r.decryptAacSamples(a.samples,0,()=>{i.samples?r.decryptAvcSamples(i.samples,0,0,()=>{n(t)}):n(t)}):i.samples&&r.decryptAvcSamples(i.samples,0,0,()=>{n(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,r){let n=0;const a=this.aacOverFlow;let i=r.data;if(a){this.aacOverFlow=null;const m=a.missing,f=a.sample.unit.byteLength;if(m===-1)i=dv(a.sample.unit,i);else{const x=f-m;a.sample.unit.set(i.subarray(0,m),x),t.samples.push(a.sample),n=a.missing}}let l,o;for(l=n,o=i.length;l0;)o+=c}}parseID3PES(t,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=Ac({},r,{type:this._videoTrack?y0.emsg:y0.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(n)}}function QCe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function nJs(s,t){return(s[t+10]&31)<<8|s[t+11]}function aJs(s,t,r,n,a,i){const l={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[t+1]&15)<<8|s[t+2],c=t+3+o-4,d=(s[t+10]&15)<<8|s[t+11];for(t+=12+d;t0){let f=t+5,x=m;for(;x>2;){switch(s[f]){case 106:r.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=u,l.segmentAudioCodec="ac3");break}const _=s[f+1]+2;f+=_,x-=_}}break;case 194:case 135:return JCe(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+=m+5}return l}function JCe(s,t,r,n){n.warn(`parsing error: ${t.message}`),s.emit(_t.ERROR,_t.ERROR,{type:di.MEDIA_ERROR,details:kr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Oje(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function K6(s,t){let r=0,n,a,i,l,o;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=dv(c[0],c[1]),c.splice(1,1);if(n=c[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(a=(n[4]<<8)+n[5],a&&a>s.size-6)return null;const u=n[7];u&192&&(l=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,u&64?(o=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=n[8];let m=i+9;if(s.size<=m)return null;s.size-=m;const f=new Uint8Array(s.size);for(let x=0,y=c.length;x_){m-=_;continue}else n=n.subarray(m),_-=m,m=0;f.set(n,r),r+=_}return a&&(a-=i+3),{data:f,pts:l,dts:o,len:a}}return null}class iJs{static getSilentFrame(t,r){switch(t){case"mp4a.40.2":if(r===1)return new Uint8Array([0,200,0,128,35,128]);if(r===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(r===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(r===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(r===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(r===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(r===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const qN=Math.pow(2,32)-1;class Nr{static init(){Nr.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 Nr.types)Nr.types.hasOwnProperty(t)&&(Nr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),n=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Nr.HDLR_TYPES={video:r,audio:n};const a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);Nr.STTS=Nr.STSC=Nr.STCO=i,Nr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Nr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Nr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Nr.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]);Nr.FTYP=Nr.box(Nr.types.ftyp,l,c,l,o),Nr.DINF=Nr.box(Nr.types.dinf,Nr.box(Nr.types.dref,a))}static box(t,...r){let n=8,a=r.length;const i=a;for(;a--;)n+=r[a].byteLength;const l=new Uint8Array(n);for(l[0]=n>>24&255,l[1]=n>>16&255,l[2]=n>>8&255,l[3]=n&255,l.set(t,4),a=0,n=8;a>24&255,t>>16&255,t>>8&255,t&255,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255,85,196,0,0]))}static mdia(t){return Nr.box(Nr.types.mdia,Nr.mdhd(t.timescale||0,t.duration||0),Nr.hdlr(t.type),Nr.minf(t))}static mfhd(t){return Nr.box(Nr.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"?Nr.box(Nr.types.minf,Nr.box(Nr.types.smhd,Nr.SMHD),Nr.DINF,Nr.stbl(t)):Nr.box(Nr.types.minf,Nr.box(Nr.types.vmhd,Nr.VMHD),Nr.DINF,Nr.stbl(t))}static moof(t,r,n){return Nr.box(Nr.types.moof,Nr.mfhd(t),Nr.traf(n,r))}static moov(t){let r=t.length;const n=[];for(;r--;)n[r]=Nr.trak(t[r]);return Nr.box.apply(null,[Nr.types.moov,Nr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(n).concat(Nr.mvex(t)))}static mvex(t){let r=t.length;const n=[];for(;r--;)n[r]=Nr.trex(t[r]);return Nr.box.apply(null,[Nr.types.mvex,...n])}static mvhd(t,r){r*=t;const n=Math.floor(r/(qN+1)),a=Math.floor(r%(qN+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Nr.box(Nr.types.mvhd,i)}static sdtp(t){const r=t.samples||[],n=new Uint8Array(4+r.length);let a,i;for(a=0;a>>8&255),r.push(l&255),r=r.concat(Array.prototype.slice.call(i));for(a=0;a>>8&255),n.push(l&255),n=n.concat(Array.prototype.slice.call(i));const o=Nr.box(Nr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),c=t.width,d=t.height,u=t.pixelRatio[0],m=t.pixelRatio[1];return Nr.box(Nr.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,Nr.box(Nr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Nr.box(Nr.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,m>>24,m>>16&255,m>>8&255,m&255])))}static esds(t){const r=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...r,6,1,2])}static audioStsd(t){const r=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(t){return Nr.box(Nr.types.mp4a,Nr.audioStsd(t),Nr.box(Nr.types.esds,Nr.esds(t)))}static mp3(t){return Nr.box(Nr.types[".mp3"],Nr.audioStsd(t))}static ac3(t){return Nr.box(Nr.types["ac-3"],Nr.audioStsd(t),Nr.box(Nr.types.dac3,t.config))}static stsd(t){const{segmentCodec:r}=t;if(t.type==="audio"){if(r==="aac")return Nr.box(Nr.types.stsd,Nr.STSD,Nr.mp4a(t));if(r==="ac3"&&t.config)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.ac3(t));if(r==="mp3"&&t.codec==="mp3")return Nr.box(Nr.types.stsd,Nr.STSD,Nr.mp3(t))}else if(t.pps&&t.sps){if(r==="avc")return Nr.box(Nr.types.stsd,Nr.STSD,Nr.avc1(t));if(r==="hevc"&&t.vps)return Nr.box(Nr.types.stsd,Nr.STSD,Nr.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${r}/${t.codec})`)}static tkhd(t){const r=t.id,n=(t.duration||0)*(t.timescale||0),a=t.width||0,i=t.height||0,l=Math.floor(n/(qN+1)),o=Math.floor(n%(qN+1));return Nr.box(Nr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,r&255,0,0,0,0,l>>24,l>>16&255,l>>8&255,l&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,a&255,0,0,i>>8&255,i&255,0,0]))}static traf(t,r){const n=Nr.sdtp(t),a=t.id,i=Math.floor(r/(qN+1)),l=Math.floor(r%(qN+1));return Nr.box(Nr.types.traf,Nr.box(Nr.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),Nr.box(Nr.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])),Nr.trun(t,n.length+16+20+8+16+8+8),n)}static trak(t){return t.duration=t.duration||4294967295,Nr.box(Nr.types.trak,Nr.tkhd(t),Nr.mdia(t))}static trex(t){const r=t.id;return Nr.box(Nr.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,r){const n=t.samples||[],a=n.length,i=12+16*a,l=new Uint8Array(i);let o,c,d,u,m,f;for(r+=8+i,l.set([t.type==="video"?1:0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,a&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),o=0;o>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,m.isLeading<<2|m.dependsOn,m.isDependedOn<<6|m.hasRedundancy<<4|m.paddingValue<<1|m.isNonSync,m.degradPrio&61440,m.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*o);return Nr.box(Nr.types.trun,l)}static initSegment(t){Nr.types||Nr.init();const r=Nr.moov(t);return dv(Nr.FTYP,r)}static hvc1(t){const r=t.params,n=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),a-1|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),n.length]);let l=i.length;for(let y=0;y>8,n[y][_].length&255]),l),l+=2,o.set(n[y][_],l),l+=n[y][_].length}const d=Nr.box(Nr.types.hvcC,o),u=t.width,m=t.height,f=t.pixelRatio[0],x=t.pixelRatio[1];return Nr.box(Nr.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,m>>8&255,m&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,Nr.box(Nr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Nr.box(Nr.types.pasp,new Uint8Array([f>>24,f>>16&255,f>>8&255,f&255,x>>24,x>>16&255,x>>8&255,x&255])))}}Nr.types=void 0;Nr.HDLR_TYPES=void 0;Nr.STTS=void 0;Nr.STSC=void 0;Nr.STCO=void 0;Nr.STSZ=void 0;Nr.VMHD=void 0;Nr.SMHD=void 0;Nr.STSD=void 0;Nr.FTYP=void 0;Nr.DINF=void 0;const G_t=9e4;function $Ie(s,t,r=1,n=!1){const a=s*t*r;return n?Math.round(a):a}function oJs(s,t,r=1,n=!1){return $Ie(s,t,1/r,n)}function bO(s,t=!1){return $Ie(s,1e3,1/G_t,t)}function lJs(s,t=1){return $Ie(s,G_t,1/t)}function lZe(s){const{baseTime:t,timescale:r,trackId:n}=s;return`${t/r} (${t}/${r}) trackId: ${n}`}const cJs=10*1e3,dJs=1024,uJs=1152,hJs=1536;let Y6=null,Fje=null;function cZe(s,t,r,n){return{duration:t,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class xhe extends yv{constructor(t,r,n,a){if(super("mp4-remuxer",a),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=r,this.typeSupported=n,this.ISGenerated=!1,Y6===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Y6=l?parseInt(l[1]):0}if(Fje===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);Fje=i?parseInt(i[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const r=this._initPTS;(!r||!t||t.trackId!==r.trackId||t.baseTime!==r.baseTime||t.timescale!==r.timescale)&&this.log(`Reset initPTS: ${r&&lZe(r)} > ${t&&lZe(t)}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let r=!1;const n=t[0].pts,a=t.reduce((i,l)=>{let o=l.pts,c=o-i;return c<-4294967296&&(r=!0,o=d0(o,n),c=o-i),c>0?i:o},n);return r&&this.debug("PTS rollover detected"),a}remux(t,r,n,a,i,l,o,c){let d,u,m,f,x,y,_=i,b=i;const j=t.pid>-1,N=r.pid>-1,C=r.samples.length,A=t.samples.length>0,E=o&&C>0||C>1;if((!j||A)&&(!N||E)||this.ISGenerated||o){if(this.ISGenerated){var R,F,O,B;const W=this.videoTrackConfig;(W&&(r.width!==W.width||r.height!==W.height||((R=r.pixelRatio)==null?void 0:R[0])!==((F=W.pixelRatio)==null?void 0:F[0])||((O=r.pixelRatio)==null?void 0:O[1])!==((B=W.pixelRatio)==null?void 0:B[1]))||!W&&E||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(m=this.generateIS(t,r,i,l));const K=this.isVideoContiguous;let Z=-1,Q;if(E&&(Z=mJs(r.samples),!K&&this.config.forceKeyFrameOnDiscontinuity))if(y=!0,Z>0){this.warn(`Dropped ${Z} out of ${C} video samples due to a missing keyframe`);const W=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(Z),r.dropped+=Z,b+=(r.samples[0].pts-W)/r.inputTimeScale,Q=b}else Z===-1&&(this.warn(`No keyframe found out of ${C} video samples`),y=!1);if(this.ISGenerated){if(A&&E){const W=this.getVideoStartPts(r.samples),ne=(d0(t.samples[0].pts,W)-W)/r.inputTimeScale;_+=Math.max(0,ne),b+=Math.max(0,-ne)}if(A){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),m=this.generateIS(t,r,i,l)),u=this.remuxAudio(t,_,this.isAudioContiguous,l,N||E||c===$a.AUDIO?b:void 0),E){const W=u?u.endPTS-u.startPTS:0;r.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),m=this.generateIS(t,r,i,l)),d=this.remuxVideo(r,b,K,W)}}else E&&(d=this.remuxVideo(r,b,K,0));d&&(d.firstKeyFrame=Z,d.independent=Z!==-1,d.firstKeyFramePTS=Q)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(x=W_t(n,i,this._initPTS,this._initDTS)),a.samples.length&&(f=K_t(a,i,this._initPTS))),{audio:u,video:d,initSegment:m,independent:y,text:f,id3:x}}computeInitPts(t,r,n,a){const i=Math.round(n*r);let l=d0(t,i);if(l0?fe-1:fe].dts&&(N=!0)}N&&l.sort(function(fe,je){const xe=fe.dts-je.dts,Ee=fe.pts-je.pts;return xe||Ee}),y=l[0].dts,_=l[l.length-1].dts;const A=_-y,E=A?Math.round(A/(c-1)):x||t.inputTimeScale/30;if(n){const fe=y-C,je=fe>E,xe=fe<-1;if((je||xe)&&(je?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${bO(fe,!0)} ms (${fe}dts) hole between fragments detected at ${r.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${bO(-fe,!0)} ms (${fe}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!xe||C>=l[0].pts||Y6)){y=C;const Ee=l[0].pts-fe;if(je)l[0].dts=y,l[0].pts=Ee;else{let Me=!0;for(let Oe=0;OeEe&&Me);Oe++){const Ie=l[Oe].pts;if(l[Oe].dts-=fe,l[Oe].pts-=fe,Oe0?je.dts-l[fe-1].dts:E;if(Me=fe>0?je.pts-l[fe-1].pts:E,Ie.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ve=Math.floor(Ie.maxBufferHole*i),Le=(a?b+a*i:this.nextAudioTs+u)-je.pts;Le>Ve?(x=Le-ze,x<0?x=ze:Z=!0,this.log(`It is approximately ${Le/90} ms to the next segment; using duration ${x/90} ms for the last video frame.`)):x=ze}else x=ze}const Oe=Math.round(je.pts-je.dts);Q=Math.min(Q,x),te=Math.max(te,x),W=Math.min(W,Me),ne=Math.max(ne,Me),o.push(cZe(je.key,x,Ee,Oe))}if(o.length){if(Y6){if(Y6<70){const fe=o[0].flags;fe.dependsOn=2,fe.isNonSync=0}}else if(Fje&&ne-W0&&(a&&Math.abs(C-(j+N))<9e3||Math.abs(d0(_[0].pts,C)-(j+N))<20*u),_.forEach(function(ne){ne.pts=d0(ne.pts,C)}),!n||j<0){const ne=_.length;if(_=_.filter(ae=>ae.pts>=0),ne!==_.length&&this.warn(`Removed ${_.length-ne} of ${ne} samples (initPTS ${N} / ${l})`),!_.length)return;i===0?j=0:a&&!y?j=Math.max(0,C-N):j=_[0].pts-N}if(t.segmentCodec==="aac"){const ne=this.config.maxAudioFramesDrift;for(let ae=0,ue=j+N;ae<_.length;ae++){const me=_[ae],de=me.pts,fe=de-ue,je=Math.abs(1e3*fe/l);if(fe<=-ne*u&&y)ae===0&&(this.warn(`Audio frame @ ${(de/l).toFixed(3)}s overlaps marker by ${Math.round(1e3*fe/l)} ms.`),this.nextAudioTs=j=de-N,ue=de);else if(fe>=ne*u&&je0){R+=b;try{D=new Uint8Array(R)}catch(je){this.observer.emit(_t.ERROR,_t.ERROR,{type:di.MUX_ERROR,details:kr.REMUX_ALLOC_ERROR,fatal:!1,error:je,bytes:R,reason:`fail allocating audio mdat ${R}`});return}f||(new DataView(D.buffer).setUint32(0,R),D.set(Nr.types.mdat,4))}else return;D.set(me,b);const fe=me.byteLength;b+=fe,x.push(cZe(!0,d,fe,0)),E=de}const O=x.length;if(!O)return;const B=x[x.length-1];j=E-N,this.nextAudioTs=j+c*B.duration;const K=f?new Uint8Array(0):Nr.moof(t.sequenceNumber++,A/c,Ac({},t,{samples:x}));t.samples=[];const Z=(A-N)/l,Q=this.nextAudioTs/l,te={data1:K,data2:D,startPTS:Z,endPTS:Q,startDTS:Z,endDTS:Q,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,te}}function d0(s,t){let r;if(t===null)return s;for(t4294967296;)s+=r;return s}function mJs(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class fJs extends yv{constructor(t,r,n,a){super("passthrough-remuxer",a),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const r=this.initPTS;r&&t&&r.baseTime===t.baseTime&&r.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,r,n,a){this.audioCodec=r,this.videoCodec=n,this.generateInitSegment(t,a),this.emitInitSegment=!0}generateInitSegment(t,r){let{audioCodec:n,videoCodec:a}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:l}=this.initData=e_t(t);if(r)tXs(t,r);else{const c=i||l;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}i&&(n=dZe(i,Rc.AUDIO,this)),l&&(a=dZe(l,Rc.VIDEO,this));const o={};i&&l?o.audiovideo={container:"video/mp4",codec:n+","+a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:i?o.audio={container:"audio/mp4",codec:n,encrypted:i.encrypted,initSegment:t,id:"audio"}:l?o.video={container:"video/mp4",codec:a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,r,n,a,i,l){var o,c;let{initPTS:d,lastEndTime:u}=this;const m={audio:void 0,video:void 0,text:a,id3:n,initSegment:void 0};Sa(u)||(u=this.lastEndTime=i||0);const f=r.samples;if(!f.length)return m;const x={initPTS:void 0,timescale:void 0,trackId:void 0};let y=this.initData;if((o=y)!=null&&o.length||(this.generateInitSegment(f),y=this.initData),!((c=y)!=null&&c.length))return this.warn("Failed to generate initSegment."),m;this.emitInitSegment&&(x.tracks=this.initTracks,this.emitInitSegment=!1);const _=rXs(f,y,this),b=y.audio?_[y.audio.id]:null,j=y.video?_[y.video.id]:null,N=HV(j,1/0),C=HV(b,1/0),A=HV(j,0,!0),E=HV(b,0,!0);let D=i,R=0;const F=b&&(!j||!d&&C0?this.lastEndTime=K:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Z=!!y.audio,Q=!!y.video;let W="";Z&&(W+="audio"),Q&&(W+="video");const te=(y.audio?y.audio.encrypted:!1)||(y.video?y.video.encrypted:!1),ne={data1:f,startPTS:B,startDTS:B,endPTS:K,endDTS:K,type:W,hasAudio:Z,hasVideo:Q,nb:1,dropped:0,encrypted:te};m.audio=Z&&!Q?ne:void 0,m.video=Q?ne:void 0;const ae=j==null?void 0:j.sampleCount;if(ae){const ue=j.keyFrameIndex,me=ue!==-1;ne.nb=ae,ne.dropped=ue===0||this.isVideoContiguous?0:me?ue:ae,ne.independent=me,ne.firstKeyFrame=ue,me&&j.keyFrameStart&&(ne.firstKeyFramePTS=(j.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(m.independent=me),this.isVideoContiguous||(this.isVideoContiguous=me),ne.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ue}/${ae} dropped: ${ne.dropped} start: ${ne.firstKeyFramePTS||"NA"}`)}return m.initSegment=x,m.id3=W_t(n,i,d,d),a.samples.length&&(m.text=K_t(a,i,d)),m}}function HV(s,t,r=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(r?s.duration:0))/s.timescale:t}function pJs(s,t,r,n){if(s===null)return!0;const a=Math.max(n,1),i=t-s.baseTime/s.timescale;return Math.abs(i-r)>a}function dZe(s,t,r){const n=s.codec;return n&&n.length>4?n:t===Rc.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?Wpe(n,!1):(r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):(r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}let Lj;try{Lj=self.performance.now.bind(self.performance)}catch{Lj=Date.now}const ghe=[{demux:eJs,remux:fJs},{demux:fk,remux:xhe},{demux:ZQs,remux:xhe},{demux:QQs,remux:xhe}];ghe.splice(2,0,{demux:XQs,remux:xhe});class uZe{constructor(t,r,n,a,i,l){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=r,this.config=n,this.id=i,this.logger=l}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,r,n,a){const i=n.transmuxing;i.executeStart=Lj();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:u,trackSwitch:m,accurateTimeOffset:f,timeOffset:x,initSegmentChange:y}=a||o,{audioCodec:_,videoCodec:b,defaultInitPts:j,duration:N,initSegmentData:C}=c,A=xJs(l,r);if(A&&OP(A.method)){const F=this.getDecrypter(),O=IIe(A.method);if(F.isSync()){let B=F.softwareDecrypt(l,A.key.buffer,A.iv.buffer,O);if(n.part>-1){const Z=F.flush();B=Z&&Z.buffer}if(!B)return i.executeEnd=Lj(),zje(n);l=new Uint8Array(B)}else return this.asyncResult=!0,this.decryptionPromise=F.webCryptoDecrypt(l,A.key.buffer,A.iv.buffer,O).then(B=>{const K=this.push(B,null,n);return this.decryptionPromise=null,K}),this.decryptionPromise}const E=this.needsProbing(u,m);if(E){const F=this.configureTransmuxer(l);if(F)return this.logger.warn(`[transmuxer] ${F.message}`),this.observer.emit(_t.ERROR,_t.ERROR,{type:di.MEDIA_ERROR,details:kr.FRAG_PARSING_ERROR,fatal:!1,error:F,reason:F.message}),i.executeEnd=Lj(),zje(n)}(u||m||y||E)&&this.resetInitSegment(C,_,b,N,r),(u||y||E)&&this.resetInitialTimestamp(j),d||this.resetContiguity();const D=this.transmux(l,A,x,f,n);this.asyncResult=qz(D);const R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,i.executeEnd=Lj(),D}flush(t){const r=t.transmuxing;r.executeStart=Lj();const{decrypter:n,currentTransmuxState:a,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(t));const l=[],{timeOffset:o}=a;if(n){const m=n.flush();m&&l.push(this.push(m.buffer,null,t))}const{demuxer:c,remuxer:d}=this;if(!c||!d){r.executeEnd=Lj();const m=[zje(t)];return this.asyncResult?Promise.resolve(m):m}const u=c.flush(o);return qz(u)?(this.asyncResult=!0,u.then(m=>(this.flushRemux(l,m,t),l))):(this.flushRemux(l,u,t),this.asyncResult?Promise.resolve(l):l)}flushRemux(t,r,n){const{audioTrack:a,videoTrack:i,id3Track:l,textTrack:o}=r,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id===$a.MAIN?"level":"track"} ${n.level}`);const u=this.remuxer.remux(a,i,l,o,d,c,!0,this.id);t.push({remuxResult:u,chunkMeta:n}),n.transmuxing.executeEnd=Lj()}resetInitialTimestamp(t){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(t),n.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(t,r,n,a,i){const{demuxer:l,remuxer:o}=this;!l||!o||(l.resetInitSegment(t,r,n,a),o.resetInitSegment(t,r,n,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,r,n,a,i){let l;return r&&r.method==="SAMPLE-AES"?l=this.transmuxSampleAes(t,r,n,a,i):l=this.transmuxUnencrypted(t,n,a,i),l}transmuxUnencrypted(t,r,n,a){const{audioTrack:i,videoTrack:l,id3Track:o,textTrack:c}=this.demuxer.demux(t,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,l,o,c,r,n,!1,this.id),chunkMeta:a}}transmuxSampleAes(t,r,n,a,i){return this.demuxer.demuxSampleAes(t,r,n).then(l=>({remuxResult:this.remuxer.remux(l.audioTrack,l.videoTrack,l.id3Track,l.textTrack,n,a,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:r,observer:n,typeSupported:a}=this;let i;for(let m=0,f=ghe.length;m0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(r=t),r}const zje=s=>({remuxResult:{},chunkMeta:s});function qz(s){return"then"in s&&s.then instanceof Function}class gJs{constructor(t,r,n,a,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=n,this.duration=a,this.defaultInitPts=i||null}}class yJs{constructor(t,r,n,a,i,l){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=r,this.accurateTimeOffset=n,this.trackSwitch=a,this.timeOffset=i,this.initSegmentChange=l}}let hZe=0;class Y_t{constructor(t,r,n,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=hZe++,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 m;const f=(m=this.workerContext)==null?void 0:m.objectURL;f&&self.URL.revokeObjectURL(f);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(_t.ERROR,{type:di.OTHER_ERROR,details:kr.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const i=t.config;this.hls=t,this.id=r,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=a;const l=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===_t.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new DIe,this.observer.on(_t.FRAG_DECRYPTED,l),this.observer.on(_t.ERROR,l);const o=CYe(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||wQs()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${r}"`),this.workerContext=NQs(i.workerPath)):(c.log(`injecting Web Worker for "${r}"`),this.workerContext=jQs());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:r,config:Hc(i)})}catch(u){c.warn(`Error setting up "${r}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new uZe(this.observer,o,i,"",r,t.logger)}return}}this.transmuxer=new uZe(this.observer,o,i,"",r,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=hZe++;const r=this.hls.config,n=CYe(r.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:n,id:this.id,config:Hc(r)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),kQs(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const r=this.transmuxer;r&&(r.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,r,n,a,i,l,o,c,d,u){var m,f;d.transmuxing.start=self.performance.now();const{instanceNo:x,transmuxer:y}=this,_=l?l.start:i.start,b=i.decryptdata,j=this.frag,N=!(j&&i.cc===j.cc),C=!(j&&d.level===j.level),A=j?d.sn-j.sn:-1,E=this.part?d.part-this.part.index:-1,D=A===0&&d.id>1&&d.id===(j==null?void 0:j.stats.chunkCount),R=!C&&(A===1||A===0&&(E===1||D&&E<=0)),F=self.performance.now();(C||A||i.stats.parsing.start===0)&&(i.stats.parsing.start=F),l&&(E||!R)&&(l.stats.parsing.start=F);const O=!(j&&((m=i.initSegment)==null?void 0:m.url)===((f=j.initSegment)==null?void 0:f.url)),B=new yJs(N,R,c,C,_,O);if(!R||N||O){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===$a.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${N} trackSwitch: ${C} contiguous: ${R} accurateTimeOffset: ${c} timeOffset: ${_} initSegmentChange: ${O}`);const K=new gJs(n,a,r,o,u);this.configureTransmuxer(K)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:x,cmd:"demux",data:t,decryptdata:b,chunkMeta:d,state:B},t instanceof ArrayBuffer?[t]:[]);else if(y){const K=y.push(t,b,d,B);qz(K)?K.then(Z=>{this.handleTransmuxComplete(Z)}).catch(Z=>{this.transmuxerError(Z,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(K)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:r,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:t});else if(n){const a=n.flush(t);qz(a)?a.then(i=>{this.handleFlushResult(i,t)}).catch(i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}):this.handleFlushResult(a,t)}}transmuxerError(t,r,n){this.hls&&(this.error=t,this.hls.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.FRAG_PARSING_ERROR,chunkMeta:r,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:n}))}handleFlushResult(t,r){t.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(r)}configureTransmuxer(t){const{instanceNo:r,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:r,cmd:"configure",config:t}):n&&n.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const mZe=100;class vJs extends LIe{constructor(t,r,n){super(t,r,n,"audio-stream-controller",$a.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(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(_t.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(_t.BUFFER_RESET,this.onBufferReset,this),t.on(_t.BUFFER_CREATED,this.onBufferCreated,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(_t.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(_t.FRAG_LOADING,this.onFragLoading,this),t.on(_t.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(_t.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(_t.BUFFER_RESET,this.onBufferReset,this),t.off(_t.BUFFER_CREATED,this.onBufferCreated,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(_t.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(_t.FRAG_LOADING,this.onFragLoading,this),t.off(_t.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:r,id:n,initPTS:a,timescale:i,trackId:l}){if(n===$a.MAIN){const o=r.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:a,timescale:i,trackId:l},this.log(`InitPTS for cc: ${o} found from main: ${a/i} (${a}/${i}) trackId: ${l}`),this.mainAnchor=r,this.state===rn.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(r,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(r,c)):this.state===rn.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,r){var n;const a=((n=this.mainFragLoading)==null?void 0:n.frag)||null;if(r&&(a==null?void 0:a.cc)===r.cc)return;const i=(a||t).cc,l=this.getLevelDetails(),o=this.getLoadPosition(),c=u_t(l,i,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===rn.IDLE&&this.doTickIdle())}startLoad(t,r){if(!this.levels){this.startPosition=t,this.state=rn.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval(mZe),n>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),t=n,this.state=rn.IDLE):this.state=rn.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}doTick(){switch(this.state){case rn.IDLE:this.doTickIdle();break;case rn.WAITING_TRACK:{const{levels:t,trackId:r}=this,n=t==null?void 0:t[r],a=n==null?void 0:n.details;if(a&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(a))break;this.state=rn.WAITING_INIT_PTS}break}case rn.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case rn.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:r,part:n,cache:a,complete:i}=t,l=this.mainAnchor;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.state=rn.FRAG_LOADING;const o=a.flush().buffer,c={frag:r,part:n,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),i&&super._handleFragmentLoadComplete(c)}else l&&l.cc!==t.frag.cc&&this.syncWithAnchor(l,t.frag)}else this.state=rn.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:r,levels:n,media:a,trackId:i}=this,l=r.config;if(!this.buffering||!a&&!this.primaryPrefetch&&(this.startFragRequested||!l.startFragPrefetch)||!(n!=null&&n[i]))return;const o=n[i],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=rn.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Rc.AUDIO,$a.AUDIO));const u=this.getFwdBufferInfo(d,$a.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){r.trigger(_t.BUFFER_EOS,{type:"audio"}),this.state=rn.ENDED;return}const m=u.len,f=r.maxBufferLength,x=c.fragments,y=x[0].start,_=this.getLoadPosition(),b=this.flushing?_:u.end;if(this.switchingTrack&&a){const C=_;c.PTSKnown&&Cy||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=y+.05)}if(m>=f&&!this.switchingTrack&&bN.end){const A=this.fragmentTracker.getFragAtPos(b,$a.MAIN);A&&A.end>N.end&&(N=A,this.mainFragLoading={frag:A,targetBufferTime:null})}if(j.start>N.end)return}this.loadFragment(j,o,b)}onMediaDetaching(t,r){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,r)}onAudioTracksUpdated(t,{audioTracks:r}){this.resetTransmuxer(),this.levels=r.map(n=>new Bz(n))}onAudioTrackSwitching(t,r){const n=!!r.url;this.trackId=r.id;const{fragCurrent:a}=this;a&&(a.abortRequests(),this.removeUnbufferedFrags(a.start)),this.resetLoadingState(),n?(this.switchingTrack=r,this.flushAudioIfNeeded(r),this.state!==rn.STOPPED&&(this.setInterval(mZe),this.state=rn.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=r,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,r){this.mainDetails=r.details;const n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(_t.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(t,r){var n;const{levels:a}=this,{details:i,id:l,groupId:o,track:c}=r;if(!a){this.warn(`Audio tracks reset while loading track ${l} "${c.name}" of "${o}"`);return}const d=this.mainDetails;if(!d||i.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=r,this.state!==rn.STOPPED&&(this.state=rn.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 m=0;if(i.live||(n=u.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(u.details){var f;m=this.alignPlaylists(i,u.details,(f=this.levelLastLoaded)==null?void 0:f.details)}i.alignedSliding||(E_t(i,d),i.alignedSliding||exe(i,d),m=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,m),this.hls.trigger(_t.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:r.groupId}),this.state===rn.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=rn.IDLE),this.tick()}_handleFragmentLoadProgress(t){var r;const n=t.frag,{part:a,payload:i}=t,{config:l,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const d=c[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const m=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let f=this.transmuxer;f||(f=this.transmuxer=new Y_t(this.hls,$a.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const x=this.initPTS[n.cc],y=(r=n.initSegment)==null?void 0:r.data;if(x!==void 0){const b=a?a.index:-1,j=b!==-1,N=new MIe(n.level,n.sn,n.stats.chunkCount,i.byteLength,b,j);f.push(i,y,m,"",n,a,u.totalduration,!1,N,x)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:_}=this.waitingData=this.waitingData||{frag:n,part:a,cache:new A_t,complete:!1};_.push(new Uint8Array(i)),this.state!==rn.STOPPED&&(this.state=rn.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,r){this.bufferFlushed=this.flushing=!1;const n=r.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(t,r){!this.audioOnly&&r.frag.type===$a.MAIN&&oh(r.frag)&&(this.mainFragLoading=r,this.state===rn.IDLE&&this.tick())}onFragBuffered(t,r){const{frag:n,part:a}=r;if(n.type!==$a.AUDIO){!this.audioOnly&&n.type===$a.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${a?" p: "+a.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(oh(n)){this.fragPrevious=n;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(_t.AUDIO_TRACK_SWITCHED,uc({},i)))}this.fragBufferedComplete(n,a),this.media&&this.tick()}onError(t,r){var n;if(r.fatal){this.state=rn.ERROR;return}switch(r.details){case kr.FRAG_GAP:case kr.FRAG_PARSING_ERROR:case kr.FRAG_DECRYPT_ERROR:case kr.FRAG_LOAD_ERROR:case kr.FRAG_LOAD_TIMEOUT:case kr.KEY_LOAD_ERROR:case kr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError($a.AUDIO,r);break;case kr.AUDIO_TRACK_LOAD_ERROR:case kr.AUDIO_TRACK_LOAD_TIMEOUT:case kr.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===rn.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===Jo.AUDIO_TRACK&&(this.state=rn.IDLE);break;case kr.BUFFER_ADD_CODEC_ERROR:case kr.BUFFER_APPEND_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case kr.BUFFER_FULL_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case kr.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(t,{type:r}){r!==Rc.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:r}){if(r!==Rc.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===rn.ENDED&&(this.state=rn.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,$a.AUDIO),this.tick())}}_handleTransmuxComplete(t){var r;const n="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:u}=o,{details:m}=u,{audio:f,text:x,id3:y,initSegment:_}=i;if(this.fragContextChanged(c)||!m){this.fragmentTracker.removeFragment(c);return}if(this.state=rn.PARSING,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const b=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(u,_.tracks,b,l),a.trigger(_t.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:n,tracks:_.tracks})}if(f){const{startPTS:b,endPTS:j,startDTS:N,endDTS:C}=f;d&&(d.elementaryStreams[Rc.AUDIO]={startPTS:b,endPTS:j,startDTS:N,endDTS:C}),c.setElementaryStreamInfo(Rc.AUDIO,b,j,N,C),this.bufferFragmentData(f,c,d,l)}if(y!=null&&(r=y.samples)!=null&&r.length){const b=Ac({id:n,frag:c,details:m},y);a.trigger(_t.FRAG_PARSING_METADATA,b)}if(x){const b=Ac({id:n,frag:c,details:m},x);a.trigger(_t.FRAG_PARSING_USERDATA,b)}}_bufferInitSegment(t,r,n,a){if(this.state!==rn.PARSING||(r.video&&delete r.video,r.audiovideo&&delete r.audiovideo,!r.audio))return;const i=r.audio;i.id=$a.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(_t.BUFFER_CODECS,r);const o=i.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:n,part:null,chunkMeta:a,parent:n.type,data:o};this.hls.trigger(_t.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,r,n){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===lm.NOT_LOADED||a===lm.PARTIAL){var i;if(!oh(t))this._loadInitSegment(t,r);else if((i=r.details)!=null&&i.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=rn.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==r.details.fragmentStart&&exe(r.details,l)}else super.loadFragment(t,r,n)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:r,lang:n,assocLang:a,characteristics:i,audioCodec:l,channels:o}=this.bufferedTrack;cA({name:r,lang:n,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,BT)||(Ype(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:r}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,r.trigger(_t.AUDIO_TRACK_SWITCHED,uc({},t))}}class UIe extends yv{constructor(t,r){super(r,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,r,n){const a=r==null?void 0:r.renditionReports;if(a){let i=-1;for(let l=0;l=0&&u>r.partTarget&&(c+=1)}const d=n&&TYe(n);return new EYe(o,c>=0?c:void 0,d)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,r){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,r){if(r)try{return r.addDirectives(t)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}return t}playlistLoaded(t,r,n){const{details:a,stats:i}=r,l=self.performance.now(),o=i.loading.first?Math.max(0,l-i.loading.first):0;a.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==a.appliedTimelineOffset){const u=Math.max(c||0,0);a.appliedTimelineOffset=u,a.fragments.forEach(m=>{m.setStart(m.playlistOffset+u)})}if(a.live||n!=null&&n.live){const u="levelInfo"in r?r.levelInfo:r.track;if(a.reloaded(n),n&&a.fragments.length>0){uQs(n,a,this);const N=a.playlistParsingError;if(N){this.warn(N);const C=this.hls;if(!C.config.ignorePlaylistParsingErrors){var d;const{networkDetails:A}=r;C.trigger(_t.ERROR,{type:di.NETWORK_ERROR,details:kr.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:N,reason:N.message,level:r.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:A,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const m=this.hls.mainForwardBufferInfo,f=m?m.end-m.len:0,x=(a.edge-f)*1e3,y=N_t(a,x);if(a.requestScheduled+y0){if(O>a.targetduration*3)this.log(`Playlist last advanced ${F.toFixed(2)}s ago. Omitting segment and part directives.`),b=void 0,j=void 0;else if(n!=null&&n.tuneInGoal&&O-a.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${B} with playlist age: ${a.age}`),B=0;else{const K=Math.floor(B/a.targetduration);if(b+=K,j!==void 0){const Z=Math.round(B%a.targetduration/a.partTarget);j+=Z}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${F.toFixed(2)}s goal: ${B} skip sn ${K} to part ${j}`)}a.tuneInGoal=B}if(_=this.getDeliveryDirectives(a,r.deliveryDirectives,b,j),N||!R){a.requestScheduled=l,this.loadingPlaylist(u,_);return}}else(a.canBlockReload||a.canSkipUntil)&&(_=this.getDeliveryDirectives(a,r.deliveryDirectives,b,j));_&&b!==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,r,n){const a=n||t.details;if(!a){this.loadingPlaylist(t,r);return}const i=self.performance.now(),l=a.requestScheduled;if(i>=l){this.loadingPlaylist(t,r);return}const o=l-i;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,r),o)}getDeliveryDirectives(t,r,n,a){let i=TYe(t);return r!=null&&r.skip&&t.deltaUpdateFailed&&(n=r.msn,a=r.part,i=fhe.No),new EYe(n,a,i)}checkRetry(t){const r=t.details,n=Zpe(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===Rf.RetryRequest||!a.resolved&&i===Rf.SendAlternateToPenaltyBox);if(c){var d;if(l>=o.maxNumRetry)return!1;if(n&&(d=t.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const u=EIe(o,l);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${r}" in ${u}ms`)}t.levelRetry=!0,a.resolved=!0}return c}}function Z_t(s,t){if(s.length!==t.length)return!1;for(let r=0;rs[a]!==t[a])}function e3e(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class bJs extends UIe{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(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.LEVEL_LOADING,this.onLevelLoading,this),t.on(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_t.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.LEVEL_LOADING,this.onLevelLoading,this),t.off(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_t.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(_t.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(t,r){const{id:n,groupId:a,details:i}=r,l=this.tracksInGroup[n];if(!l||l.groupId!==a){this.warn(`Audio track with id:${n} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=r.details,this.log(`Audio track ${n} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(t,r){this.switchLevel(r.level)}onLevelSwitching(t,r){this.switchLevel(r.level)}switchLevel(t){const r=this.hls.levels[t];if(!r)return;const n=r.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!n||(a==null?void 0:a.length)!==(n==null?void 0:n.length)||n!=null&&n.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(f=>!n||n.indexOf(f.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(f=>f.default)&&(this.selectDefaultTrack=!1),o.forEach((f,x)=>{f.id=x});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const f=x_(c,o,BT);if(f>-1)i=o[f];else{const x=x_(c,this.tracks);i=this.tracks[x]}}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): ${n==null?void 0:n.join(",")}`),this.hls.trigger(_t.AUDIO_TRACKS_UPDATED,u);const m=this.trackId;if(d!==-1&&m===-1)this.setAudioTrack(d);else if(o.length&&m===-1){var l;const f=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(f.message),this.hls.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}onError(t,r){r.fatal||!r.context||r.context.type===Jo.AUDIO_TRACK&&r.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(r.context.groupId)!==-1)&&this.checkRetry(r)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const r=this.hls;if(r.config.audioPreference=t,t){const n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){const a=this.currentTrack;if(a&&cA(t,a,BT))return a;const i=x_(t,this.tracksInGroup,BT);if(i>-1){const l=this.tracksInGroup[i];return this.setAudioTrack(i),l}else if(a){let l=r.loadLevel;l===-1&&(l=r.firstAutoLevel);const o=IXs(t,r.levels,n,l,BT);if(o===-1)return null;r.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=x_(t,n);if(l>-1)return n[l]}}}return null}setAudioTrack(t){const r=this.tracksInGroup;if(t<0||t>=r.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,a=r[t],i=a.details&&!a.details.live;if(t===this.trackId&&a===n&&i||(this.log(`Switching to audio-track ${t} "${a.name}" lang:${a.lang} group:${a.groupId} channels:${a.channels}`),this.trackId=t,this.currentTrack=a,this.hls.trigger(_t.AUDIO_TRACK_SWITCHING,uc({},a)),i))return;const l=this.switchParams(a.url,n==null?void 0:n.details,a.details);this.loadPlaylist(l)}findTrackId(t){const r=this.tracksInGroup;for(let n=0;n{const n={label:"async-blocker",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,t)})}prependBlocker(t){return new Promise(r=>{if(this.queues){const n={label:"async-blocker-prepend",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var r;const n=(r=t[0])==null?void 0:r.label;(n==="async-blocker"||n==="async-blocker-prepend")&&(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(this.queues===null)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const r=this.queues[t];if(r.length){const a=r[0];try{a.execute()}catch(i){var n;if(a.onError(i),this.queues===null||this.tracks===null)return;const l=(n=this.tracks[t])==null?void 0:n.buffer;l!=null&&l.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var r;return((r=this.queues)==null?void 0:r[t][0])||null}toString(){const{queues:t,tracks:r}=this;return t===null||r===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(t){var r,n;return(r=this.queues)!=null&&r[t]||(n=this.tracks)!=null&&n[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var r;const n=(r=this.tracks)==null?void 0:r[t],a=n==null?void 0:n.buffer;return a?`SourceBuffer${a.updating?" updating":""}${n.ended?" ended":""}${n.ending?" ending":""}`:"none"}listOps(t){var r;return((r=this.queues)==null?void 0:r[t].map(n=>n.label).join(", "))||""}}const fZe=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,X_t="HlsJsTrackRemovedError";class wJs extends Error{constructor(t){super(t),this.name=X_t}}class jJs extends yv{constructor(t,r){super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=n=>{var a;this.hls&&((a=this.mediaSource)==null?void 0:a.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=n=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=n=>{const{media:a,mediaSource:i}=this;n&&this.log("Media source opened"),!(!a||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(_t.MEDIA_ATTACHED,{media:a,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:n,_objectUrl:a}=this;n!==a&&this.error(`Media element src was set while attaching MediaSource (${a} > ${n})`)},this.hls=t,this.fragmentTracker=r,this.appendSource=HZs(US(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(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.BUFFER_RESET,this.onBufferReset,this),t.on(_t.BUFFER_APPENDING,this.onBufferAppending,this),t.on(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.on(_t.BUFFER_EOS,this.onBufferEos,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_t.FRAG_PARSED,this.onFragParsed,this),t.on(_t.FRAG_CHANGED,this.onFragChanged,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.BUFFER_RESET,this.onBufferReset,this),t.off(_t.BUFFER_APPENDING,this.onBufferAppending,this),t.off(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.off(_t.BUFFER_EOS,this.onBufferEos,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_t.FRAG_PARSED,this.onFragParsed,this),t.off(_t.FRAG_CHANGED,this.onFragChanged,this),t.off(_t.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:r}=this;if(!t)return null;const n={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const l=this.isQueued();(i||l)&&this.warn(`Transfering MediaSource with${l?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const a=this.transferData;return!this.sourceBufferCount&&a&&a.mediaSource===r?Ac(n,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(n[l]=Ac({},this.tracks[l]),this.removeBuffer(l)),i[0]=i[1]=null}),{media:t,mediaSource:r,tracks:n}}initTracks(){const t={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,r){var n;let a=2;(r.audio&&!r.video||!r.altAudio)&&(a=1),this.bufferCodecEventsTotal=a,this.log(`${a} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&a&&this.bufferCreated()}onMediaAttaching(t,r){const n=this.media=r.media;this.transferData=this.overrides=void 0;const a=US(this.appendSource);if(a){const i=!!r.mediaSource;(i||r.overrides)&&(this.transferData=r,this.overrides=r.overrides);const l=this.mediaSource=r.mediaSource||new a;if(this.assignMediaSource(l),i)this._objectUrl=n.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(l);if(this.appendSource)try{n.removeAttribute("src");const c=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||c&&l instanceof c,pZe(n),NJs(n,o),n.load()}catch{n.src=o}else n.src=o}n.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var r,n;this.log(`${((r=this.transferData)==null?void 0:r.mediaSource)===t?"transferred":"created"} media source: ${(n=t.constructor)==null?void 0:n.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,r=this.transferData;if(!r||!t)return;const n=this.tracks,a=r.tracks,i=a?Object.keys(a):null,l=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(a&&i&&l){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${Hc(n,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${Hc(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!Wbt(a,n)){r.mediaSource=null,r.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(n)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(_t.MEDIA_DETACHING,{}),this.onMediaAttaching(_t.MEDIA_ATTACHING,r),t.currentTime=u;return}this.transferData=void 0,i.forEach(c=>{const d=c,u=a[d];if(u){const m=u.buffer;if(m){const f=this.fragmentTracker,x=u.id;if(f.hasFragments(x)||f.hasParts(x)){const b=po.getBuffered(m);f.detectEvictedFragments(d,b,x,null,!0)}const y=Bje(d),_=[d,m];this.sourceBuffers[y]=_,m.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 r=(t=this.mediaSource)==null?void 0:t.readyState;return r==="open"||r==="ended"}onMediaDetaching(t,r){const n=!!r.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${n?"transferring":"detaching"}`),n)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const c=i.sourceBuffers;for(let d=c.length;d--;)o&&c[d].abort(),i.removeSourceBuffer(c[d]);o&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}a&&(a.removeEventListener("emptied",this._onMediaEmptied),n||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&pZe(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(_t.MEDIA_DETACHED,r)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var r;const n=(r=this.tracks[t])==null?void 0:r.buffer;if(this.removeBuffer(t),n)try{var a;(a=this.mediaSource)!=null&&a.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(n)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Bje(t)]=[null,null];const r=this.tracks[t];r&&(r.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new _Js(this.tracks)}onBufferCodecs(t,r){var n;const a=this.tracks,i=Object.keys(r);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in r&&(a.audio||a.video)||a.audiovideo&&("audio"in r||"video"in r),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,u;const m=r[c],{id:f,codec:x,levelCodec:y,container:_,metadata:b,supplemental:j}=m;let N=a[c];const C=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],A=C!=null&&C.buffer?C:N,E=(A==null?void 0:A.pendingCodec)||(A==null?void 0:A.codec),D=A==null?void 0:A.levelCodec;N||(N=a[c]={buffer:void 0,listeners:[],codec:x,supplemental:j,container:_,levelCodec:y,metadata:b,id:f});const R=mhe(E,D),F=R==null?void 0:R.replace(fZe,"$1");let O=mhe(x,y);const B=(u=O)==null?void 0:u.replace(fZe,"$1");O&&R&&F!==B&&(c.slice(0,5)==="audio"&&(O=Wpe(O,this.appendSource)),this.log(`switching codec ${E} to ${O}`),O!==(N.pendingCodec||N.codec)&&(N.pendingCodec=O),N.container=_,this.appendChangeType(c,_,O))}),(this.tracksReady||this.sourceBufferCount)&&(r.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!r.video&&((n=r.audio)==null?void 0:n.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,r)=>{const n=this.tracks[r];return t[r]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},t},{})}appendChangeType(t,r,n){const a=`${r};codecs=${n}`,i={label:`change-type=${a}`,execute:()=>{const l=this.tracks[t];if(l){const o=l.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${a}`),o.changeType(a),l.codec=n,l.container=r)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn(`Failed to change ${t} SourceBuffer type`,l)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var r;const n=t.start,a=n+t.duration*.05;if(((r=this.fragmentTracker.getAppendedFrag(n,$a.MAIN))==null?void 0:r.gap)===!0)return;const l={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>a||c!=null&&c.buffer&&po.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,$a.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:l,frag:t},this.append(l,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:r}=this;t&&r&&(this.blockedAudioAppend=null,r.unblockAudio(t.op))}onBufferAppending(t,r){const{tracks:n}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:u}=r,m=d.buffering[i],{sn:f,cc:x}=o,y=self.performance.now();m.start=y;const _=o.stats.buffering,b=c?c.stats.buffering:null;_.start===0&&(_.start=y),b&&b.start===0&&(b.start=y);const j=n.audio;let N=!1;i==="audio"&&(j==null?void 0:j.container)==="audio/mpeg"&&(N=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const C=n.video,A=C==null?void 0:C.buffer;if(A&&f!=="initSegment"){const R=c||o,F=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(C.ending||C.ended)){const B=R.start+R.duration*.05,K=A.buffered,Z=this.currentOp("video");!K.length&&!Z?this.blockAudio(R):!Z&&!po.isBuffered(A,B)&&this.lastVideoAppendEndB||O{var R;m.executeStart=self.performance.now();const F=(R=this.tracks[i])==null?void 0:R.buffer;F&&(N?this.updateTimestampOffset(F,E,.1,i,f,x):u!==void 0&&Sa(u)&&this.updateTimestampOffset(F,u,1e-6,i,f,x)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const R=self.performance.now();m.executeEnd=m.end=R,_.first===0&&(_.first=R),b&&b.first===0&&(b.first=R);const F={};this.sourceBuffers.forEach(([O,B])=>{O&&(F[O]=po.getBuffered(B))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(_t.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:F})},onError:R=>{var F;const O={type:di.MEDIA_ERROR,parent:o.type,details:kr.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:R,err:R,fatal:!1},B=(F=this.media)==null?void 0:F.error;if(R.code===DOMException.QUOTA_EXCEEDED_ERR||R.name=="QuotaExceededError"||"quota"in R)O.details=kr.BUFFER_FULL_ERROR;else if(R.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!B)O.errorAction=RP(!0);else if(R.name===X_t&&this.sourceBufferCount===0)O.errorAction=RP(!0);else{const K=++this.appendErrors[i];this.warn(`Failed ${K}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${B||"no media error"})`),(K>=this.hls.config.appendErrorMaxRetry||B)&&(O.fatal=!0)}this.hls.trigger(_t.ERROR,O)}};this.log(`queuing "${i}" append sn: ${f}${c?" p: "+c.index:""} of ${o.type===$a.MAIN?"level":"track"} ${o.level} cc: ${x}`),this.append(D,i,this.isPending(this.tracks[i]))}getFlushOp(t,r,n){return this.log(`queuing "${t}" remove ${r}-${n}`),{label:"remove",execute:()=>{this.removeExecutor(t,r,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(_t.BUFFER_FLUSHED,{type:t})},onError:a=>{this.warn(`Failed to remove ${r}-${n} from "${t}" SourceBuffer`,a)}}}onBufferFlushing(t,r){const{type:n,startOffset:a,endOffset:i}=r;n?this.append(this.getFlushOp(n,a,i),n):this.sourceBuffers.forEach(([l])=>{l&&this.append(this.getFlushOp(l,a,i),l)})}onFragParsed(t,r){const{frag:n,part:a}=r,i=[],l=a?a.elementaryStreams:n.elementaryStreams;l[Rc.AUDIOVIDEO]?i.push("audiovideo"):(l[Rc.AUDIO]&&i.push("audio"),l[Rc.VIDEO]&&i.push("video"));const o=()=>{const c=self.performance.now();n.stats.buffering.end=c,a&&(a.stats.buffering.end=c);const d=a?a.stats:n.stats;this.hls.trigger(_t.FRAG_BUFFERED,{frag:n,part:a,stats:d,id:n.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(o,i).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,r){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const r=this.tracks[t];if(r)return!r.ended||r.ending}return!1})}onBufferEos(t,r){var n;this.sourceBuffers.forEach(([l])=>{if(l){const o=this.tracks[l];(!r.type||r.type===l)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${l} buffer reached EOS`)))}});const a=((n=this.overrides)==null?void 0:n.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([l])=>{var o;return l&&!((o=this.tracks[l])!=null&&o.ended)})?a?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:l}=this;if(!l||l.readyState!=="open"){l&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${l.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),l.endOfStream(),this.hls.trigger(_t.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(_t.BUFFERED_TO_END,void 0)):r.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){const r=this.tracks[t];r&&(r.ending=!1)}})}onLevelUpdated(t,{details:r}){r.fragments.length&&(this.details=r,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,r){if(r.details===kr.BUFFER_APPEND_ERROR&&r.frag){var n;const a=(n=r.errorAction)==null?void 0:n.nextAutoLevel;Sa(a)&&a!==r.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:r,media:n}=this;if(!n||r===null||!this.sourceBufferCount)return;const a=t.config,i=n.currentTime,l=r.levelTargetDuration,o=r.live&&a.liveBackBufferLength!==null?a.liveBackBufferLength:a.backBufferLength;if(Sa(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(Sa(c)&&c>0){const d=Math.max(a.maxBufferLength,c),u=Math.max(d,l),m=Math.floor(i/l)*l+u;this.flushFrontBuffer(i,l,m)}}flushBackBuffer(t,r,n){this.sourceBuffers.forEach(([a,i])=>{if(i){const o=po.getBuffered(i);if(o.length>0&&n>o.start(0)){var l;this.hls.trigger(_t.BACK_BUFFER_REACHED,{bufferEnd:n});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(_t.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(c!=null&&c.ended){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(_t.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:a})}}})}flushFrontBuffer(t,r,n){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=po.getBuffered(i),o=l.length;if(o<2)return;const c=l.start(o-1),d=l.end(o-1);if(n>c||t>=c&&t<=d)return;this.hls.trigger(_t.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}getDurationAndRange(){var t;const{details:r,mediaSource:n}=this;if(!r||!this.media||(n==null?void 0:n.readyState)!=="open")return null;const a=r.edge;if(r.live&&this.hls.config.liveDurationInfinity){if(r.fragments.length&&n.setLiveSeekableRange){const d=Math.max(0,r.fragmentStart),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 Sa(i)?{duration:i}:null;const l=this.media.duration,o=Sa(n.duration)?n.duration:0;return a>o&&a>l||!Sa(l)?{duration:a}:null}updateMediaSource({duration:t,start:r,end:n}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Sa(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),a.duration=t),r!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${a.duration}. Setting seekable range to ${r}-${n}.`),a.setLiveSeekableRange(r,n)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:r,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${r} codec events expected: ${t}) ${Hc(n)}`),this.tracksReady){var a;const i=(a=this.transferData)==null?void 0:a.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([r,n])=>{if(r){const a=this.tracks[r];t[r]={buffer:n,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}}),this.hls.trigger(_t.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([r])=>{this.executeNext(r)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:r,mediaSource:n}=this;if(!n)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in t){const l=i,o=t[l];if(this.isPending(o)){const c=this.getTrackCodec(o,l),d=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(l)?" Queued":""} ${Hc(o)}`);try{const u=n.addSourceBuffer(d),m=Bje(l),f=[l,u];r[m]=f,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(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:l,mimeType:d,parent:o.id});return}this.trackSourceBuffer(l,o)}}this.bufferCreated()}getTrackCodec(t,r){const n=t.supplemental;let a=t.codec;n&&(r==="video"||r==="audiovideo")&&Fz(n,"video")&&(a=mXs(a,n));const i=mhe(a,t.levelCodec);return i?r.slice(0,5)==="audio"?Wpe(i,this.appendSource):i:""}trackSourceBuffer(t,r){const n=r.buffer;if(!n)return;const a=this.getTrackCodec(r,t);this.tracks[t]={buffer:n,codec:a,container:r.container,levelCodec:r.levelCodec,supplemental:r.supplemental,metadata:r.metadata,id:r.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(i,l)=>{const o=l.removedRanges;o!=null&&o.length&&this.hls.trigger(_t.BUFFER_FLUSHED,{type:i})})}get mediaSrc(){var t,r;const n=((t=this.media)==null||(r=t.querySelector)==null?void 0:r.call(t,"source"))||this.media;return n==null?void 0:n.src}onSBUpdateStart(t){const r=this.currentOp(t);r&&r.onStart()}onSBUpdateEnd(t){var r;if(((r=this.mediaSource)==null?void 0:r.readyState)==="closed"){this.resetBuffer(t);return}const n=this.currentOp(t);n&&(n.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,r){var n;const a=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(n=this.mediaSource)==null?void 0:n.readyState}`);this.error(`${a}`,r),this.hls.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:a,fatal:!1});const i=this.currentOp(t);i&&i.onError(a)}updateTimestampOffset(t,r,n,a,i,l){const o=r-t.timestampOffset;Math.abs(o)>=n&&(this.log(`Updating ${a} SourceBuffer timestampOffset to ${r} (sn: ${i} cc: ${l})`),t.timestampOffset=r)}removeExecutor(t,r,n){const{media:a,mediaSource:i}=this,l=this.tracks[t],o=l==null?void 0:l.buffer;if(!a||!i||!o){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(t);return}const c=Sa(a.duration)?a.duration:1/0,d=Sa(i.duration)?i.duration:1/0,u=Math.max(0,r),m=Math.min(n,c,d);m>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${m}] from the ${t} SourceBuffer`),o.remove(u,m)):this.shiftAndExecuteNext(t)}appendExecutor(t,r){const n=this.tracks[r],a=n==null?void 0:n.buffer;if(!a)throw new wJs(`Attempting to append to the ${r} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,a.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(r=>{this.warn(`SourceBuffer blocked callback ${r}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(r){this.warn(`Callback run without blocking ${this.operationQueue} ${r}`)}}isUpdating(){return this.sourceBuffers.some(([t,r])=>t&&r.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,r=this.sourceBufferTypes){if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:n}=this,a=r.map(l=>this.appendBlocker(l));return r.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(a).then(l=>{n===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(r=>{var n;const a=(n=this.tracks[r])==null?void 0:n.buffer;!a||a.updating||this.shiftAndExecuteNext(r)})}append(t,r,n){this.operationQueue&&this.operationQueue.append(t,r,n)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,r)=>t+(this.isPending(this.tracks[r])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[r])=>t+(r?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,r,n){const a=this.tracks[t];if(!a)return;const i=a.buffer;if(!i)return;const l=n.bind(this,t);a.listeners.push({event:r,listener:l}),i.addEventListener(r,l)}removeBufferListeners(t){const r=this.tracks[t];if(!r)return;const n=r.buffer;n&&(r.listeners.forEach(a=>{n.removeEventListener(a.event,a.listener)}),r.listeners.length=0)}}function pZe(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(r=>{s.removeChild(r)})}function NJs(s,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,s.appendChild(r)}function Bje(s){return s==="audio"?1:0}class qIe{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(_t.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(_t.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,r){const n=this.hls.levels[r.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(t,r){this.media=r.media instanceof HTMLVideoElement?r.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,r){const n=this.hls;this.restrictedLevels=[],this.firstLevel=r.firstLevel,n.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onLevelsUpdated(t,r){this.timer&&Sa(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,r){this.hls.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const r=this.hls,n=this.getMaxLevel(t.length-1);n!==this.autoLevelCapping&&r.logger.log(`Setting autoLevelCapping to ${n}: ${t[n].height}p@${t[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),r.autoLevelCapping=n,r.autoLevelEnabled&&r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(t){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((a,i)=>this.isLevelAllowed(a)&&i<=t);return this.clientRect=null,qIe.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,r={width:0,height:0};if(t){const n=t.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||t.width||0,r.height=n.bottom-n.top||t.height||0)}return this.clientRect=r,r}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(n=>t.bitrate===n.bitrate&&t.width===n.width&&t.height===n.height)}static getMaxLevelByMediaSize(t,r,n){if(!(t!=null&&t.length))return-1;const a=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let i=t.length-1;const l=Math.max(r,n);for(let o=0;o=l||c.height>=l)&&a(c,t[o+1])){i=o;break}}return i}}const kJs={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Xx=kJs,SJs={HLS:"h"},CJs=SJs;class Y_{constructor(t,r){Array.isArray(t)&&(t=t.map(n=>n instanceof Y_?n:new Y_(n))),this.value=t,this.params=r}}const TJs="Dict";function EJs(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 AJs(s,t,r,n){return new Error(`failed to ${s} "${EJs(t)}" as ${r}`,{cause:n})}function Z_(s,t,r){return AJs("serialize",s,t,r)}class Q_t{constructor(t){this.description=t}}const xZe="Bare Item",MJs="Boolean";function IJs(s){if(typeof s!="boolean")throw Z_(s,MJs);return s?"?1":"?0"}function PJs(s){return btoa(String.fromCharCode(...s))}const LJs="Byte Sequence";function DJs(s){if(ArrayBuffer.isView(s)===!1)throw Z_(s,LJs);return`:${PJs(s)}:`}const RJs="Integer";function OJs(s){return s<-999999999999999||99999999999999912)throw Z_(s,zJs);const r=t.toString();return r.includes(".")?r:`${r}.0`}const $Js="String",UJs=/[\x00-\x1f\x7f]+/;function qJs(s){if(UJs.test(s))throw Z_(s,$Js);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function VJs(s){return s.description||s.toString().slice(7,-1)}const HJs="Token";function gZe(s){const t=VJs(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Z_(t,HJs);return t}function t3e(s){switch(typeof s){case"number":if(!Sa(s))throw Z_(s,xZe);return Number.isInteger(s)?J_t(s):BJs(s);case"string":return qJs(s);case"symbol":return gZe(s);case"boolean":return IJs(s);case"object":if(s instanceof Date)return FJs(s);if(s instanceof Uint8Array)return DJs(s);if(s instanceof Q_t)return gZe(s);default:throw Z_(s,xZe)}}const GJs="Key";function s3e(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Z_(s,GJs);return s}function VIe(s){return s==null?"":Object.entries(s).map(([t,r])=>r===!0?`;${s3e(t)}`:`;${s3e(t)}=${t3e(r)}`).join("")}function twt(s){return s instanceof Y_?`${t3e(s.value)}${VIe(s.params)}`:t3e(s)}function WJs(s){return`(${s.value.map(twt).join(" ")})${VIe(s.params)}`}function KJs(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw Z_(s,TJs);const r=s instanceof Map?s.entries():Object.entries(s),n=t!=null&&t.whitespace?" ":"";return Array.from(r).map(([a,i])=>{i instanceof Y_||(i=new Y_(i));let l=s3e(a);return i.value===!0?l+=VIe(i.params):(l+="=",Array.isArray(i.value)?l+=WJs(i):l+=twt(i)),l}).join(`,${n}`)}function swt(s,t){return KJs(s,t)}const zb="CMCD-Object",Pu="CMCD-Request",_C="CMCD-Session",VN="CMCD-Status",YJs={br:zb,ab:zb,d:zb,ot:zb,tb:zb,tpb:zb,lb:zb,tab:zb,lab:zb,url:zb,pb:Pu,bl:Pu,tbl:Pu,dl:Pu,ltc:Pu,mtp:Pu,nor:Pu,nrr:Pu,rc:Pu,sn:Pu,sta:Pu,su:Pu,ttfb:Pu,ttfbb:Pu,ttlb:Pu,cmsdd:Pu,cmsds:Pu,smrt:Pu,df:Pu,cs:Pu,ts:Pu,cid:_C,pr:_C,sf:_C,sid:_C,st:_C,v:_C,msd:_C,bs:VN,bsd:VN,cdn:VN,rtp:VN,bg:VN,pt:VN,ec:VN,e:VN},ZJs={REQUEST:Pu};function XJs(s){return Object.keys(s).reduce((t,r)=>{var n;return(n=s[r])===null||n===void 0||n.forEach(a=>t[a]=r),t},{})}function QJs(s,t){const r={};if(!s)return r;const n=Object.keys(s),a=t?XJs(t):{};return n.reduce((i,l)=>{var o;const c=YJs[l]||a[l]||ZJs.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},r)}function JJs(s){return["ot","sf","st","e","sta"].includes(s)}function eer(s){return typeof s=="number"?Sa(s):s!=null&&s!==""&&s!==!1}const rwt="event";function ter(s,t){const r=new URL(s),n=new URL(t);if(r.origin!==n.origin)return s;const a=r.pathname.split("/").slice(1),i=n.pathname.split("/").slice(1,-1);for(;a[0]===i[0];)a.shift(),i.shift();for(;i.length;)i.shift(),a.unshift("..");return a.join("/")+r.search+r.hash}const yhe=s=>Math.round(s),r3e=(s,t)=>Array.isArray(s)?s.map(r=>r3e(r,t)):s instanceof Y_&&typeof s.value=="string"?new Y_(r3e(s.value,t),s.params):(t.baseUrl&&(s=ter(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),GV=s=>yhe(s/100)*100,ser=(s,t)=>{let r=s;return t.version>=2&&(s instanceof Y_&&typeof s.value=="string"?r=new Y_([s]):typeof s=="string"&&(r=[s])),r3e(r,t)},rer={br:yhe,d:yhe,bl:GV,dl:GV,mtp:GV,nor:ser,rtp:GV,tb:yhe},nwt="request",awt="response",HIe=["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"],ner=["e"],aer=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Qye(s){return aer.test(s)}function ier(s){return HIe.includes(s)||ner.includes(s)||Qye(s)}const iwt=["d","dl","nor","ot","rtp","su"];function oer(s){return HIe.includes(s)||iwt.includes(s)||Qye(s)}const ler=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function cer(s){return HIe.includes(s)||iwt.includes(s)||ler.includes(s)||Qye(s)}const der=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function uer(s){return der.includes(s)||Qye(s)}const her={[awt]:cer,[rwt]:ier,[nwt]:oer};function owt(s,t={}){const r={};if(s==null||typeof s!="object")return r;const n=t.version||s.v||1,a=t.reportingMode||nwt,i=n===1?uer:her[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===awt||a===rwt;c&&!l.includes("ts")&&l.push("ts"),n>1&&!l.includes("v")&&l.push("v");const d=Ac({},rer,t.formatters),u={version:n,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(m=>{let f=s[m];const x=d[m];if(typeof x=="function"&&(f=x(f,u)),m==="v"){if(n===1)return;f=n}m=="pr"&&f===1||(c&&m==="ts"&&!Sa(f)&&(f=Date.now()),eer(f)&&(JJs(m)&&typeof f=="string"&&(f=new Q_t(f)),r[m]=f))}),r}function mer(s,t={}){const r={};if(!s)return r;const n=owt(s,t),a=QJs(n,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=swt(o,{whitespace:!1});return c&&(i[l]=c),i},r)}function fer(s,t,r){return Ac(s,mer(t,r))}const per="CMCD";function xer(s,t={}){return s?swt(owt(s,t),{whitespace:!1}):""}function ger(s,t={}){if(!s)return"";const r=xer(s,t);return encodeURIComponent(r)}function yer(s,t={}){if(!s)return"";const r=ger(s,t);return`${per}=${r}`}const yZe=/CMCD=[^&#]+/;function ver(s,t,r){const n=yer(t,r);if(!n)return s;if(yZe.test(s))return s.replace(yZe,n);const a=s.includes("?")?"&":"?";return`${s}${a}${n}`}class ber{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:Xx.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===Xx.VIDEO||c===Xx.AUDIO||c==Xx.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 r=this.config=t.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||t.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHED,this.onMediaDetached,this),t.on(_t.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHED,this.onMediaDetached,this),t.off(_t.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,r){this.media=r.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,r){var n,a;this.audioBuffer=(n=r.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(a=r.tracks.video)==null?void 0:a.buffer}createData(){var t;return{v:1,sf:CJs.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,r={}){Ac(r,this.createData());const n=r.ot===Xx.INIT||r.ot===Xx.VIDEO||r.ot===Xx.MUXED;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering);const{includeKeys:a}=this;a&&(r=Object.keys(r).reduce((l,o)=>(a.includes(o)&&(l[o]=r[o]),l),{}));const i={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),fer(t.headers,r,i)):t.url=ver(t.url,r,i)}getNextFrag(t){var r;const n=(r=this.hls.levels[t.level])==null?void 0:r.details;if(n){const a=t.sn-n.startSN;return n.fragments[a+1]}}getNextPart(t){var r;const{index:n,fragment:a}=t,i=(r=this.hls.levels[a.level])==null||(r=r.details)==null?void 0:r.partList;if(i){const{sn:l}=a;for(let o=i.length-1;o>=0;o--){const c=i[o];if(c.index===n&&c.fragment.sn===l)return i[o+1]}}}getObjectType(t){const{type:r}=t;if(r==="subtitle")return Xx.TIMED_TEXT;if(t.sn==="initSegment")return Xx.INIT;if(r==="audio")return Xx.AUDIO;if(r==="main")return this.hls.audioTracks.length?Xx.VIDEO:Xx.MUXED}getTopBandwidth(t){let r=0,n;const a=this.hls;if(t===Xx.AUDIO)n=a.audioTracks;else{const i=a.maxAutoLevel,l=i>-1?i+1:a.levels.length;n=a.levels.slice(0,l)}return n.forEach(i=>{i.bitrate>r&&(r=i.bitrate)}),r>0?r:NaN}getBufferLength(t){const r=this.media,n=t===Xx.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:po.bufferInfo(n,r.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,r=this.applyPlaylistData,n=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new n(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){r(i),this.loader.load(i,l,o)}}}createFragmentLoader(){const{fLoader:t}=this.config,r=this.applyFragmentData,n=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new n(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){r(i),this.loader.load(i,l,o)}}}}const _er=3e5;class wer extends yv{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(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,r)=>(t.indexOf(r.pathwayId)===-1&&t.push(r.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const r=this.levels;r&&(this.levels=r.filter(n=>n!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,r){const{contentSteering:n}=r;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(t,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}onError(t,r){const{errorAction:n}=r;if((n==null?void 0:n.action)===Rf.SendAlternateToPenaltyBox&&n.flags===c0.MoveAllAlternatesMatchingHost){const a=this.levels;let i=this._pathwayPriority,l=this.pathwayId;if(r.context){const{groupId:o,pathwayId:c,type:d}=r.context;o&&a?l=this.getPathwayForGroupId(o,d,l):c&&(l=c)}l in this.penalizedPathways||(this.penalizedPathways[l]=performance.now()),!i&&a&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),n.resolved=this.pathwayId!==l),r.details===kr.BUFFER_APPEND_ERROR&&!r.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${r.details} ("${r.error.message}") with content-steering for Pathway: ${l} levels: ${a&&a.length} priorities: ${Hc(i)} penalized: ${Hc(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let r=this.getLevelsForPathway(this.pathwayId);if(r.length===0){const n=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),r=this.getLevelsForPathway(n),this.pathwayId=n}return r.length!==t.length&&this.log(`Found ${r.length}/${t.length} levels in Pathway "${this.pathwayId}"`),r}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(r=>t===r.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let r;const n=this.penalizedPathways,a=performance.now();Object.keys(n).forEach(i=>{a-n[i]>_er&&delete n[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,C_t(r),this.hls.trigger(_t.LEVELS_UPDATED,{levels:r});const d=this.hls.levels[o];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,r,n){const a=this.getLevelsForPathway(n).concat(this.levels||[]);for(let i=0;i{const{ID:l,"BASE-ID":o,"URI-REPLACEMENT":c}=i;if(r.some(u=>u.pathwayId===l))return;const d=this.getLevelsForPathway(o).map(u=>{const m=new nu(u.attrs);m["PATHWAY-ID"]=l;const f=m.AUDIO&&`${m.AUDIO}_clone_${l}`,x=m.SUBTITLES&&`${m.SUBTITLES}_clone_${l}`;f&&(n[m.AUDIO]=f,m.AUDIO=f),x&&(a[m.SUBTITLES]=x,m.SUBTITLES=x);const y=lwt(u.uri,m["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new Bz({attrs:m,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 b=1;b{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":b,"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||f.url),b&&this.clonePathways(b);const N={steeringManifest:y,url:a.toString()};this.hls.trigger(_t.STEERING_MANIFEST_LOADED,N),j&&this.updatePathwayPriority(j)},onError:(u,m,f,x)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${m.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${m.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 b=_.getResponseHeader("Retry-After");b&&(y=parseFloat(b)*1e3)}this.log(`Steering manifest ${m.url} rate limited`);return}this.scheduleRefresh(this.uri||m.url,y)},onTimeout:(u,m,f)=>{this.log(`Timeout loading steering manifest (${m.url})`),this.scheduleRefresh(this.uri||m.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,r=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const a=(n=this.hls)==null?void 0:n.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},r)}}function vZe(s,t,r,n){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=Ac({},l);return o.details=void 0,o.attrs=new nu(o.attrs),o.url=o.attrs.URI=lwt(l.url,l.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),o.groupId=o.attrs["GROUP-ID"]=t[a],o.attrs["PATHWAY-ID"]=n,o});s.push(...i)})}function lwt(s,t,r,n){const{HOST:a,PARAMS:i,[r]:l}=n;let o;t&&(o=l==null?void 0:l[t],o&&(s=o));const c=new self.URL(s);return a&&!o&&(c.host=a),i&&Object.keys(i).sort().forEach(d=>{d&&c.searchParams.set(d,i[d])}),c.href}class FP extends yv{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=FP.CDMCleanupPromise?[FP.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=r=>{const{initDataType:n,initData:a}=r,i=`"${r.type}" event: init data type: "${n}"`;if(this.debug(i),a!==null){if(!this.keyFormatPromise){let l=Object.keys(this.keySystemAccessPromises);l.length||(l=YO(this.config));const o=l.map(Ije).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=phe(l);if(n!=="sinf"||o!==uu.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${o}`);return}let c;try{const x=am(new Uint8Array(a)),y=PIe(JSON.parse(x).sinf),_=s_t(y);if(!_)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(_.subarray(8,24))}catch(x){this.warn(`${i} Failed to parse sinf: ${x}`);return}const d=Of(c),{keyIdToKeySessionPromise:u,mediaKeySessions:m}=this;let f=u[d];for(let x=0;xthis.generateRequestWithPreferredKeySession(y,n,a,"encrypted-event-key-match")),f.catch(j=>this.handleError(j));break}}f||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${m.length}.`))}).catch(l=>this.handleError(l))}},this.onWaitingForKey=r=>{this.log(`"${r.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(_t.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(_t.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(_t.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(_t.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:r,widevineLicenseUrl:n}=this.config,a=r==null?void 0:r[t];if(a)return a.licenseUrl;if(t===uu.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(t){const r=this.getLicenseServerUrl(t);if(r===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return r}getServerCertificateUrl(t){const{drmSystems:r}=this.config,n=r==null?void 0:r[t];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const r=this.hls.levels,n=(l,o,c)=>!!l&&c.indexOf(l)===o,a=r.map(l=>l.audioCodec).filter(n),i=r.map(l=>l.videoCodec).filter(n);return a.length+i.length===0&&i.push("avc1.42e01e"),new Promise((l,o)=>{const c=d=>{const u=d.shift();this.getMediaKeysPromise(u,a,i).then(m=>l({keySystem:u,mediaKeys:m})).catch(m=>{d.length?c(d):m instanceof i0?o(m):o(new i0({type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_NO_ACCESS,error:m,fatal:!0},m.message))})};c(t)})}requestMediaKeySystemAccess(t,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let a=`Configured requestMediaKeySystemAccess is not a function ${n}`;return v_t===null&&self.location.protocol==="http:"&&(a=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(a))}return n(t,r)}getMediaKeysPromise(t,r,n){var a;const i=sQs(t,r,n,this.config.drmSystemOptions||{});let l=this.keySystemAccessPromises[t],o=(a=l)==null?void 0:a.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Hc(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 m=c.mediaKeys=d.createMediaKeys().then(f=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,u.then(x=>x?this.setMediaKeysServerCertificate(f,t,x):f)));return m.catch(f=>{this.error(`Failed to create media-keys for "${t}"}: ${f}`)}),m})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${Of(t.keyId||[])} keyUri: ${t.uri}`);const a=n.createSession(),i={decryptdata:t,keySystem:r,mediaKeys:n,mediaKeysSession:a,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const r=t.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(t),a=WV(r),i="cenc";this.keyIdToKeySessionPromise[a]=this.generateRequestWithPreferredKeySession(n,i,r.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,r){const n=t.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${Of(t.decryptdata.keyId||[])} } (data length: ${r.byteLength})`),n.update(r)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Ije(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:r,mediaKeys:n})=>this.attemptSetMediaKeys(r,n))}selectKeySystem(t){return new Promise((r,n)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:a})=>{const i=Ije(a);i?r(i):n(new Error(`Unable to find format for key-system "${a}"`))}).catch(n)})}selectKeySystemFormat(t){const r=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(t){const r=YO(this.config),n=t.map(phe).filter(a=>!!a&&r.indexOf(a)!==-1);return this.selectKeySystem(n)}getKeyStatus(t){const{mediaKeySessions:r}=this;for(let n=0;n(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:r}))))).then(c=>{const d="cenc",u=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,u,"playlist-key")});return o.catch(c=>this.handleError(c,t.frag)),this.keyIdToKeySessionPromise[n]=o,o}return l.catch(o=>{if(o instanceof i0){const c=uc({},o.data);this.getKeyStatus(r)==="internal-error"&&(c.decryptdata=r);const d=new i0(c,o.message);this.handleError(d,t.frag)}}),l}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,r){if(this.hls)if(t instanceof i0){r&&(t.data.frag=r);const n=t.data.decryptdata;this.error(`${t.message}${n?` (${Of(n.keyId||[])})`:""}`),this.hls.trigger(_t.ERROR,t.data)}else this.error(t.message),this.hls.trigger(_t.ERROR,{type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const r=WV(t),n=this.keyIdToKeySessionPromise[r];if(!n){const a=phe(t.keyFormat),i=a?[a]:YO(this.config);return this.attemptKeySystemAccess(i)}return n}getKeySystemSelectionPromise(t){if(t.length||(t=YO(this.config)),t.length===0)throw new i0({type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Hc({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,r){if(this.mediaResolved=void 0,this.mediaKeys===r)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(r):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=r,this.media.setMediaKeys(r).then(i).catch(l)}}));return this.mediaKeys=r,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),n.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>n.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,r,n,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const y=l.call(this.hls,r,n,t);if(!y)throw new Error("Invalid response from configured generateRequest filter");r=y.initDataType,n=y.initData?y.initData:null,t.decryptdata.pssh=n?new Uint8Array(n):null}catch(y){if(this.warn(y.message),this.hls&&this.hls.config.debug)throw y}if(n===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=WV(t.decryptdata),c=t.decryptdata.uri;this.log(`Generating key-session request for "${a}" keyId: ${o} URI: ${c} (init data type: ${r} length: ${n.byteLength})`);const d=new DIe,u=t._onmessage=y=>{const _=t.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:b,message:j}=y;this.log(`"${b}" message event for session "${_.sessionId}" message size: ${j.byteLength}`),b==="license-request"||b==="license-renewal"?this.renewLicense(t,j).catch(N=>{d.eventNames().length?d.emit("error",N):this.handleError(N)}):b==="license-release"?t.keySystem===uu.FAIRPLAY&&this.updateKeySession(t,YCe("acknowledged")).then(()=>this.removeSession(t)).catch(N=>this.handleError(N)):this.warn(`unhandled media key message type "${b}"`)},m=(y,_)=>{_.keyStatus=y;let b;y.startsWith("usable")?d.emit("resolved"):y==="internal-error"||y==="output-restricted"||y==="output-downscaled"?b=bZe(y,_.decryptdata):y==="expired"?b=new Error(`key expired (keyId: ${o})`):y==="released"?b=new Error("key released"):y==="status-pending"||this.warn(`unhandled key status change "${y}" (keyId: ${o})`),b&&(d.eventNames().length?d.emit("error",b):this.handleError(b))},f=t._onkeystatuseschange=y=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const b=this.getKeyStatuses(t);if(!Object.keys(b).some(A=>b[A]!=="status-pending"))return;if(b[o]==="expired"){this.log(`Expired key ${Hc(b)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let N=b[o];if(N)m(N,t);else{var C;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(C=t.keyStatusTimeouts)[o]||(C[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.`),m(E,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),N="internal-error",m(N,t)},1e3)),this.log(`No status for keyId ${o} (${Hc(b)}).`)}};Cx(t.mediaKeysSession,"message",u),Cx(t.mediaKeysSession,"keystatuseschange",f);const x=new Promise((y,_)=>{d.on("error",_),d.on("resolved",y)});return t.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(y=>{throw new i0({type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_NO_SESSION,error:y,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${y}`)}).then(()=>x).catch(y=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw y}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const r={};return t.mediaKeysSession.keyStatuses.forEach((n,a)=>{if(typeof a=="string"&&typeof n=="object"){const o=a;a=n,n=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===uu.PLAYREADY&&i.length===16){const o=Of(i);r[o]=n,g_t(i)}const l=Of(i);n==="internal-error"&&(this.bannedKeyIds[l]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),r[l]=n}),r}fetchServerCertificate(t){const r=this.config,n=r.loader,a=new n(r),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=r.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(f,x,y,_)=>{l(f.data)},onError:(f,x,y,_)=>{o(new i0({type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:uc({url:c.url,data:void 0},f)},`"${t}" certificate request failed (${i}). Status: ${f.code} (${f.text})`))},onTimeout:(f,x,y)=>{o(new i0({type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(f,x,y)=>{o(new Error("aborted"))}};a.load(c,u,m)})):Promise.resolve()}setMediaKeysServerCertificate(t,r,n){return new Promise((a,i)=>{t.setServerCertificate(n).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),a(t)}).catch(l=>{i(new i0({type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:l,fatal:!0},l.message))})})}renewLicense(t,r){return this.requestLicense(t,new Uint8Array(r)).then(n=>this.updateKeySession(t,new Uint8Array(n)).catch(a=>{throw new i0({type:di.KEY_SYSTEM_ERROR,details:kr.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:a,fatal:!1},a.message)}))}unpackPlayReadyKeyMessage(t,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const a=new DOMParser().parseFromString(n,"application/xml"),i=a.querySelectorAll("HttpHeader");if(i.length>0){let u;for(let m=0,f=i.length;m in key message");return YCe(atob(d))}setupLicenseXHR(t,r,n,a){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,r,n,a)}).catch(l=>{if(!n.decryptdata)throw l;return t.open("POST",r,!0),i.call(this.hls,t,r,n,a)}).then(l=>(t.readyState||t.open("POST",r,!0),{xhr:t,licenseChallenge:l||a})):(t.open("POST",r,!0),Promise.resolve({xhr:t,licenseChallenge:a}))}requestLicense(t,r){const n=this.config.keyLoadPolicy.default;return new Promise((a,i)=>{const l=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${l}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,o,l,t)}catch(u){this.error(u)}a(c)}else{const c=n.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)i(new i0({type:di.KEY_SYSTEM_ERROR,details:kr.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,r).then(a,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,l,t,r).then(({xhr:c,licenseChallenge:d})=>{t.keySystem==uu.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,Cx(n,"encrypted",this.onMediaEncrypted),Cx(n,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=n.mediaKeys}onMediaDetached(){const t=this.media;t&&(ug(t,"encrypted",this.onMediaEncrypted),ug(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const r=this.mediaResolved;if(r&&r(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,SS.clearKeyUriToKeyIdMap();const i=a.length;FP.CDMCleanupPromise=Promise.all(a.map(l=>this.removeSession(l)).concat((n==null||(t=n.setMediaKeys(null))==null?void 0:t.catch(l=>{this.log(`Could not clear media keys: ${l}`),this.hls&&this.hls.trigger(_t.ERROR,{type:di.OTHER_ERROR,details:kr.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(_t.ERROR,{type:di.OTHER_ERROR,details:kr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${l}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((a,i)=>(a.indexOf(i.keyFormat)===-1&&a.push(i.keyFormat),a),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(t){const{mediaKeysSession:r,licenseXhr:n,decryptdata:a}=t;if(r){this.log(`Remove licenses and keys and close session "${r.sessionId}" keyId: ${Of((a==null?void 0:a.keyId)||[])}`),t._onmessage&&(r.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:l}=t;l&&Object.keys(l).forEach(d=>self.clearTimeout(l[d]));const{drmSystemOptions:o}=this.config;return(nQs(o)?new Promise((d,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(d).catch(u)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(_t.ERROR,{type:di.OTHER_ERROR,details:kr.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>r.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(_t.ERROR,{type:di.OTHER_ERROR,details:kr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}FP.CDMCleanupPromise=void 0;function WV(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Of(s.keyId)}function jer(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 i0 extends Error{constructor(t,r){super(r),this.data=void 0,t.error||(t.error=new Error(r)),this.data=t,t.err=t.error}}function bZe(s,t){const r=s==="output-restricted",n=r?kr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:kr.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new i0({type:di.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":`key status changed to "${s}"`)}class Ner{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(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,r){const n=this.hls.config;if(n.capLevelOnFPSDrop){const a=r.media instanceof self.HTMLVideoElement?r.media:null;this.media=a,a&&typeof a.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,r,n){const a=performance.now();if(r){if(this.lastTime){const i=a-this.lastTime,l=n-this.lastDroppedFrames,o=r-this.lastDecodedFrames,c=1e3*l/i,d=this.hls;if(d.trigger(_t.FPS_DROP,{currentDropped:l,currentDecoded:o,totalDroppedFrames:n}),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(_t.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const r=t.getVideoPlaybackQuality();this.checkFPS(t,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}function cwt(s,t){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=s,t.dispatchEvent(r)}function dwt(s,t){const r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(t.id))try{if(s.addCue(t),!s.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(n){fc.debug(`[texttrack-utils]: ${n}`);try{const a=new self.TextTrackCue(t.startTime,t.endTime,t.text);a.id=t.id,s.addCue(a)}catch(a){fc.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}r==="disabled"&&(s.mode=r)}function DI(s,t){const r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues)for(let n=s.cues.length;n--;)t&&s.cues[n].removeEventListener("enter",t),s.removeCue(s.cues[n]);r==="disabled"&&(s.mode=r)}function n3e(s,t,r,n){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=Ser(s.cues,t,r);for(let l=0;ls[r].endTime)return-1;let n=0,a=r,i;for(;n<=a;)if(i=Math.floor((a+n)/2),ts[i].startTime&&n-1)for(let i=a,l=s.length;i=t&&o.endTime<=r)n.push(o);else if(o.startTime>r)return n}return n}function vhe(s){const t=[];for(let r=0;rthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=null;const n=vhe(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.LEVEL_LOADING,this.onLevelLoading,this),t.on(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_t.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(_t.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.LEVEL_LOADING,this.onLevelLoading,this),t.off(_t.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_t.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(_t.ERROR,this.onError,this)}onMediaAttached(t,r){this.media=r.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,r){const n=this.media;if(!n)return;const a=!!r.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,a)return;vhe(n.textTracks).forEach(l=>{DI(l)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(t,r){const{id:n,groupId:a,details:i}=r,l=this.tracksInGroup[n];if(!l||l.groupId!==a){this.warn(`Subtitle track with id:${n} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=r.details,this.log(`Subtitle track ${n} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(t,r){this.switchLevel(r.level)}onLevelSwitching(t,r){this.switchLevel(r.level)}switchLevel(t){const r=this.hls.levels[t];if(!r)return;const n=r.subtitleGroups||null,a=this.groupIds;let i=this.currentTrack;if(!n||(a==null?void 0:a.length)!==(n==null?void 0:n.length)||n!=null&&n.some(l=>(a==null?void 0:a.indexOf(l))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(u=>!n||n.indexOf(u.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(u=>u.default)&&(this.selectDefaultTrack=!1),l.forEach((u,m)=>{u.id=m});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const u=x_(o,l);if(u>-1)i=l[u];else{const m=x_(o,this.tracks);i=this.tracks[m]}}let c=this.findTrackId(i);c===-1&&i&&(c=this.findTrackId(null));const d={subtitleTracks:l};this.log(`Updating subtitle tracks, ${l.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(_t.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(t){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let a=0;a-1){const i=this.tracksInGroup[a];return this.setSubtitleTrack(a),i}else{if(n)return null;{const i=x_(t,r);if(i>-1)return r[i]}}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,r){super.loadingPlaylist(t,r);const n=t.id,a=t.groupId,i=this.getUrlWithDirectives(t.url,r),l=t.details,o=l==null?void 0:l.age;this.log(`Loading subtitle ${n} "${t.name}" lang:${t.lang} group:${a}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${i}`),this.hls.trigger(_t.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:a,deliveryDirectives:r||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const r=vhe(t.textTracks),n=this.currentTrack;let a;if(n&&(a=r.filter(i=>e3e(n,i))[0],a||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(r).forEach(i=>{i.mode!=="disabled"&&i!==a&&(i.mode="disabled")}),a){const i=this.subtitleDisplay?"showing":"hidden";a.mode!==i&&(a.mode=i)}}setSubtitleTrack(t){const r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=r.length||!Sa(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,a=r[t]||null;if(this.trackId=t,this.currentTrack=a,this.toggleTrackModes(),!a){this.hls.trigger(_t.SUBTITLE_TRACK_SWITCH,{id:t});return}const i=!!a.details&&!a.details.live;if(t===this.trackId&&a===n&&i)return;this.log(`Switching to subtitle-track ${t}`+(a?` "${a.name}" lang:${a.lang} group:${a.groupId}`:""));const{id:l,groupId:o="",name:c,type:d,url:u}=a;this.hls.trigger(_t.SUBTITLE_TRACK_SWITCH,{id:l,groupId:o,name:c,type:d,url:u});const m=this.switchParams(a.url,n==null?void 0:n.details,a.details);this.loadPlaylist(m)}}function Ter(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),r=t.toString();return URL.revokeObjectURL(t),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const i=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(a=="x"?i:i&3|8).toString(16)})}}}function Q7(s){let t=5381,r=s.length;for(;r;)t=t*33^s.charCodeAt(--r);return(t>>>0).toString()}const zP=.025;let sxe=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function Eer(s,t,r){return`${s.identifier}-${r+1}-${Q7(t)}`}class Aer{constructor(t,r){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,(t=this.assetListLoader)==null||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var r;if(t>0&&t>=this.assetList.length)return!0;const n=this.playoutLimit;return t<=0||isNaN(n)?!1:n===0?!0:(((r=this.assetList[t])==null?void 0:r.startOffset)||0)>n}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const r=this.dateRange.tagAnchor;if(r)return $je(t,r)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const r=this.dateRange.startTime,n=$je(r,t);return r-n<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,r=Sa(t)?t:this.duration;return this.cumulativeDuration+r}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const r=this.resumeAnchor;if(r)return $je(t,r)}return t}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return Mer(this)}}function $je(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function aI(s){const t=s.timelineStart,r=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+r).toFixed(2)}]`}class Ier{constructor(t,r,n,a){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(_t.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(r);this.interstitial=n,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(_t.LEVEL_LOADED,l),i.once(_t.AUDIO_TRACK_LOADED,l),i.once(_t.SUBTITLE_TRACK_LOADED,l),i.on(_t.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(_t.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(_t.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let r=this.assetItem.uri;try{r=uwt(r,t.config.primarySessionId||"").href}catch{}t.loadSource(r)}}bufferedInPlaceToEnd(t){var r;if(!this.appendInPlace)return!1;if((r=this.hls)!=null&&r.bufferedToEnd)return!0;if(!t)return!1;const n=Math.min(this._bufferedEosTime||1/0,this.duration),a=this.timelineOffset,i=po.bufferInfo(t,a,0);return this.getAssetTime(i.end)>=n-.02}reachedPlayout(t){const n=this.interstitial.playoutLimit;return this.startOffset+t>=n}get destroyed(){var t;return!((t=this.hls)!=null&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return((t=this.hls)==null?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const r=po.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(r.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const r=this.interstitial.playoutLimit;if(r){const n=r-this.startOffset;if(n>0&&n1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const r=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,t-r),n)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var t;(t=this.hls)!=null&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var r;this.loadSource(),(r=this.hls)==null||r.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,(t=this.hls)==null||t.detachMedia()}resumeBuffering(){var t;(t=this.hls)==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.hls)==null||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),((t=this.hls)==null?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const r=n=>delete n.details;t.levels.forEach(r),t.allAudioTracks.forEach(r),t.allSubtitleTracks.forEach(r),this.hasDetails=!1}}on(t,r,n){var a;(a=this.hls)==null||a.on(t,r)}once(t,r,n){var a;(a=this.hls)==null||a.once(t,r)}off(t,r,n){var a;(a=this.hls)==null||a.off(t,r)}toString(){var t;return`HlsAssetPlayer: ${aI(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const _Ze=.033;class Per extends yv{constructor(t,r){super("interstitials-sched",r),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,r){return this.events?this.events.reduce((n,a)=>t<=a.startOffset&&r>a.startOffset?(delete a.error,n+1):n,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,r){if(t.event)return this.findEventIndex(t.event.identifier);let n=-1;t.nextEvent?n=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(n=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[n]||(r===void 0&&(r=t.start),n=this.findItemIndexAtTime(r));n>=0&&(i=a[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(t,r){const n=this.items;if(n)for(let a=0;ai.start&&t1)for(let i=0;io&&(r!o.includes(d.identifier)):[];l.length&&l.sort((d,u)=>{const m=d.cue.pre,f=d.cue.post,x=u.cue.pre,y=u.cue.post;if(m&&!x)return-1;if(x&&!m||f&&!y)return 1;if(y&&!f)return-1;if(!m&&!x&&!f&&!y){const _=d.startTime,b=u.startTime;if(_!==b)return _-b}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,r=[],n=!1){const a=this.events||[];if(a.length||r.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(n||r.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(r,i))}}parseDateRanges(t,r,n){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,r);let c=0,d=0;if(t.forEach((u,m)=>{const f=u.cue.pre,x=u.cue.post,y=t[m-1]||null,_=u.appendInPlace,b=x?i:u.startOffset,j=u.duration,N=u.timelineOccupancy===sxe.Range?j:0,C=u.resumptionOffset,A=(y==null?void 0:y.startTime)===b,E=b+u.cumulativeDuration;let D=_?E+j:b+C;if(f||!x&&b<=0){const F=d;d+=N,u.timelineStart=E;const O=l;l+=j,n.push({event:u,start:E,end:D,playout:{start:O,end:l},integrated:{start:F,end:d}})}else if(b<=i){if(!A){const B=b-c;if(B>_Ze){const K=c,Z=d;d+=B;const Q=l;l+=B;const W={previousEvent:t[m-1]||null,nextEvent:u,start:K,end:K+B,playout:{start:Q,end:l},integrated:{start:Z,end:d}};n.push(W)}else B>0&&y&&(y.cumulativeDuration+=B,n[n.length-1].end=b)}x&&(D=E),u.timelineStart=E;const F=d;d+=N;const O=l;l+=j,n.push({event:u,start:E,end:D,playout:{start:O,end:l},integrated:{start:F,end:d}})}else return;const R=u.resumeTime;x||R>i?c=i:c=R}),c{const d=o.cue.pre,u=o.cue.post,m=d?0:u?a:o.startTime;this.updateAssetDurations(o),l===m?o.cumulativeDuration=i:(i=0,l=m),!u&&o.snapOptions.in&&(o.resumeAnchor=VA(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,r)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1zP?(this.log(`"${t.identifier}" resumption ${n} not aligned with estimated timeline end ${a}`),!1):!Object.keys(r).some(l=>{const o=r[l].details,c=o.edge;if(n>=c)return this.log(`"${t.identifier}" resumption ${n} past ${l} playlist end ${c}`),!1;const d=VA(null,o.fragments,n);if(!d)return this.log(`"${t.identifier}" resumption ${n} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=l==="audio"?.175:0;return Math.abs(d.start-n){const b=f.data,j=b==null?void 0:b.ASSETS;if(!Array.isArray(j)){const N=this.assignAssetListError(t,kr.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),y.url,x,_);this.hls.trigger(_t.ERROR,N);return}t.assetListResponse=b,this.hls.trigger(_t.ASSET_LIST_LOADED,{event:t,assetListResponse:b,networkDetails:_})},onError:(f,x,y,_)=>{const b=this.assignAssetListError(t,kr.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${f.code} ${f.text} (${x.url})`),x.url,_,y);this.hls.trigger(_t.ERROR,b)},onTimeout:(f,x,y)=>{const _=this.assignAssetListError(t,kr.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${x.url})`),x.url,f,y);this.hls.trigger(_t.ERROR,_)}};return o.load(c,u,m),this.hls.trigger(_t.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,r,n,a,i,l){return t.error=n,{type:di.NETWORK_ERROR,details:r,fatal:!1,interstitial:t,url:a,error:n,networkDetails:l,stats:i}}}function wZe(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function Z6(s,t){return`[${s}] Advancing timeline position to ${t}`}class Der extends yv{constructor(t,r){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled||!this.schedule)return;const a=n-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=n,this.bufferedPos=n;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(n,n-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&n=o.end){var c;const x=this.findItemIndex(o);let y=this.schedule.findItemIndexAtTime(n);if(y===-1&&(y=x+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${n} (resolving from ${x} to ${y})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&y>x){const _=this.schedule.findJumpRestrictedIndex(x+1,y);if(_>x){this.setSchedulePosition(_);return}}this.setSchedulePosition(y);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const x=o.event.assetList[0];x&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,x))}return}const u=d.timelineStart,m=d.duration||0;if(l&&n=u+m){var f;(f=o.event)!=null&&f.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,d)}},this.onTimeupdate=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),n>this.timelinePos)this.timelinePos=n,n>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(n>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);n>=l&&this.setScheduleToAssetAtTime(n,i)},this.onScheduleUpdate=(n,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,u=n.map(_=>_.identifier),m=!!(o.length||u.length);(m||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(_=>e1(_))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let f=null,x=null;l&&(f=this.updateItem(l,this.timelinePos),this.itemsMatch(l,f)?this.playingItem=f:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const y=this.bufferingItem;if(y&&(x=this.updateItem(y,this.bufferedPos),this.itemsMatch(y,x)?this.bufferingItem=x:y.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(y.event,null))),n.forEach(_=>{_.assetList.forEach(b=>{this.clearAssetPlayer(b.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const b=_.assetItem.timelineStart,j=_.timelineOffset-b;if(j)try{_.timelineOffset=b}catch(N){Math.abs(j)>zP&&this.warn(`${N} ("${_.assetId}" ${_.timelineOffset}->${b})`)}}}),m||a){if(this.hls.trigger(_t.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(f,l),y&&x!==f&&this.trimInPlace(x,y),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=r,this.assetListLoader=new Ler(t),this.schedule=new Per(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(_t.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(_t.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(_t.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(_t.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(_t.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(_t.BUFFER_APPENDED,this.onBufferAppended,this),t.on(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(_t.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(_t.MEDIA_ENDED,this.onMediaEnded,this),t.on(_t.ERROR,this.onError,this),t.on(_t.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(_t.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(_t.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(_t.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(_t.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(_t.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(_t.BUFFER_CODECS,this.onBufferCodecs,this),t.off(_t.BUFFER_APPENDED,this.onBufferAppended,this),t.off(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(_t.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(_t.MEDIA_ENDED,this.onMediaEnded,this),t.off(_t.ERROR,this.onError,this),t.off(_t.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){ug(t,"play",this.onPlay),ug(t,"pause",this.onPause),ug(t,"seeking",this.onSeeking),ug(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,r){const n=this.media=r.media;Cx(n,"seeking",this.onSeeking),Cx(n,"timeupdate",this.onTimeupdate),Cx(n,"play",this.onPlay),Cx(n,"pause",this.onPause)}onMediaAttached(t,r){const n=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(n);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,r){const n=!!r.transferMedia,a=this.media;if(this.media=null,!n&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,r=()=>t.bufferingItem||t.waitingItem,n=m=>m&&t.getAssetPlayer(m.identifier),a=(m,f,x,y,_)=>{if(m){let b=m[f].start;const j=m.event;if(j){if(f==="playout"||j.timelineOccupancy!==sxe.Point){const N=n(x);(N==null?void 0:N.interstitial)===j&&(b+=N.assetItem.startOffset+N[_])}}else{const N=y==="bufferedPos"?l():t[y];b+=N-m.start}return b}return 0},i=(m,f)=>{var x;if(m!==0&&f!=="primary"&&(x=t.schedule)!=null&&x.length){var y;const _=t.schedule.findItemIndexAtTime(m),b=(y=t.schedule.items)==null?void 0:y[_];if(b){const j=b[f].start-b.start;return m+j}}return m},l=()=>{const m=t.bufferedPos;return m===Number.MAX_VALUE?o("primary"):Math.max(m,0)},o=m=>{var f,x;return(f=t.primaryDetails)!=null&&f.live?t.primaryDetails.edge:((x=t.schedule)==null?void 0:x.durations[m])||0},c=(m,f)=>{var x,y;const _=t.effectivePlayingItem;if(_!=null&&(x=_.event)!=null&&x.restrictions.skip||!t.schedule)return;t.log(`seek to ${m} "${f}"`);const b=t.effectivePlayingItem,j=t.schedule.findItemIndexAtTime(m,f),N=(y=t.schedule.items)==null?void 0:y[j],C=t.getBufferingPlayer(),A=C==null?void 0:C.interstitial,E=A==null?void 0:A.appendInPlace,D=b&&t.itemsMatch(b,N);if(b&&(E||D)){const R=n(t.playingAsset),F=(R==null?void 0:R.media)||t.primaryMedia;if(F){const O=f==="primary"?F.currentTime:a(b,f,t.playingAsset,"timelinePos","currentTime"),B=m-O,K=(E?O:F.currentTime)+B;if(K>=0&&(!R||E||K<=R.duration)){F.currentTime=K;return}}}if(N){let R=m;if(f!=="primary"){const O=N[f].start,B=m-O;R=N.start+B}const F=!t.isInterstitial(N);if((!t.isInterstitial(b)||b.event.appendInPlace)&&(F||N.event.appendInPlace)){const O=t.media||(E?C==null?void 0:C.media:null);O&&(O.currentTime=R)}else if(b){const O=t.findItemIndex(b);if(j>O){const K=t.schedule.findJumpRestrictedIndex(O+1,j);if(K>O){t.setSchedulePosition(K);return}}let B=0;if(F)t.timelinePos=R,t.checkBuffer();else{const K=N.event.assetList,Z=m-(N[f]||N).start;for(let Q=K.length;Q--;){const W=K[Q];if(W.duration&&Z>=W.startOffset&&Z{const m=t.effectivePlayingItem;if(t.isInterstitial(m))return m;const f=r();return t.isInterstitial(f)?f:null},u={get bufferedEnd(){const m=r(),f=t.bufferingItem;if(f&&f===m){var x;return a(f,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-f.playout.start||((x=t.bufferingAsset)==null?void 0:x.startOffset)||0}return 0},get currentTime(){const m=d(),f=t.effectivePlayingItem;return f&&f===m?a(f,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-f.playout.start:0},set currentTime(m){const f=d(),x=t.effectivePlayingItem;x&&x===f&&c(m+x.playout.start,"playout")},get duration(){const m=d();return m?m.playout.end-m.playout.start:0},get assetPlayers(){var m;const f=(m=d())==null?void 0:m.event.assetList;return f?f.map(x=>t.getAssetPlayer(x.identifier)):[]},get playingIndex(){var m;const f=(m=d())==null?void 0:m.event;return f&&t.effectivePlayingAsset?f.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var m;return((m=t.schedule)==null||(m=m.events)==null?void 0:m.slice(0))||[]},get schedule(){var m;return((m=t.schedule)==null||(m=m.items)==null?void 0:m.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return r()},get bufferingIndex(){const m=r();return t.findItemIndex(m)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const m=t.effectivePlayingItem;return t.findItemIndex(m)},primary:{get bufferedEnd(){return l()},get currentTime(){const m=t.timelinePos;return m>0?m:0},set currentTime(m){c(m,"primary")},get duration(){return o("primary")},get seekableStart(){var m;return((m=t.primaryDetails)==null?void 0:m.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(r(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(m){c(m,"integrated")},get duration(){return o("integrated")},get seekableStart(){var m;return i(((m=t.primaryDetails)==null?void 0:m.fragmentStart)||0,"integrated")}},skip:()=>{const m=t.effectivePlayingItem,f=m==null?void 0:m.event;if(f&&!f.restrictions.skip){const x=t.findItemIndex(m);if(f.appendInPlace){const y=m.playout.start+m.event.duration;c(y+.001,"playout")}else t.advanceAfterAssetEnded(f,x,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const r=this.playingItem,n=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!r||!n?!1:this.findItemIndex(r)===n.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,r;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(r=a)==null?void 0:r.currentTime;if(!(i===void 0||!Sa(i)))return i}get primaryMedia(){var t;return this.media||((t=this.detachedData)==null?void 0:t.media)||null}isInterstitial(t){return!!(t!=null&&t.event)}retreiveMediaSource(t,r){const n=this.getAssetPlayer(t);n&&this.transferMediaFromPlayer(n,r)}transferMediaFromPlayer(t,r){const n=t.interstitial.appendInPlace,a=t.media;if(n&&a===this.primaryMedia){if(this.bufferingAsset=null,(!r||this.isInterstitial(r)&&!r.event.appendInPlace)&&r&&a){this.detachedData={media:a};return}const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Hc(i)}`),this.detachedData=i}else r&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,r){var n,a;if(t.media===r)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(n=this.detachedData)==null?void 0:n.mediaSource;let 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 ${Hc(i)}`);else if(!this.detachedData||l.media===r){const y=this.playerQueue;y.length>1&&y.forEach(_=>{if(o&&_.interstitial.appendInPlace!==c){const b=_.interstitial;this.clearInterstitial(_.interstitial,null),b.appendInPlace=!1,b.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${b}`)}}),this.hls.detachMedia(),this.detachedData={media:r}}}const m=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",f=m&&i?i:r;this.log(`${m?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u} (media.currentTime: ${r.currentTime})`);const x=this.schedule;if(f===i&&x){const y=o&&t.assetId===x.assetIdAtEnd;f.overrides={duration:x.duration,endOfStream:!o||y,cueRemoval:!o}}t.attachMedia(f)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,r=t==null?void 0:t.events;if(!r||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const n=this.timelinePos,a=this.effectivePlayingItem;if(n===-1){const i=this.hls.startPosition;if(this.timelinePos=i,r.length===0)this.setSchedulePosition(0);else if(r[0].cue.pre){this.log(Z6("checkStart (preroll)",i));const l=t.findEventIndex(r[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(Z6("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(Z6("checkStart (playing item)",a.start));const i=t.findItemIndex(a);this.setSchedulePosition(i)}}advanceAssetBuffering(t,r){const n=t.event,a=n.findAssetIndex(r),i=Uje(n,a);if(!n.isAssetPastPlayoutLimit(i))this.bufferedToEvent(t,i);else if(this.schedule){var l;const o=(l=this.schedule.items)==null?void 0:l[this.findItemIndex(t)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(t,r,n){const a=Uje(t,n);if(t.isAssetPastPlayoutLimit(a)){if(this.schedule){const i=this.schedule.items;if(i){const l=r+1,o=i.length;if(l>=o){this.setSchedulePosition(-1);return}const c=t.resumeTime;this.timelinePos=0?a[t]:null;this.log(`setSchedulePosition ${t}, ${r} (${i&&e1(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const u=l.event,m=this.playingAsset,f=m==null?void 0:m.identifier,x=f?this.getAssetPlayer(f):null;if(x&&f&&(!this.eventItemsMatch(l,i)||r!==void 0&&f!==u.assetList[r].identifier)){var c;const y=u.findAssetIndex(m);if(this.log(`INTERSTITIAL_ASSET_ENDED ${y+1}/${u.assetList.length} ${aI(m)}`),this.endedAsset=m,this.playingAsset=null,this.hls.trigger(_t.INTERSTITIAL_ASSET_ENDED,{asset:m,assetListIndex:y,event:u,schedule:a.slice(0),scheduleIndex:t,player:x}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),y);return}this.retreiveMediaSource(f,i),x.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&x.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${e1(l)}`),u.hasPlayed=!0,this.hls.trigger(_t.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,r,l,o)}return}}this.advanceSchedule(t,a,r,l,o)}advanceSchedule(t,r,n,a,i){const l=this.schedule;if(!l)return;const o=r[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const m=u.interstitial,f=l.findEventIndex(m.identifier);(ft+1)&&this.clearInterstitial(m,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(n===void 0){n=l.findAssetIndex(u,this.timelinePos);const y=Uje(u,n-1);if(u.isAssetPastPlayoutLimit(y)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,n);return}n=y}const m=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let f=this.preloadAssets(u,n);if(this.eventItemsMatch(o,m||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${e1(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(_t.INTERSTITIAL_STARTED,{event:u,schedule:r.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 x=u.assetList[n];if(!x){this.advanceAfterAssetEnded(u,t,n||0);return}if(f||(f=this.getAssetPlayer(x.identifier)),f===null||f.destroyed){const y=u.assetList.length;this.warn(`asset ${n+1}/${y} player destroyed ${u}`),f=this.createAssetPlayer(u,x,n),f.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(x))return;this.startAssetPlayer(f,n,r,t,c),this.shouldPlay&&wZe(f.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&wZe(this.hls.media)):i&&this.isInterstitial(a)&&(this.endedItem=null,this.playingItem=a,a.event.appendInPlace||this.attachPrimary(l.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var t;return(t=this.mediaSelection)==null?void 0:t.main.details}get primaryLive(){var t;return!!((t=this.primaryDetails)!=null&&t.live)}resumePrimary(t,r,n){var a,i;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${e1(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,r),this.log(Z6("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,t)}if(!n)return;const l=(i=this.schedule)==null?void 0:i.items;l&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${e1(t)}`),this.hls.trigger(_t.INTERSTITIALS_PRIMARY_RESUMED,{schedule:l.slice(0),scheduleIndex:r}),this.checkBuffer())}getPrimaryResumption(t,r){const n=t.start;if(this.primaryLive){const a=this.primaryDetails;if(r===0)return this.hls.startPosition;if(a&&(na.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(t){const r=this.getAssetPlayer(t.identifier);return r!=null&&r.hls?r.hls.bufferedToEnd:po.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,r,n){r?this.setBufferingItem(r):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const a=this.primaryMedia;if(!a)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,a),n&&this.startLoadingPrimaryAt(t,n)),n||(this.log(Z6("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,n))}startLoadingPrimaryAt(t,r){var n;const a=this.hls;!a.loadingEnabled||!a.media||Math.abs((((n=a.mainForwardBufferInfo)==null?void 0:n.start)||a.media.currentTime)-t)>.5?a.startLoad(t,r):a.bufferingEnabled||a.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),(t=this.schedule)==null||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(_t.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(_t.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,r){if(r.level===-1||!this.schedule)return;const n=this.hls.levels[r.level];if(!n.details)return;const a=uc(uc({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=a,this.schedule.parseInterstitialDateRanges(a,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,r){const n=this.hls.audioTracks[r.id],a=this.mediaSelection;if(!a){this.altSelection=uc(uc({},this.altSelection),{},{audio:n});return}const i=uc(uc({},a),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(t,r){const n=this.hls.subtitleTracks[r.id],a=this.mediaSelection;if(!a){this.altSelection=uc(uc({},this.altSelection),{},{subtitles:n});return}const i=uc(uc({},a),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(t,r){const n=MYe(r);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(r)||a.setAudioOption(n)))}onSubtitleTrackSwitch(t,r){const n=MYe(r);this.playerQueue.forEach(({hls:a})=>a&&(a.setSubtitleOption(r)||r.id!==-1&&a.setSubtitleOption(n)))}onBufferCodecs(t,r){const n=r.tracks;n&&(this.requiredTracks=n)}onBufferAppended(t,r){this.checkBuffer()}onBufferFlushed(t,r){const n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){const a=this.timelinePos;this.bufferedPos=a,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const r=this.schedule.events;if(this.bufferedPos.25){t.event.assetList.forEach((i,l)=>{t.event.isAssetPastPlayoutLimit(l)&&this.clearAssetPlayer(i.identifier,null)});const n=t.end+.25,a=po.bufferInfo(this.primaryMedia,n,0);(a.end>n||(a.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${e1(t)} (was ${e1(r)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(t,r){return!!r&&(t===r||t.event&&r.event&&this.eventItemsMatch(t,r)||!t.event&&!r.event&&this.findItemIndex(t)===this.findItemIndex(r))}eventItemsMatch(t,r){var n;return!!r&&(t===r||t.event.identifier===((n=r.event)==null?void 0:n.identifier))}findItemIndex(t,r){return t&&this.schedule?this.schedule.findItemIndex(t,r):-1}updateSchedule(t=!1){var r;const n=this.mediaSelection;n&&((r=this.schedule)==null||r.updateSchedule(n,[],t))}checkBuffer(t){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n)return;const a=po.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,n,t)}updateBufferedPos(t,r,n){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(r.length===1&&this.itemsMatch(r[0],i)){this.bufferedPos=t;return}const l=this.playingItem,o=this.findItemIndex(l);let c=a.findItemIndexAtTime(t);if(this.bufferedPos=i.end||(d=f.event)!=null&&d.appendInPlace&&t+.01>=f.start)&&(c=m),this.isInterstitial(i)){const x=i.event;if(m-o>1&&x.appendInPlace===!1||x.assetList.length===0&&x.assetListLoader)return}if(this.bufferedPos=t,c>u&&c>o)this.bufferedToItem(f);else{const x=this.primaryDetails;this.primaryLive&&x&&t>x.edge-x.targetduration&&f.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(r))})}setBufferingItem(t){const r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(t,r)&&n){const{items:a,events:i}=n;if(!a||!i)return r;const l=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const c=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${e1(t)}`+(r?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(l){const d=n.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((u,m)=>{const f=this.getAssetPlayer(u.identifier);f&&(m===d&&f.loadSource(),f.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(_t.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:a.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return r}bufferedToItem(t,r=0){const n=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,r);else if(n!==null){this.bufferingAsset=null;const a=this.detachedData;a?a.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t):this.preloadPrimary(t)}}}preloadPrimary(t){const r=this.findItemIndex(t),n=this.getPrimaryResumption(t,r);this.startLoadingPrimaryAt(n)}bufferedToEvent(t,r){const n=t.event,a=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(a||!i){const l=this.preloadAssets(n,r);if(l!=null&&l.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(l,o)}}}preloadAssets(t,r){const n=t.assetUrl,a=t.assetList.length,i=a===0&&!t.assetListLoader,l=t.cue.once;if(i){const c=t.timelineStart;if(t.appendInPlace){var o;const f=this.playingItem;!this.isInterstitial(f)&&(f==null||(o=f.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 f=u-c;f>0&&(d=Math.round(f*1e3)/1e3)}if(this.log(`Load interstitial asset ${r+1}/${n?1:a} ${t}${d?` live-start: ${u} start-offset: ${d}`:""}`),n)return this.createAsset(t,0,0,c,t.duration,n);const m=this.assetListLoader.loadAssetList(t,d);m&&(t.assetListLoader=m)}else if(!l&&a){for(let d=r;d{this.hls.trigger(_t.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const r=this.playerQueue;for(let n=0;n1){const E=r.duration;E&&A{if(A.live){var E;const F=new Error(`Interstitials MUST be VOD assets ${t}`),O={fatal:!0,type:di.OTHER_ERROR,details:kr.INTERSTITIAL_ASSET_ITEM_ERROR,error:F},B=((E=this.schedule)==null?void 0:E.findEventIndex(t.identifier))||-1;this.handleAssetItemError(O,t,B,n,F.message);return}const D=A.edge-A.fragmentStart,R=r.duration;(_||R===null||D>R)&&(_=!1,this.log(`Interstitial asset "${m}" duration change ${R} > ${D}`),r.duration=D,this.updateSchedule())};y.on(_t.LEVEL_UPDATED,(A,{details:E})=>b(E)),y.on(_t.LEVEL_PTS_UPDATED,(A,{details:E})=>b(E)),y.on(_t.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const j=(A,E)=>{const D=this.getAssetPlayer(m);if(D&&E.tracks){D.off(_t.BUFFER_CODECS,j),D.tracks=E.tracks;const R=this.primaryMedia;this.bufferingAsset===D.assetItem&&R&&!D.media&&this.bufferAssetPlayer(D,R)}};y.on(_t.BUFFER_CODECS,j);const N=()=>{var A;const E=this.getAssetPlayer(m);if(this.log(`buffered to end of asset ${E}`),!E||!this.schedule)return;const D=this.schedule.findEventIndex(t.identifier),R=(A=this.schedule.items)==null?void 0:A[D];this.isInterstitial(R)&&this.advanceAssetBuffering(R,r)};y.on(_t.BUFFERED_TO_END,N);const C=A=>()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,D,A)};return y.once(_t.MEDIA_ENDED,C(n)),y.once(_t.PLAYOUT_LIMIT_REACHED,C(1/0)),y.on(_t.ERROR,(A,E)=>{if(!this.schedule)return;const D=this.getAssetPlayer(m);if(E.details===kr.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(E,t,this.schedule.findEventIndex(t.identifier),n,`Asset player error ${E.error} ${t}`)}),y.on(_t.DESTROYING,()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;const E=new Error(`Asset player destroyed unexpectedly ${m}`),D={fatal:!0,type:di.OTHER_ERROR,details:kr.INTERSTITIAL_ASSET_ITEM_ERROR,error:E};this.handleAssetItemError(D,t,this.schedule.findEventIndex(t.identifier),n,E.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${aI(r)}`),this.hls.trigger(_t.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:r,assetListIndex:n,event:t,player:y}),y}clearInterstitial(t,r){this.clearAssetPlayers(t,r),t.reset()}clearAssetPlayers(t,r){t.assetList.forEach(n=>{this.clearAssetPlayer(n.identifier,r)})}resetAssetPlayer(t){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){this.log(`reset asset player "${t}" after error`);const n=this.playerQueue[r];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(t,r){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){const a=this.playerQueue[n];this.log(`clear ${a} toSegment: ${r&&e1(r)}`),this.transferMediaFromPlayer(a,r),this.playerQueue.splice(n,1),a.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,r,n,a,i){const{interstitial:l,assetItem:o,assetId:c}=t,d=l.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,n[a]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${r+1}/${d} ${aI(o)}`),this.hls.trigger(_t.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:r,event:l,schedule:n.slice(0),scheduleIndex:a,player:t})),this.bufferAssetPlayer(t,i)}bufferAssetPlayer(t,r){var n,a;if(!this.schedule)return;const{interstitial:i,assetItem:l}=t,o=this.schedule.findEventIndex(i.identifier),c=(n=this.schedule.items)==null?void 0:n[o];if(!c)return;t.loadSource(),this.setBufferingItem(c),this.bufferingAsset=l;const d=this.getBufferingPlayer();if(d===t)return;const u=i.appendInPlace;if(u&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const m=(d==null?void 0:d.tracks)||((a=this.detachedData)==null?void 0:a.tracks)||this.requiredTracks;if(u&&l!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(m&&!Wbt(m,t.tracks)){const f=new Error(`Asset ${aI(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(m)}')`),x={fatal:!0,type:di.OTHER_ERROR,details:kr.INTERSTITIAL_ASSET_ITEM_ERROR,error:f},y=i.findAssetIndex(l);this.handleAssetItemError(x,i,o,y,f.message);return}}this.transferMediaTo(t,r)}handleInPlaceStall(t){const r=this.schedule,n=this.primaryMedia;if(!r||!n)return;const a=n.currentTime,i=r.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/n.playbackRate<.5||o.bufferedInPlaceToEnd(n))&&o.hls){const u=r.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,u,i)}}}}advanceInPlace(t){const r=this.primaryMedia;r&&r.currentTime!_.error))r.error=y;else for(let _=a;_{const j=parseFloat(_.DURATION);this.createAsset(i,b,u,c+u,j,_.URI),u+=j}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${i}`);const m=this.waitingItem,f=(m==null?void 0:m.event.identifier)===l;this.updateSchedule();const x=(a=this.bufferingItem)==null?void 0:a.event;if(f){var y;const _=this.schedule.findEventIndex(l),b=(y=this.schedule.items)==null?void 0:y[_];if(b){if(!this.playingItem&&this.timelinePos>b.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(b)}this.setSchedulePosition(_)}else if((x==null?void 0:x.identifier)===l){const _=i.assetList[0];if(_){const b=this.getAssetPlayer(_.identifier);if(x.appendInPlace){const j=this.primaryMedia;b&&j&&this.bufferAssetPlayer(b,j)}else b&&b.loadSource()}}}onError(t,r){if(this.schedule)switch(r.details){case kr.ASSET_LIST_PARSING_ERROR:case kr.ASSET_LIST_LOAD_ERROR:case kr.ASSET_LIST_LOAD_TIMEOUT:{const n=r.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case kr.BUFFER_STALLED_ERROR:{const n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace){this.handleInPlaceStall(n.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const jZe=500;class Rer extends LIe{constructor(t,r,n){super(t,r,n,"subtitle-stream-controller",$a.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(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(_t.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(_t.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(_t.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(_t.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(_t.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(_t.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,r){this.stopLoad(),this.state=rn.IDLE,this.setInterval(jZe),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,r){this.tracksBuffered=[],super.onMediaDetaching(t,r)}onLevelLoaded(t,r){this.mainDetails=r.details}onSubtitleFragProcessed(t,r){const{frag:n,success:a}=r;if(this.fragContextChanged(n)||(oh(n)&&(this.fragPrevious=n),this.state=rn.IDLE),!a)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let l;const o=n.start;for(let d=0;d=i[d].start&&o<=i[d].end){l=i[d];break}const c=n.start+n.duration;l?l.end=c:(l={start:o,end:c},i.push(l)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}onBufferFlushing(t,r){const{startOffset:n,endOffset:a}=r;if(n===0&&a!==Number.POSITIVE_INFINITY){const i=a-1;if(i<=0)return;r.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(l=>{for(let o=0;onew Bz(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const a=new Bz(n);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,$a.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,r){var n;if(this.currentTrackId=r.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}const a=this.levels[this.currentTrackId];a!=null&&a.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,a&&this.state!==rn.STOPPED&&this.setInterval(jZe)}onSubtitleTrackLoaded(t,r){var n;const{currentTrackId:a,levels:i}=this,{details:l,id:o}=r;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=i[o];if(o>=i.length||!c)return;this.log(`Subtitle track ${o} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""},duration:${l.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(l.live||(n=c.details)!=null&&n.live){if(l.deltaUpdateFailed)return;const m=this.mainDetails;if(!m){this.startFragRequested=!1;return}const f=m.fragments[0];if(!c.details)l.hasProgramDateTime&&m.hasProgramDateTime?(exe(l,m),d=l.fragmentStart):f&&(d=f.start,XCe(l,d));else{var u;d=this.alignPlaylists(l,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&f&&(d=f.start,XCe(l,d))}m&&!this.startFragRequested&&this.setStartPosition(m,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(_t.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:r.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===rn.IDLE&&(VA(null,l.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:r,payload:n}=t,a=r.decryptdata,i=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&OP(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,IIe(a.method)).catch(o=>{throw i.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:r}),o}).then(o=>{const c=performance.now();i.trigger(_t.FRAG_DECRYPTED,{frag:r,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=rn.IDLE})}}doTick(){if(!this.media){this.state=rn.IDLE;return}if(this.state===rn.IDLE){const{currentTrackId:t,levels:r}=this,n=r==null?void 0:r[t];if(!n||!r.length||!n.details||this.waitForLive(n))return;const{config:a}=this,i=this.getLoadPosition(),l=po.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=n.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(c>u)return;const m=d.fragments,f=m.length,x=d.edge;let y=null;const _=this.fragPrevious;if(ox-N?0:N;y=VA(_,m,Math.max(m[0].start,o),C),!y&&_&&_.start{if(a=a>>>0,a>i-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${a}) is greater than the maximum bound (${i})`);return t[a][n]};this.buffered={get length(){return t.length},end(n){return r("end",n,t.length)},start(n){return r("start",n,t.length)}}}}const Fer={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},hwt=s=>String.fromCharCode(Fer[s]||s),n1=15,jj=100,zer={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ber={17:2,18:4,21:6,22:8,23:10,19:13,20:15},$er={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Uer={25:2,26:4,29:6,30:8,31:10,27:13,28:15},qer=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ver{constructor(){this.time=null,this.verboseLevel=0}log(t,r){if(this.verboseLevel>=t){const n=typeof r=="function"?r():r;fc.log(`${this.time} [${t}] ${n}`)}}}const wC=function(t){const r=[];for(let n=0;njj&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=jj)}moveCursor(t){const r=this.pos+t;if(t>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=hwt(t);if(this.pos>=jj){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+r+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1)}clearFromPos(t){let r;for(r=t;r"pacData = "+Hc(t));let r=t.row-1;if(this.nrRollUpRows&&r"bkgData = "+Hc(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const r=[];let n="",a=-1;for(let i=0;i0&&(t?n="["+r.join(" | ")+"]":n=r.join(` `)),n}getTextAndFormat(){return this.rows}}class NZe{constructor(t,r,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new qje(n),this.nonDisplayedMemory=new qje(n),this.lastOutputScreen=new qje(n),this.currRollUpRow=this.displayedMemory.rows[n1-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[n1-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let n=0;nr+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const r={flash:!1};if(r.underline=t%2===1,r.italics=t>=46,r.italics)r.foreground="white";else{const n=Math.floor(t/2)-16,a=["white","green","blue","cyan","red","yellow","magenta"];r.foreground=a[n]}this.logger.log(2,"MIDROW: "+Hc(r)),this.writeScreen.setPen(r)}outputDataUpdate(t=!1){const r=this.logger.time;r!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=r:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class kZe{constructor(t,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Ker(),this.logger=void 0;const a=this.logger=new Ver;this.channels=[null,new NZe(t,r,a),new NZe(t+1,n,a)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,r){this.channels[t].setHandler(r)}addData(t,r){this.logger.time=t;for(let n=0;n"["+wC([r[n],r[n+1]])+"] -> ("+wC([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(Wer(a,i,c)){KV(null,null,c),this.logger.log(3,()=>"Repeated command ("+wC([a,i])+") is dropped");continue}KV(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 KV(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 "+wC([a,i])+" orig: "+wC([r[n],r[n+1]]))}}parseCmd(t,r){const n=(t===20||t===28||t===21||t===29)&&r>=32&&r<=47,a=(t===23||t===31)&&r>=33&&r<=35;if(!(n||a))return!1;const i=t===20||t===21||t===23?1:2,l=this.channels[i];return t===20||t===21||t===28||t===29?r===32?l.ccRCL():r===33?l.ccBS():r===34?l.ccAOF():r===35?l.ccAON():r===36?l.ccDER():r===37?l.ccRU(2):r===38?l.ccRU(3):r===39?l.ccRU(4):r===40?l.ccFON():r===41?l.ccRDC():r===42?l.ccTR():r===43?l.ccRTD():r===44?l.ccEDM():r===45?l.ccCR():r===46?l.ccENM():r===47&&l.ccEOC():l.ccTO(r-32),this.currentChannel=i,!0}parseMidrow(t,r){let n=0;if((t===17||t===25)&&r>=32&&r<=47){if(t===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const a=this.channels[n];return a?(a.ccMIDROW(r),this.logger.log(3,()=>"MIDROW ("+wC([t,r])+")"),!0):!1}return!1}parsePAC(t,r){let n;const a=(t>=17&&t<=23||t>=25&&t<=31)&&r>=64&&r<=127,i=(t===16||t===24)&&r>=64&&r<=95;if(!(a||i))return!1;const l=t<=23?1:2;r>=64&&r<=95?n=l===1?zer[t]:$er[t]:n=l===1?Ber[t]:Uer[t];const o=this.channels[l];return o?(o.setPAC(this.interpretPAC(n,r)),this.currentChannel=l,!0):!1}interpretPAC(t,r){let n;const a={color:null,italics:!1,indent:null,underline:!1,row:t};return r>95?n=r-96:n=r-64,a.underline=(n&1)===1,n<=13?a.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(a.italics=!0,a.color="white"):a.indent=Math.floor((n-16)/2)*4,a}parseChars(t,r){let n,a=null,i=null;if(t>=25?(n=2,i=t-8):(n=1,i=t),i>=17&&i<=19){let l;i===17?l=r+80:i===18?l=r+112:l=r+144,this.logger.log(2,()=>"Special char '"+hwt(l)+"' in channel "+n),a=[l]}else t>=32&&t<=127&&(a=r===0?[t]:[t,r]);return a&&this.logger.log(3,()=>"Char codes = "+wC(a).join(",")),a}parseBackgroundAttributes(t,r){const n=(t===16||t===24)&&r>=32&&r<=47,a=(t===23||t===31)&&r>=45&&r<=47;if(!(n||a))return!1;let i;const l={};t===16||t===24?(i=Math.floor((r-32)/2),l.background=qer[i],r%2===1&&(l.background=l.background+"_semi")):r===45?l.background="transparent":(l.foreground="black",r===47&&(l.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(l),!0}reset(){for(let t=0;t100)throw new Error("Position must be between 0 and 100.");D=B,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},m,{get:function(){return R},set:function(B){const K=a(B);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");R=K,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},m,{get:function(){return F},set:function(B){if(B<0||B>100)throw new Error("Size must be between 0 and 100.");F=B,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},m,{get:function(){return O},set:function(B){const K=a(B);if(!K)throw new SyntaxError("An invalid or illegal string was specified.");O=K,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class Yer{decode(t,r){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function fwt(s){function t(n,a,i,l){return(n|0)*3600+(a|0)*60+(i|0)+parseFloat(l||0)}const r=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}class Zer{constructor(){this.values=Object.create(null)}set(t,r){!this.get(t)&&r!==""&&(this.values[t]=r)}get(t,r,n){return n?this.has(t)?this.values[t]:r[n]:this.has(t)?this.values[t]:r}has(t){return t in this.values}alt(t,r,n){for(let a=0;a=0&&n<=100)return this.set(t,n),!0}return!1}}function pwt(s,t,r,n){const a=n?s.split(n):[s];for(const i in a){if(typeof a[i]!="string")continue;const l=a[i].split(r);if(l.length!==2)continue;const o=l[0],c=l[1];t(o,c)}}const a3e=new GIe(0,0,""),YV=a3e.align==="middle"?"middle":"center";function Xer(s,t,r){const n=s;function a(){const o=fwt(s);if(o===null)throw new Error("Malformed timestamp: "+n);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function i(o,c){const d=new Zer;pwt(o,function(f,x){let y;switch(f){case"region":for(let _=r.length-1;_>=0;_--)if(r[_].id===x){d.set(f,r[_].region);break}break;case"vertical":d.alt(f,x,["rl","lr"]);break;case"line":y=x.split(","),d.integer(f,y[0]),d.percent(f,y[0])&&d.set("snapToLines",!1),d.alt(f,y[0],["auto"]),y.length===2&&d.alt("lineAlign",y[1],["start",YV,"end"]);break;case"position":y=x.split(","),d.percent(f,y[0]),y.length===2&&d.alt("positionAlign",y[1],["start",YV,"end","line-left","line-right","auto"]);break;case"size":d.percent(f,x);break;case"align":d.alt(f,x,["start",YV,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&a3e.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",YV);let m=d.get("position","auto");m==="auto"&&a3e.position===50&&(m=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=m}function l(){s=s.replace(/^\s+/,"")}if(l(),t.startTime=a(),l(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);s=s.slice(3),l(),t.endTime=a(),l(),i(s,t)}function xwt(s){return s.replace(//gi,` `)}class Qer{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Yer,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const r=this;t&&(r.buffer+=r.decoder.decode(t,{stream:!0}));function n(){let i=r.buffer,l=0;for(i=xwt(i);l")===-1){r.cue.id=i;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{Xer(i,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const o=i.indexOf("-->")!==-1;if(!i||o&&(l=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(r.cue===null)continue;r.cue.text&&(r.cue.text+=` `),r.cue.text+=i}continue;case"BADCUE":i||(r.state="ID")}}}catch{r.state==="CUETEXT"&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state=r.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=` `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(r){t.onparsingerror&&t.onparsingerror(r)}return t.onflush&&t.onflush(),this}}const Jer=/\r\n|\n\r|\n|\r/g,Vje=function(t,r,n=0){return t.slice(n,n+r.length)===r},etr=function(t){let r=parseInt(t.slice(-3));const n=parseInt(t.slice(-6,-4)),a=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!Sa(r)||!Sa(n)||!Sa(a)||!Sa(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return r+=1e3*n,r+=60*1e3*a,r+=60*60*1e3*i,r};function WIe(s,t,r){return Q7(s.toString())+Q7(t.toString())+Q7(r)}const ttr=function(t,r,n){let a=t[r],i=t[a.prevCC];if(!i||!i.new&&a.new){t.ccOffset=t.presentationOffset=a.start,a.new=!1;return}for(;(l=i)!=null&&l.new;){var l;t.ccOffset+=a.start-i.start,a.new=!1,a=i,i=t[a.prevCC]}t.presentationOffset=n};function str(s,t,r,n,a,i,l){const o=new Qer,c=O0(new Uint8Array(s)).trim().replace(Jer,` `).split(` `),d=[],u=t?lJs(t.baseTime,t.timescale):0;let m="00:00.000",f=0,x=0,y,_=!0;o.oncue=function(b){const j=r[n];let N=r.ccOffset;const C=(f-u)/9e4;if(j!=null&&j.new&&(x!==void 0?N=r.ccOffset=j.start:ttr(r,n,C)),C){if(!t){y=new Error("Missing initPTS for VTT MPEGTS");return}N=C-r.presentationOffset}const A=b.endTime-b.startTime,E=d0((b.startTime+N-x)*9e4,a*9e4)/9e4;b.startTime=Math.max(E,0),b.endTime=Math.max(E+A,0);const D=b.text.trim();b.text=decodeURIComponent(encodeURIComponent(D)),b.id||(b.id=WIe(b.startTime,b.endTime,D)),b.endTime>0&&d.push(b)},o.onparsingerror=function(b){y=b},o.onflush=function(){if(y){l(y);return}i(d)},c.forEach(b=>{if(_)if(Vje(b,"X-TIMESTAMP-MAP=")){_=!1,b.slice(16).split(",").forEach(j=>{Vje(j,"LOCAL:")?m=j.slice(6):Vje(j,"MPEGTS:")&&(f=parseInt(j.slice(7)))});try{x=etr(m)/1e3}catch(j){y=j}return}else b===""&&(_=!1);o.parse(b+` `)}),o.flush()}const Hje="stpp.ttml.im1t",gwt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ywt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,rtr={left:"start",center:"center",right:"end",start:"start",end:"end"};function SZe(s,t,r,n){const a=Fo(new Uint8Array(s),["mdat"]);if(a.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>O0(o)),l=oJs(t.baseTime,1,t.timescale);try{i.forEach(o=>r(ntr(o,l)))}catch(o){n(o)}}function ntr(s,t){const a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!a)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},l=Object.keys(i).reduce((m,f)=>(m[f]=a.getAttribute(`ttp:${f}`)||i[f],m),{}),o=a.getAttribute("xml:space")!=="preserve",c=CZe(Gje(a,"styling","style")),d=CZe(Gje(a,"layout","region")),u=Gje(a,"body","[begin]");return[].map.call(u,m=>{const f=vwt(m,o);if(!f||!m.hasAttribute("begin"))return null;const x=Kje(m.getAttribute("begin"),l),y=Kje(m.getAttribute("dur"),l);let _=Kje(m.getAttribute("end"),l);if(x===null)throw TZe(m);if(_===null){if(y===null)throw TZe(m);_=x+y}const b=new GIe(x-t,_-t,f);b.id=WIe(b.startTime,b.endTime,b.text);const j=d[m.getAttribute("region")],N=c[m.getAttribute("style")],C=atr(j,N,c),{textAlign:A}=C;if(A){const E=rtr[A];E&&(b.lineAlign=E),b.align=A}return Ac(b,C),b}).filter(m=>m!==null)}function Gje(s,t,r){const n=s.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function CZe(s){return s.reduce((t,r)=>{const n=r.getAttribute("xml:id");return n&&(t[n]=r),t},{})}function vwt(s,t){return[].slice.call(s.childNodes).reduce((r,n,a)=>{var i;return n.nodeName==="br"&&a?r+` `:(i=n.childNodes)!=null&&i.length?vwt(n,t):t?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function atr(s,t,r){const n="http://www.w3.org/ns/ttml#styling";let a=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],l=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return l&&r.hasOwnProperty(l)&&(a=r[l]),i.reduce((o,c)=>{const d=Wje(t,n,c)||Wje(s,n,c)||Wje(a,n,c);return d&&(o[c]=d),o},{})}function Wje(s,t,r){return s&&s.hasAttributeNS(t,r)?s.getAttributeNS(t,r):null}function TZe(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Kje(s,t){if(!s)return null;let r=fwt(s);return r===null&&(gwt.test(s)?r=itr(s,t):ywt.test(s)&&(r=otr(s,t))),r}function itr(s,t){const r=gwt.exec(s),n=(r[4]|0)+(r[5]|0)/t.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/t.frameRate}function otr(s,t){const r=ywt.exec(s),n=Number(r[1]);switch(r[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}class ZV{constructor(t,r){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,r,n){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class ltr{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=AZe(),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(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_t.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(_t.FRAG_LOADING,this.onFragLoading,this),t.on(_t.FRAG_LOADED,this.onFragLoaded,this),t.on(_t.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(_t.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(_t.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(_t.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_t.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(_t.FRAG_LOADING,this.onFragLoading,this),t.off(_t.FRAG_LOADED,this.onFragLoaded,this),t.off(_t.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(_t.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(_t.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(_t.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new ZV(this,"textTrack1"),r=new ZV(this,"textTrack2"),n=new ZV(this,"textTrack3"),a=new ZV(this,"textTrack4");this.cea608Parser1=new kZe(1,t,r),this.cea608Parser2=new kZe(3,n,a)}addCues(t,r,n,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=ctr(c[0],c[1],r,n);if(d>=0&&(c[0]=Math.min(c[0],r),c[1]=Math.max(c[1],n),l=!0,d/(n-r)>.5))return}if(l||i.push([r,n]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,r,n,a)}else{const o=this.Cues.newCue(null,r,n,a);this.hls.trigger(_t.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:r,id:n,initPTS:a,timescale:i,trackId:l}){const{unparsedVttFrags:o}=this;n===$a.MAIN&&(this.initPTS[r.cc]={baseTime:a,timescale:i,trackId:l}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(_t.FRAG_LOADED,c):this.hls.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,r){const{media:n}=this;if(n)for(let a=0;a{DI(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=AZe(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const r=t.textTracks;if(r)for(let n=0;ni.textCodec===Hje);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(Z_t(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const l=this.media,o=l?vhe(l.textTracks):null;if(this.tracks.forEach((c,d)=>{let u;if(o){let m=null;for(let f=0;fd!==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(_t.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}onManifestLoaded(t,r){this.config.enableCEA708Captions&&r.captions&&r.captions.forEach(n=>{const a=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!a)return;const i=`textTrack${a[1]}`,l=this.captionsProperties[i];l&&(l.label=n.name,n.lang&&(l.languageCode=n.lang),l.media=n)})}closedCaptionsForLevel(t){const r=this.hls.levels[t.level];return r==null?void 0:r.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,r){if(this.enabled&&r.frag.type===$a.MAIN){var n,a;const{cea608Parser1:i,cea608Parser2:l,lastSn:o}=this,{cc:c,sn:d}=r.frag,u=(n=(a=r.part)==null?void 0:a.index)!=null?n:-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,r){const{frag:n,payload:a}=r;if(n.type===$a.SUBTITLE)if(a.byteLength){const i=n.decryptdata,l="stats"in r;if(i==null||!i.encrypted||l){const o=this.tracks[n.level],c=this.vttCCs;c[n.cc]||(c[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),o&&o.textCodec===Hje?this._parseIMSC1(n,a):this._parseVTTs(r)}}else this.hls.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,r){const n=this.hls;SZe(r,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{n.logger.log(`Failed to parse IMSC1: ${a}`),n.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:a})})}_parseVTTs(t){var r;const{frag:n,payload:a}=t,{initPTS:i,unparsedVttFrags:l}=this,o=i.length-1;if(!i[n.cc]&&o===-1){l.push(t);return}const c=this.hls,d=(r=n.initSegment)!=null&&r.data?dv(n.initSegment.data,new Uint8Array(a)).buffer:a;str(d,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,u=>{this._appendCues(u,n.level),c.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},u=>{const m=u.message==="Missing initPTS for VTT MPEGTS";m?l.push(t):this._fallbackToIMSC1(n,a),c.logger.log(`Failed to parse VTT cue: ${u}`),!(m&&o>n.cc)&&c.trigger(_t.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:u})})}_fallbackToIMSC1(t,r){const n=this.tracks[t.level];n.textCodec||SZe(r,this.initPTS[t.cc],()=>{n.textCodec=Hje,this._parseIMSC1(t,r)},()=>{n.textCodec="wvtt"})}_appendCues(t,r){const n=this.hls;if(this.config.renderTextTracksNatively){const a=this.textTracks[r];if(!a||a.mode==="disabled")return;t.forEach(i=>dwt(a,i))}else{const a=this.tracks[r];if(!a)return;const i=a.default?"default":"subtitles"+r;n.trigger(_t.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,r){const{frag:n}=r;n.type===$a.SUBTITLE&&this.onFragLoaded(_t.FRAG_LOADED,r)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,r){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:n,samples:a}=r;if(!(n.type===$a.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let i=0;in3e(o[c],r,n))}if(this.config.renderTextTracksNatively&&r===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>n3e(o[c],r,a))}}}extractCea608Data(t){const r=[[],[]],n=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const x=xwt(d.trim()),y=WIe(t,r,x);s!=null&&(m=s.cues)!=null&&m.getCueById(y)||(l=new u(t,r,x),l.id=y,l.line=f+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((f,x)=>f.line==="auto"||x.line==="auto"?0:f.line>8&&x.line>8?x.line-f.line:f.line-x.line),a.forEach(f=>dwt(s,f))),a}};function htr(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const mtr=/(\d+)-(\d+)\/(\d+)/;class MZe{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||gtr,this.controller=new self.AbortController,this.stats=new kIe}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,r,n){const a=this.stats;if(a.loading.start)throw new Error("Loader can only be used once.");a.loading.start=self.performance.now();const i=ftr(t,this.controller.signal),l=t.responseType==="arraybuffer",o=l?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=r.loadPolicy;this.context=t,this.config=r,this.callbacks=n,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),r.timeout=c&&Sa(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},r.timeout),(qz(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(m=>{var f;this.response=this.loader=m;const x=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),r.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},d-(x-a.loading.start)),!m.ok){const{status:_,statusText:b}=m;throw new ytr(b||"fetch, bad network response",_,m)}a.loading.first=x,a.total=xtr(m.headers)||a.total;const y=(f=this.callbacks)==null?void 0:f.onProgress;return y&&Sa(r.highWaterMark)?this.loadProgressively(m,a,t,r.highWaterMark,y):l?m.arrayBuffer():t.responseType==="json"?m.json():m.text()}).then(m=>{var f,x;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 _=m[o];_&&(a.loaded=a.total=_);const b={url:y.url,data:m,code:y.status},j=(f=this.callbacks)==null?void 0:f.onProgress;j&&!Sa(r.highWaterMark)&&j(a,t,m,y),(x=this.callbacks)==null||x.onSuccess(b,a,t,y)}).catch(m=>{var f;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const x=m&&m.code||0,y=m?m.message:null;(f=this.callbacks)==null||f.onError({code:x,text:y},t,m?m.details:null,a)})}getCacheAge(){let t=null;if(this.response){const r=this.response.headers.get("age");t=r?parseFloat(r):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,r,n,a=0,i){const l=new A_t,o=t.body.getReader(),c=()=>o.read().then(d=>{if(d.done)return l.dataLength&&i(r,n,l.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const u=d.value,m=u.length;return r.loaded+=m,m=a&&i(r,n,l.flush().buffer,t)):i(r,n,u.buffer,t),c()}).catch(()=>Promise.reject());return c()}}function ftr(s,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Ac({},s.headers))};return s.rangeEnd&&r.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),r}function ptr(s){const t=mtr.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function xtr(s){const t=s.get("Content-Range");if(t){const n=ptr(t);if(Sa(n))return n}const r=s.get("Content-Length");if(r)return parseInt(r)}function gtr(s,t){return new self.Request(s.url,t)}class ytr extends Error{constructor(t,r,n){super(t),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const vtr=/^age:\s*[\d.]+\s*$/im;class _wt{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 kIe,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,r,n){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=r,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:t,context:r}=this;if(!t||!r)return;const n=this.loader=new self.XMLHttpRequest,a=this.stats;a.loading.first=0,a.loaded=0,a.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i(n,r.url)}).catch(l=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),i(n,r.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,r,t)}).catch(l=>{var o;(o=this.callbacks)==null||o.onError({code:n.status,text:l.message},r,n,a)}):this.openAndSendXhr(n,r,t)}openAndSendXhr(t,r,n){t.readyState||t.open("GET",r.url,!0);const a=r.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:l}=n.loadPolicy;if(a)for(const o in a)t.setRequestHeader(o,a[o]);r.rangeEnd&&t.setRequestHeader("Range","bytes="+r.rangeStart+"-"+(r.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=r.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&Sa(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),t.send()}readystatechange(){const{context:t,loader:r,stats:n}=this;if(!t||!r)return;const a=r.readyState,i=this.config;if(!n.aborted&&a>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const d=r.status,u=r.responseType==="text"?r.responseText:null;if(d>=200&&d<300){const y=u??r.response;if(y!=null){var l,o;n.loading.end=Math.max(self.performance.now(),n.loading.first);const _=r.responseType==="arraybuffer"?y.byteLength:y.length;n.loaded=n.total=_,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);const b=(l=this.callbacks)==null?void 0:l.onProgress;b&&b(n,t,y,r);const j={url:r.responseURL,data:y,code:d};(o=this.callbacks)==null||o.onSuccess(j,n,t,r);return}}const m=i.loadPolicy.errorRetry,f=n.retry,x={url:t.url,data:void 0,code:d};if(Xpe(m,f,!1,x))this.retry(m);else{var c;fc.error(`${d} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:d,text:r.statusText},t,r,n)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(Xpe(t,r,!0))this.retry(t);else{var n;fc.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);const a=this.callbacks;a&&(this.abortInternal(),a.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:r,stats:n}=this;this.retryDelay=EIe(t,n.retry),n.retry++,fc.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${r==null?void 0:r.url}, retrying ${n.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const r=this.stats;r.loaded=t.loaded,t.lengthComputable&&(r.total=t.total)}getCacheAge(){let t=null;if(this.loader&&vtr.test(this.loader.getAllResponseHeaders())){const r=this.loader.getResponseHeader("age");t=r?parseFloat(r):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const btr={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},_tr=uc(uc({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:_wt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:PXs,bufferController:jJs,capLevelController:qIe,errorController:FXs,fpsController:Ner,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:v_t,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:btr},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},wtr()),{},{subtitleStreamController:Rer,subtitleTrackController:Cer,timelineController:ltr,audioStreamController:vJs,audioTrackController:bJs,emeController:FP,cmcdController:ber,contentSteeringController:wer,interstitialsController:Der});function wtr(){return{cueHandler:utr,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 jtr(s,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=i3e(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 m=`${l}Loading${u}`,f=t[m];if(f!==void 0&&c){d.push(m);const x=n[o].default;switch(t[o]={default:x},u){case"TimeOut":x.maxLoadTimeMs=f,x.maxTimeToFirstByteMs=f;break;case"MaxRetry":x.errorRetry.maxNumRetry=f,x.timeoutRetry.maxNumRetry=f;break;case"RetryDelay":x.errorRetry.retryDelayMs=f,x.timeoutRetry.retryDelayMs=f;break;case"MaxRetryTimeout":x.errorRetry.maxRetryDelayMs=f,x.timeoutRetry.maxRetryDelayMs=f;break}}}),d.length&&r.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${Hc(t[o])}`)}),uc(uc({},n),t)}function i3e(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(i3e):Object.keys(s).reduce((t,r)=>(t[r]=i3e(s[r]),t),{}):s}function Ntr(s,t){const r=s.loader;r!==MZe&&r!==_wt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):htr()&&(s.loader=MZe,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const bhe=2,ktr=.1,Str=.05,Ctr=100;class Ttr extends f_t{constructor(t,r){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var n;(n=this.media)!=null&&n.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var n;this.ended=((n=this.media)==null?void 0:n.currentTime)||1,this.hls.trigger(_t.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=r,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,r){this.setInterval(Ctr),this.mediaSource=r.mediaSource;const n=this.media=r.media;Cx(n,"playing",this.onMediaPlaying),Cx(n,"waiting",this.onMediaWaiting),Cx(n,"ended",this.onMediaEnded)}onMediaDetaching(t,r){this.clearInterval();const{media:n}=this;n&&(ug(n,"playing",this.onMediaPlaying),ug(n,"waiting",this.onMediaWaiting),ug(n,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,r){this.buffered=r.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const r=this.media.currentTime;this.poll(r,this.lastCurrentTime),this.lastCurrentTime=r}poll(t,r){var n,a;const i=(n=this.hls)==null?void 0:n.config;if(!i)return;const l=this.media;if(!l)return;const{seeking:o}=l,c=this.seeking&&!o,d=!this.seeking&&o,u=l.paused&&!o||l.ended||l.playbackRate===0;if(this.seeking=o,t!==r){r&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&t>r&&this.nudgeOnVideoHole(t,r)),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(_t.MEDIA_ENDED,{stalled:!1}));return}if(!po.getBuffered(l).length){this.nudgeRetry=0;return}const m=po.bufferInfo(l,t,0),f=m.nextStart||0,x=this.fragmentTracker;if(o&&x&&this.hls){const D=IZe(this.hls.inFlightFragments,t),R=m.len>bhe,F=!f||D||f-t>bhe&&!x.getPartialFragment(t);if(R||F)return;this.moved=!1}const y=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&x){if(!(m.len>0)&&!f)return;const R=Math.max(f,m.start||0)-t,O=!!(y!=null&&y.live)?y.targetduration*2:bhe,B=XV(t,x);if(R>0&&(R<=O||B)){l.paused||this._trySkipBufferHole(B);return}}const _=i.detectStallWithCurrentTimeMs,b=self.performance.now(),j=this.waiting;let N=this.stalled;if(N===null)if(j>0&&b-j<_)N=this.stalled=j;else{this.stalled=b;return}const C=b-N;if(!o&&(C>=_||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(_t.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(m),!this.media||!this.hls)return}const E=po.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(E,C,t)}stallResolved(t){const r=this.stalled;if(r&&this.hls&&(this.stalled=null,this.stallReported)){const n=self.performance.now()-r;this.log(`playback not stuck anymore @${t}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(_t.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,r){var n;const a=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&a&&a.length>1&&t>a.end(0)){const i=po.bufferedInfo(po.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&r>=i.start){const l=po.timeRangesToArray(a),o=po.bufferedInfo(l,r,0).bufferedIndex;if(o>-1&&oo)&&u-d<1&&t-d<2){const m=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${d} -> ${u} buffered index: ${c}`);this.warn(m.message),this.media.currentTime+=1e-6;let f=XV(t,this.fragmentTracker);f&&"fragment"in f?f=f.fragment:f||(f=void 0);const x=po.bufferInfo(this.media,t,0);this.hls.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,frag:f,buffer:x.len,bufferInfo:x})}}}}}_tryFixBufferStall(t,r,n){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,u=XV(n,l);if((u||d!=null&&d.live&&n1&&t.len>c.maxBufferHole||t.nextStart&&(t.nextStart-nc.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,r){const n=this.fragmentTracker,a=t.nextStart;if(n&&a){const i=n.getFragAtPos(r,$a.MAIN),l=n.getFragAtPos(a,$a.MAIN);if(i&&l)return l.sn-i.sn<2}return!1}_reportStall(t){const{hls:r,media:n,stallReported:a,stalled:i}=this;if(!a&&i!==null&&n&&r){this.stallReported=!0;const l=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${Hc(t)})`);this.warn(l.message),r.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.BUFFER_STALLED_ERROR,fatal:!1,error:l,buffer:t.len,bufferInfo:t,stalled:{start:i}})}}_trySkipBufferHole(t){var r;const{fragmentTracker:n,media:a}=this,i=(r=this.hls)==null?void 0:r.config;if(!a||!n||!i)return 0;const l=a.currentTime,o=po.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,f=c-l;if(f>0&&(u||m)){if(f>i.maxBufferHole){let y=!1;if(l===0){const _=n.getAppendedFrag(0,$a.MAIN);_&&c<_.end&&(y=!0)}if(!y&&t){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||IZe(this.hls.inFlightFragments,c))return 0;let b=!1,j=t.end;for(;j"u"))return self.VTTCue||self.TextTrackCue}function Yje(s,t,r,n,a){let i=new s(t,r,"");try{i.value=n,a&&(i.type=a)}catch{i=new s(t,r,Hc(a?uc({type:a},n):n))}return i}const QV=(()=>{const s=o3e();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Atr{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(_t.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(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_t.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(_t.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(_t.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_t.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,r){var n;this.media=r.media,((n=r.overrides)==null?void 0:n.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var t;const r=(t=this.hls)==null?void 0:t.latestLevelDetails;r&&this.updateDateRangeCues(r)}onMediaDetaching(t,r){this.media=null,!r.transferMedia&&(this.id3Track&&(this.removeCues&&DI(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const r=this.getID3Track(t.textTracks);return r.mode="hidden",r}getID3Track(t){if(this.media){for(let r=0;rQV&&(m=QV),m-u<=0&&(m=u+Etr);for(let x=0;xu.type===y0.audioId3&&c:a==="video"?d=u=>u.type===y0.emsg&&o:d=u=>u.type===y0.audioId3&&c||u.type===y0.emsg&&o,n3e(i,r,n,d)}}onLevelUpdated(t,{details:r}){this.updateDateRangeCues(r,!0)}onLevelPtsUpdated(t,r){Math.abs(r.drift)>.01&&this.updateDateRangeCues(r.details)}updateDateRangeCues(t,r){if(!this.hls||!this.media)return;const{assetPlayerId:n,timelineOffset:a,enableDateRangeMetadataCues:i,interstitialsController:l}=this.hls.config;if(!i)return;const o=o3e();if(n&&a&&!l){const{fragmentStart:_,fragmentEnd:b}=t;let j=this.assetCue;j?(j.startTime=_,j.endTime=b):o&&(j=this.assetCue=Yje(o,_,b,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),j&&(j.id=n,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 m=this.dateRangeCuesAppended;if(c&&r){var f;if((f=c.cues)!=null&&f.length){const _=Object.keys(m).filter(b=>!u.includes(b));for(let b=_.length;b--;){var x;const j=_[b],N=(x=m[j])==null?void 0:x.cues;delete m[j],N&&Object.keys(N).forEach(C=>{const A=N[C];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(A)}catch{}}})}}else m=this.dateRangeCuesAppended={}}const y=t.fragments[t.fragments.length-1];if(!(u.length===0||!Sa(y==null?void 0:y.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(Z!==j.id){const Q=d[Z];if(Q.class===j.class&&Q.startDate>j.startDate&&(!K||j.startDate.01&&(Z.startTime=N,Z.endTime=D);else if(o){let Q=j.attr[K];QXs(K)&&(Q=Kbt(Q));const te=Yje(o,N,D,{key:K,data:Q},y0.dateRange);te&&(te.id=b,this.id3Track.addCue(te),A[K]=te,l&&(K==="X-ASSET-LIST"||K==="X-ASSET-URL")&&te.addEventListener("enter",this.onEventCueEnter))}}m[b]={cues:A,dateRange:j,durationKnown:E}}}}}class Mtr{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:r}=this,n=this.levelDetails;if(!r||!n)return;this.currentTime=r.currentTime;const a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:l}=this.config;if(!i||l===1||!n.live)return;const o=this.targetLatency;if(o===null)return;const c=a-o,d=Math.min(this.maxLatency,o+n.targetduration);if(c.05&&this.forwardBufferLength>1){const m=Math.min(2,Math.max(1,l)),f=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,x=Math.min(m,Math.max(1,f));this.changeMediaPlaybackRate(r,x)}else r.playbackRate!==1&&r.playbackRate!==0&&this.changeMediaPlaybackRate(r,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:r,partHoldBack:n,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&n||r;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const 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(),r=this.targetLatency;if(t===null||r===null)return null;const n=this.levelDetails;if(n===null)return null;const a=n.edge,i=t-r-this.edgeStalled,l=a-n.totalduration,o=a-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const r=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-r,0)}get forwardBufferLength(){const{media:t}=this,r=this.levelDetails;if(!t||!r)return 0;const n=t.buffered.length;return(n?t.buffered.end(n-1):r.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_t.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(_t.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_t.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_t.ERROR,this.onError,this))}onMediaAttached(t,r){this.media=r.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:r}){r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,r){var n;r.details===kr.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,r){var n,a;t.playbackRate!==r&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(a=this.targetLatency)==null?void 0:a.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${r}`),t.playbackRate=r)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}class Itr extends UIe{constructor(t,r){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=r,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_t.FRAG_BUFFERED,this.onFragBuffered,this),t.on(_t.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_t.FRAG_BUFFERED,this.onFragBuffered,this),t.off(_t.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(r=>{r.loadError=0,r.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,r){this.resetLevels()}onManifestLoaded(t,r){const n=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1;r.levels.forEach(u=>{const m=u.attrs;let{audioCodec:f,videoCodec:x}=u;f&&(u.audioCodec=f=Wpe(f,n)||void 0),x&&(x=u.videoCodec=fXs(x));const{width:y,height:_,unknownCodecs:b}=u,j=(b==null?void 0:b.length)||0;if(o||(o=!!(y&&_)),c||(c=!!x),d||(d=!!f),j||f&&!this.isAudioSupported(f)||x&&!this.isVideoSupported(x)){this.log(`Some or all CODECS not supported "${m.CODECS}"`);return}const{CODECS:N,"FRAME-RATE":C,"HDCP-LEVEL":A,"PATHWAY-ID":E,RESOLUTION:D,"VIDEO-RANGE":R}=m,O=`${`${E||"."}-`}${u.bitrate}-${D}-${C}-${N}-${R}-${A}`;if(i[O])if(i[O].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const B=l[O]+=1;u.attrs["PATHWAY-ID"]=new Array(B+1).join(".");const K=this.createLevel(u);i[O]=K,a.push(K)}else i[O].addGroupId("audio",m.AUDIO),i[O].addGroupId("text",m.SUBTITLES);else{const B=this.createLevel(u);i[O]=B,l[O]=1,a.push(B)}}),this.filterAndSortMediaOptions(a,r,o,c,d)}createLevel(t){const r=new Bz(t),n=t.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){const a=new Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(a.message),r.supportedResult=i_t(a,[])}return r}isAudioSupported(t){return Fz(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Fz(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,r,n,a,i){var l;let o=[],c=[],d=t;const u=((l=r.stats)==null?void 0:l.parsing)||{};if((n||a)&&i&&(d=d.filter(({videoCodec:N,videoRange:C,width:A,height:E})=>(!!N||!!(A&&E))&&NXs(C))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let N="no level with compatible codecs found in manifest",C=N;r.levels.length&&(C=`one or more CODECS in variant not supported: ${Hc(r.levels.map(E=>E.attrs.CODECS).filter((E,D,R)=>R.indexOf(E)===D))}`,this.warn(C),N+=` (${C})`);const A=new Error(N);this.hls.trigger(_t.ERROR,{type:di.MEDIA_ERROR,details:kr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:A,reason:C})}}),u.end=performance.now();return}r.audioTracks&&(o=r.audioTracks.filter(N=>!N.audioCodec||this.isAudioSupported(N.audioCodec)),LZe(o)),r.subtitles&&(c=r.subtitles,LZe(c));const m=d.slice(0);d.sort((N,C)=>{if(N.attrs["HDCP-LEVEL"]!==C.attrs["HDCP-LEVEL"])return(N.attrs["HDCP-LEVEL"]||"")>(C.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&N.height!==C.height)return N.height-C.height;if(N.frameRate!==C.frameRate)return N.frameRate-C.frameRate;if(N.videoRange!==C.videoRange)return Kpe.indexOf(N.videoRange)-Kpe.indexOf(C.videoRange);if(N.videoCodec!==C.videoCodec){const A=kYe(N.videoCodec),E=kYe(C.videoCodec);if(A!==E)return E-A}if(N.uri===C.uri&&N.codecSet!==C.codecSet){const A=Gpe(N.codecSet),E=Gpe(C.codecSet);if(A!==E)return E-A}return N.averageBitrate!==C.averageBitrate?N.averageBitrate-C.averageBitrate:0});let f=m[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==m.length)){for(let N=0;NA&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}const y=i&&!a,_=this.hls.config,b=!!(_.audioStreamController&&_.audioTrackController),j={levels:d,audioTracks:o,subtitleTracks:c,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:i,video:a,altAudio:b&&!y&&o.some(N=>!!N.url)};u.end=performance.now(),this.hls.trigger(_t.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 r=this._levels;if(r.length===0)return;if(t<0||t>=r.length){const u=new Error("invalid level idx"),m=t<0;if(this.hls.trigger(_t.ERROR,{type:di.OTHER_ERROR,details:kr.LEVEL_SWITCH_ERROR,level:t,fatal:m,error:u,reason:u.message}),m)return;t=Math.min(t,r.length-1)}const n=this.currentLevelIndex,a=this.currentLevel,i=a?a.attrs["PATHWAY-ID"]:void 0,l=r[t],o=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,n===t&&a&&i===o)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${o?" with Pathway "+o:""} from level ${n}${i?" with Pathway "+i:""}`);const c={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(_t.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 r=this.steering.pathways(),n=t.filter(a=>r.indexOf(a)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${r}`);return}this.steering.pathwayPriority=n}}onError(t,r){r.fatal||!r.context||r.context.type===Jo.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(t,{frag:r}){if(r!==void 0&&r.type===$a.MAIN){const n=r.elementaryStreams;if(!Object.keys(n).some(i=>!!n[i]))return;const a=this._levels[r.level];a!=null&&a.loadError&&(this.log(`Resetting level error count of ${a.loadError} on frag buffered`),a.loadError=0)}}onLevelLoaded(t,r){var n;const{level:a,details:i}=r,l=r.levelInfo;if(!l){var o;this.warn(`Invalid level index ${a}`),(o=r.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(l===this.currentLevel||r.withoutMultiVariant){l.fragmentError===0&&(l.loadError=0);let c=l.details;c===r.details&&c.advanced&&(c=void 0),this.playlistLoaded(a,r,c)}else(n=r.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,r){super.loadingPlaylist(t,r);const n=this.getUrlWithDirectives(t.uri,r),a=this.currentLevelIndex,i=t.attrs["PATHWAY-ID"],l=t.details,o=l==null?void 0:l.age;this.log(`Loading level index ${a}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${i?" Pathway "+i:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${n}`),this.hls.trigger(_t.LEVEL_LOADING,{url:n,level:a,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var r;if(this._levels.length===1)return;const n=this._levels.filter((i,l)=>l!==t?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(o=>o.level=-1)),!1));C_t(n),this._levels=n,this.currentLevelIndex>-1&&(r=this.currentLevel)!=null&&r.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const a=n.length-1;this._firstLevel=Math.min(this._firstLevel,a),this._startLevel&&(this._startLevel=Math.min(this._startLevel,a)),this.hls.trigger(_t.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(t,{levels:r}){this._levels=r}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:r,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(_t.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function LZe(s){const t={};s.forEach(r=>{const n=r.groupId||"";r.id=t[n]=t[n]||0,t[n]++})}function wwt(){return self.SourceBuffer||self.WebKitSourceBuffer}function jwt(){if(!US())return!1;const t=wwt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function Ptr(){if(!jwt())return!1;const s=US();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(zz(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(zz(t,"audio"))))}function Ltr(){var s;const t=wwt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const Dtr=100;class Rtr extends LIe{constructor(t,r,n){super(t,r,n,"stream-controller",$a.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||!Sa(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,$a.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(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_t.LEVEL_LOADING,this.onLevelLoading,this),t.on(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_t.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(_t.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(_t.BUFFER_CREATED,this.onBufferCreated,this),t.on(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_t.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(_t.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_t.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_t.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(_t.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(_t.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(_t.BUFFER_CREATED,this.onBufferCreated,this),t.off(_t.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_t.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,r){if(this.levels){const{lastCurrentTime:n,hls:a}=this;if(this.stopLoad(),this.setInterval(Dtr),this.level=-1,!this.startFragRequested){let i=a.startLevel;i===-1&&(a.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=a.firstAutoLevel),a.nextLoadLevel=i,this.level=a.loadLevel,this._hasEnoughToStart=!!r}n>0&&t===-1&&!r&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),t=n),this.state=rn.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=rn.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case rn.WAITING_LEVEL:{const{levels:t,level:r}=this,n=t==null?void 0:t[r],a=n==null?void 0:n.details;if(a&&(!a.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(a))break;this.state=rn.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=rn.IDLE;break}break}case rn.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===rn.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:r,levels:n,media:a}=this;if(r===null||!a&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(n!=null&&n[i]))return;const l=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const _={};this.altAudio===2&&(_.type="video"),this.hls.trigger(_t.BUFFER_EOS,_),this.state=rn.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===rn.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=rn.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,m=this.getMaxBufferLength(l.maxBitrate);if(u>=m)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:o.end;let x=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&x&&oh(x)&&this.fragmentTracker.getState(x)!==lm.OK){var y;const b=((y=this.backtrackFragment)!=null?y:x).sn-d.startSN,j=d.fragments[b-1];j&&x.cc===j.cc&&(x=j,this.fragmentTracker.removeFragment(j))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(x&&this.isLoopLoading(x,f)){if(!x.gap){const b=this.audioOnly&&!this.altAudio?Rc.AUDIO:Rc.VIDEO,j=(b===Rc.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;j&&this.afterBufferFlushed(j,b,$a.MAIN)}x=this.getNextFragmentLoopLoading(x,d,o,$a.MAIN,m)}x&&(this.exceedsMaxBuffer(o,m,x)||(x.initSegment&&!x.initSegment.data&&!this.bitrateTest&&(x=x.initSegment),this.loadFragment(x,l,f)))}loadFragment(t,r,n){const a=this.fragmentTracker.getState(t);a===lm.NOT_LOADED||a===lm.PARTIAL?oh(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,r)):super.loadFragment(t,r,n):this._loadInitSegment(t,r):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,$a.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var t;(((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:r}=this;if(r!=null&&r.readyState){let n;const a=this.getAppendedFrag(r.currentTime);a&&a.start>1&&this.flushMainBuffer(0,a.start-1);const i=this.getLevelDetails();if(i!=null&&i.live){const o=this.getMainFwdBufferInfo();if(!o||o.len=l-r.maxFragLookUpTolerance&&i<=o;if(a!==null&&n.duration>a&&(i{this.hls&&this.hls.trigger(_t.AUDIO_TRACK_SWITCHED,r)}),n.trigger(_t.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(_t.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(t,r){const n=Ype(r.url,this.hls);if(n){const a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=n?2:0,this.tick()}onBufferCreated(t,r){const n=r.tracks;let a,i,l=!1;for(const o in n){const c=n[o];if(c.id==="main"){if(i=o,a=c,o==="video"){const d=n[o];d&&(this.videoBuffer=d.buffer)}}else l=!0}l&&a?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=a.buffer):this.mediaBuffer=this.media}onFragBuffered(t,r){const{frag:n,part:a}=r,i=n.type===$a.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${a?" p: "+a.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===rn.PARSED&&(this.state=rn.IDLE);return}const o=a?a.stats:n.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),oh(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,a)}const l=this.media;l&&(!this._hasEnoughToStart&&po.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,r){var n;if(r.fatal){this.state=rn.ERROR;return}switch(r.details){case kr.FRAG_GAP:case kr.FRAG_PARSING_ERROR:case kr.FRAG_DECRYPT_ERROR:case kr.FRAG_LOAD_ERROR:case kr.FRAG_LOAD_TIMEOUT:case kr.KEY_LOAD_ERROR:case kr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError($a.MAIN,r);break;case kr.LEVEL_LOAD_ERROR:case kr.LEVEL_LOAD_TIMEOUT:case kr.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===rn.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===Jo.LEVEL&&(this.state=rn.IDLE);break;case kr.BUFFER_ADD_CODEC_ERROR:case kr.BUFFER_APPEND_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.resetLoadingState();break;case kr.BUFFER_FULL_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case kr.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onFragLoadEmergencyAborted(){this.state=rn.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:r}){if(r!==Rc.AUDIO||!this.altAudio){const n=(r===Rc.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r,$a.MAIN),this.tick())}}onLevelsUpdated(t,r){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=r.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const r=t.currentTime;let n=this.startPosition;if(n>=0&&r0&&(c{const{hls:a}=this,i=n==null?void 0:n.frag;if(!i||this.fragContextChanged(i))return;r.fragmentError=0,this.state=rn.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(_t.FRAG_LOADED,n),i.bitrateTest=!1}).catch(n=>{this.state===rn.STOPPED||this.state===rn.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const r=this.playlistType,{hls:n}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:u,text:m,id3:f,initSegment:x}=a,{details:y}=d,_=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=rn.PARSING,x){const b=x.tracks;if(b){const A=o.initSegment||o;if(this.unhandledEncryptionError(x,o))return;this._bufferInitSegment(d,b,A,i),n.trigger(_t.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:r,tracks:b})}const j=x.initPTS,N=x.timescale,C=this.initPTS[o.cc];if(Sa(j)&&(!C||C.baseTime!==j||C.timescale!==N)){const A=x.trackId;this.initPTS[o.cc]={baseTime:j,timescale:N,trackId:A},n.trigger(_t.INIT_PTS_FOUND,{frag:o,id:r,initPTS:j,timescale:N,trackId:A})}}if(u&&y){_&&u.type==="audiovideo"&&this.logMuxedErr(o);const b=y.fragments[o.sn-1-y.startSN],j=o.sn===y.startSN,N=!b||o.cc>b.cc;if(a.independent!==!1){const{startPTS:C,endPTS:A,startDTS:E,endDTS:D}=u;if(c)c.elementaryStreams[u.type]={startPTS:C,endPTS:A,startDTS:E,endDTS:D};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!N&&(this.couldBacktrack=!0),u.dropped&&u.independent){const R=this.getMainFwdBufferInfo(),F=(R?R.end:this.getLoadPosition())+this.config.maxBufferHole,O=u.firstKeyFramePTS?u.firstKeyFramePTS:C;if(!j&&Fbhe&&(o.gap=!0);o.setElementaryStreamInfo(u.type,C,A,E,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,j||N)}else if(j||N)o.gap=!0;else{this.backtrack(o);return}}if(_){const{startPTS:b,endPTS:j,startDTS:N,endDTS:C}=_;c&&(c.elementaryStreams[Rc.AUDIO]={startPTS:b,endPTS:j,startDTS:N,endDTS:C}),o.setElementaryStreamInfo(Rc.AUDIO,b,j,N,C),this.bufferFragmentData(_,o,c,i)}if(y&&f!=null&&f.samples.length){const b={id:r,frag:o,details:y,samples:f.samples};n.trigger(_t.FRAG_PARSING_METADATA,b)}if(y&&m){const b={id:r,frag:o,details:y,samples:m.samples};n.trigger(_t.FRAG_PARSING_USERDATA,b)}}logMuxedErr(t){this.warn(`${oh(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,r,n,a){if(this.state!==rn.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&(delete r.audio,r.audiovideo&&this.logMuxedErr(n));const{audio:i,video:l,audiovideo:o}=r;if(i){const d=t.audioCodec;let u=mhe(i.codec,d);u==="mp4a"&&(u="mp4a.40.5");const m=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const f=i.metadata;f&&"channelCount"in f&&(f.channelCount||1)!==1&&m.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&m.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=$a.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${i.codec}]`),delete r.audiovideo}if(l){l.levelCodec=t.videoCodec,l.id=$a.MAIN;const d=l.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":l.codec="hvc1.1.6.L120.90";break;case"av01":l.codec="av01.0.04M.08";break;case"avc1":l.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${l.container}, codecs[level/parsed]=[${t.videoCodec||""}/${d}]${l.codec!==d?" parsed-corrected="+l.codec:""}${l.supplemental?" supplemental="+l.supplemental:""}`),delete r.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete r.video,delete r.audio);const c=Object.keys(r);if(c.length){if(this.hls.trigger(_t.BUFFER_CODECS,r),!this.hls)return;c.forEach(d=>{const m=r[d].initSegment;m!=null&&m.byteLength&&this.hls.trigger(_t.BUFFER_APPENDING,{type:d,data:m,frag:n,part:null,chunkMeta:a,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,$a.MAIN)}get maxBufferLength(){const{levels:t,level:r}=this,n=t==null?void 0:t[r];return n?this.getMaxBufferLength(n.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=rn.IDLE}checkFragmentChanged(){const t=this.media;let r=null;if(t&&t.readyState>1&&t.seeking===!1){const n=t.currentTime;if(po.isBuffered(t,n)?r=this.getAppendedFrag(n):po.isBuffered(t,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const a=this.fragPlaying,i=r.level;(!a||r.sn!==a.sn||a.level!==i)&&(this.fragPlaying=r,this.hls.trigger(_t.FRAG_CHANGED,{frag:r}),(!a||a.level!==i)&&this.hls.trigger(_t.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const r=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return Sa(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var t;const r=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Sa(r)){const n=this.getLevelDetails(),a=this.currentFrag||(n?VA(null,n.fragments,r):null);if(a){const i=a.programDateTime;if(i!==null){const l=i+(r-a.start)*1e3;return new Date(l)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Otr extends yv{constructor(t,r){super("key-loader",r),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const n in this.keyIdToKeyInfo){const a=this.keyIdToKeyInfo[n].loader;if(a){var r;if(t&&t!==((r=a.context)==null?void 0:r.frag.type))return;a.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[t];(r.mediaKeySessionContext||r.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[t].loader;r&&r.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,r=kr.KEY_LOAD_ERROR,n,a,i){return new Pj({type:di.NETWORK_ERROR,details:r,fatal:!1,frag:t,response:i,error:n,networkDetails:a})}loadClear(t,r,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(r.length)for(let a=0,i=r.length;a{if(!this.emeController)return;l.setKeyFormat(o);const c=phe(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=YO(this.config);if(a.length)return this.emeController.getKeySystemAccess(a)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(r=>this.loadInternal(t,r)):this.loadInternal(t)}loadInternal(t,r){var n,a;r&&t.setKeyFormat(r);const i=t.decryptdata;if(!i){const d=new Error(r?`Expected frag.decryptdata to be defined after setting format ${r}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,kr.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,kr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=Zje(i);let c=this.keyIdToKeyInfo[o];if((n=c)!=null&&n.decryptdata.key)return i.key=c.decryptdata.key,Promise.resolve({frag:t,keyInfo:c});if(this.emeController&&(a=c)!=null&&a.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(u=>{const{keyInfo:m}=u;return i.key=m.decryptdata.key,{frag:t,keyInfo:m}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${i.keyId?" keyId: "+Of(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,kr.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,r){const n={frag:r,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var a;if(!t.decryptdata.keyId&&(a=r.initSegment)!=null&&a.data){const l=sXs(r.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Of(o)}`),SS.setKeyIdForUri(t.decryptdata.uri,o)):(o=SS.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${Of(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!oh(r))return Promise.resolve(n);const i=this.emeController.loadKey(n);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,n))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=r),l})}return Promise.resolve(n)}loadKeyHTTP(t,r){const n=this.config,a=n.loader,i=new a(n);return r.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:r,responseType:"arraybuffer",url:t.decryptdata.uri},d=n.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(f,x,y,_)=>{const{frag:b,keyInfo:j}=y,N=Zje(j.decryptdata);if(!b.decryptdata||j!==this.keyIdToKeyInfo[N])return o(this.createKeyLoadError(b,kr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));j.decryptdata.key=b.decryptdata.key=new Uint8Array(f.data),b.keyLoader=null,j.loader=null,l({frag:b,keyInfo:j})},onError:(f,x,y,_)=>{this.resetLoader(x),o(this.createKeyLoadError(r,kr.KEY_LOAD_ERROR,new Error(`HTTP Error ${f.code} loading key ${f.text}`),y,uc({url:c.url,data:void 0},f)))},onTimeout:(f,x,y)=>{this.resetLoader(x),o(this.createKeyLoadError(r,kr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),y))},onAbort:(f,x,y)=>{this.resetLoader(x),o(this.createKeyLoadError(r,kr.INTERNAL_ABORTED,new Error("key loading aborted"),y))}};i.load(c,u,m)})}resetLoader(t){const{frag:r,keyInfo:n,url:a}=t,i=n.loader;r.keyLoader===i&&(r.keyLoader=null,n.loader=null);const l=Zje(n.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function Zje(s){if(s.keyFormat!==$f.FAIRPLAY){const t=s.keyId;if(t)return Of(t)}return s.uri}function DZe(s){const{type:t}=s;switch(t){case Jo.AUDIO_TRACK:return $a.AUDIO;case Jo.SUBTITLE_TRACK:return $a.SUBTITLE;default:return $a.MAIN}}function Xje(s,t){let r=s.url;return(r===void 0||r.indexOf("data:")===0)&&(r=t.url),r}class Ftr{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(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_t.LEVEL_LOADING,this.onLevelLoading,this),t.on(_t.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(_t.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(_t.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(_t.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_t.LEVEL_LOADING,this.onLevelLoading,this),t.off(_t.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(_t.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(_t.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const r=this.hls.config,n=r.pLoader,a=r.loader,i=n||a,l=new i(r);return this.loaders[t.type]=l,l}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const r=this.loaders[t];r&&r.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,r){const{url:n}=r;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Jo.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,r){const{id:n,level:a,pathwayId:i,url:l,deliveryDirectives:o,levelInfo:c}=r;this.load({id:n,level:a,pathwayId:i,responseType:"text",type:Jo.LEVEL,url:l,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(t,r){const{id:n,groupId:a,url:i,deliveryDirectives:l,track:o}=r;this.load({id:n,groupId:a,level:null,responseType:"text",type:Jo.AUDIO_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onSubtitleTrackLoading(t,r){const{id:n,groupId:a,url:i,deliveryDirectives:l,track:o}=r;this.load({id:n,groupId:a,level:null,responseType:"text",type:Jo.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,r){const n=this.loaders[Jo.LEVEL];if(n){const a=n.context;a&&!r.levels.some(i=>i===a.levelOrTrack)&&(n.abort(),delete this.loaders[Jo.LEVEL])}}load(t){var r;const n=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===Jo.MANIFEST?i=n.manifestLoadPolicy.default:i=Ac({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Sa((r=t.deliveryDirectives)==null?void 0:r.part)){let d;if(t.type===Jo.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===Jo.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===Jo.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const u=d.partTarget,m=d.targetduration;if(u&&m){const f=Math.max(u*3,m*.8)*1e3;i=Ac({},i,{maxTimeToFirstByteMs:Math.min(f,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(f,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,m,f)=>{const x=this.getInternalLoader(m);this.resetInternalLoader(m.type);const y=d.data;u.parsing.start=performance.now(),g_.isMediaPlaylist(y)||m.type!==Jo.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,m,f||null,x):this.handleMasterPlaylist(d,u,m,f)},onError:(d,u,m,f)=>{this.handleNetworkError(u,m,!1,d,f)},onTimeout:(d,u,m)=>{this.handleNetworkError(u,m,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:r},forceStartLoad:n}=this.hls;(t||n)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${r}`),this.hls.startLoad(r))}handleMasterPlaylist(t,r,n,a){const i=this.hls,l=t.data,o=Xje(t,n),c=g_.parseMasterPlaylist(l,o);if(c.playlistParsingError){r.parsing.end=performance.now(),this.handleManifestParsingError(t,n,c.playlistParsingError,a,r);return}const{contentSteering:d,levels:u,sessionData:m,sessionKeys:f,startTimeOffset:x,variableList:y}=c;this.variableList=y,u.forEach(N=>{const{unknownCodecs:C}=N;if(C){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:E,videoCodec:D}=N;for(let R=C.length;R--;){const F=C[R];Fz(F,"audio",A)?(N.audioCodec=E=E?`${E},${F}`:F,o8.audio[E.substring(0,4)]=2,C.splice(R,1)):Fz(F,"video",A)&&(N.videoCodec=D=D?`${D},${F}`:F,o8.video[D.substring(0,4)]=2,C.splice(R,1))}}});const{AUDIO:_=[],SUBTITLES:b,"CLOSED-CAPTIONS":j}=g_.parseMasterPlaylistMedia(l,o,c);_.length&&!_.some(C=>!C.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 nu({}),bitrate:0,url:""})),i.trigger(_t.MANIFEST_LOADED,{levels:u,audioTracks:_,subtitles:b,captions:j,contentSteering:d,url:o,stats:r,networkDetails:a,sessionData:m,sessionKeys:f,startTimeOffset:x,variableList:y})}handleTrackOrLevelPlaylist(t,r,n,a,i){const l=this.hls,{id:o,level:c,type:d}=n,u=Xje(t,n),m=Sa(c)?c:Sa(o)?o:0,f=DZe(n),x=g_.parseLevelPlaylist(t.data,u,m,f,0,this.variableList);if(d===Jo.MANIFEST){const y={attrs:new nu({}),bitrate:0,details:x,name:"",url:u};x.requestScheduled=r.loading.start+N_t(x,0),l.trigger(_t.MANIFEST_LOADED,{levels:[y],audioTracks:[],url:u,stats:r,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=x,this.handlePlaylistLoaded(x,t,r,n,a,i)}handleManifestParsingError(t,r,n,a,i){this.hls.trigger(_t.ERROR,{type:di.NETWORK_ERROR,details:kr.MANIFEST_PARSING_ERROR,fatal:r.type===Jo.MANIFEST,url:t.url,err:n,error:n,reason:n.message,response:t,context:r,networkDetails:a,stats:i})}handleNetworkError(t,r,n=!1,a,i){let l=`A network ${n?"timeout":"error"+(a?" (status "+a.code+")":"")} occurred while loading ${t.type}`;t.type===Jo.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===Jo.AUDIO_TRACK||t.type===Jo.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=kr.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case Jo.MANIFEST:c=n?kr.MANIFEST_LOAD_TIMEOUT:kr.MANIFEST_LOAD_ERROR,d=!0;break;case Jo.LEVEL:c=n?kr.LEVEL_LOAD_TIMEOUT:kr.LEVEL_LOAD_ERROR,d=!1;break;case Jo.AUDIO_TRACK:c=n?kr.AUDIO_TRACK_LOAD_TIMEOUT:kr.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Jo.SUBTITLE_TRACK:c=n?kr.SUBTITLE_TRACK_LOAD_TIMEOUT:kr.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const m={type:di.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:u,context:t,error:o,networkDetails:r,stats:i};if(a){const f=(r==null?void 0:r.url)||t.url;m.response=uc({url:f,data:void 0},a)}this.hls.trigger(_t.ERROR,m)}handlePlaylistLoaded(t,r,n,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:m,groupId:f,deliveryDirectives:x}=a,y=Xje(r,a),_=DZe(a);let b=typeof a.level=="number"&&_===$a.MAIN?d:void 0;const j=t.playlistParsingError;if(j){if(this.hls.logger.warn(`${j} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(_t.ERROR,{type:di.NETWORK_ERROR,details:kr.LEVEL_PARSING_ERROR,fatal:!1,url:y,error:j,reason:j.message,response:r,context:a,level:b,parent:_,networkDetails:i,stats:n});return}t.playlistParsingError=null}if(!t.fragments.length){const N=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(_t.ERROR,{type:di.NETWORK_ERROR,details:kr.LEVEL_EMPTY_ERROR,fatal:!1,url:y,error:N,reason:N.message,response:r,context:a,level:b,parent:_,networkDetails:i,stats:n});return}switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),(!l.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),c){case Jo.MANIFEST:case Jo.LEVEL:if(b){if(!u)b=0;else if(u!==o.levels[b]){const N=o.levels.indexOf(u);N>-1&&(b=N)}}o.trigger(_t.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:b||0,id:m||0,stats:n,networkDetails:i,deliveryDirectives:x,withoutMultiVariant:c===Jo.MANIFEST});break;case Jo.AUDIO_TRACK:o.trigger(_t.AUDIO_TRACK_LOADED,{details:t,track:u,id:m||0,groupId:f||"",stats:n,networkDetails:i,deliveryDirectives:x});break;case Jo.SUBTITLE_TRACK:o.trigger(_t.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:m||0,groupId:f||"",stats:n,networkDetails:i,deliveryDirectives:x});break}}}class l_{static get version(){return $z}static isMSESupported(){return jwt()}static isSupported(){return Ptr()}static getMediaSource(){return US()}static get Events(){return _t}static get MetadataSchema(){return y0}static get ErrorTypes(){return di}static get ErrorDetails(){return kr}static get DefaultConfig(){return l_.defaultConfig?l_.defaultConfig:_tr}static set DefaultConfig(t){l_.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 DIe,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const r=this.logger=VZs(t.debug||!1,"Hls instance",t.assetPlayerId),n=this.config=jtr(l_.DefaultConfig,t,r);this.userConfig=t,n.progressive&&Ntr(n,r);const{abrController:a,bufferController:i,capLevelController:l,errorController:o,fpsController:c}=n,d=new o(this),u=this.abrController=new a(this),m=new zXs(this),f=n.interstitialsController,x=f?this.interstitialsController=new f(this,l_):null,y=this.bufferController=new i(this,m),_=this.capLevelController=new l(this),b=new c(this),j=new Ftr(this),N=n.contentSteeringController,C=N?new N(this):null,A=this.levelController=new Itr(this,C),E=new Atr(this),D=new Otr(this.config,this.logger),R=this.streamController=new Rtr(this,m,D),F=this.gapController=new Ttr(this,m);_.setStreamController(R),b.setStreamController(R);const O=[j,A,R];x&&O.splice(1,0,x),C&&O.splice(1,0,C),this.networkControllers=O;const B=[u,y,F,_,b,E,m];this.audioTrackController=this.createController(n.audioTrackController,O);const K=n.audioStreamController;K&&O.push(this.audioStreamController=new K(this,m,D)),this.subtitleTrackController=this.createController(n.subtitleTrackController,O);const Z=n.subtitleStreamController;Z&&O.push(this.subtititleStreamController=new Z(this,m,D)),this.createController(n.timelineController,B),D.emeController=this.emeController=this.createController(n.emeController,B),this.cmcdController=this.createController(n.cmcdController,B),this.latencyController=this.createController(Mtr,B),this.coreComponents=B,O.push(d);const Q=d.onErrorOut;typeof Q=="function"&&this.on(_t.ERROR,Q,d),this.on(_t.MANIFEST_LOADED,j.onManifestLoaded,j)}createController(t,r){if(t){const n=new t(this);return r&&r.push(n),n}return null}on(t,r,n=this){this._emitter.on(t,r,n)}once(t,r,n=this){this._emitter.once(t,r,n)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,r,n=this,a){this._emitter.off(t,r,n,a)}listeners(t){return this._emitter.listeners(t)}emit(t,r,n){return this._emitter.emit(t,r,n)}trigger(t,r){if(this.config.debug)return this.emit(t,t,r);try{return this.emit(t,t,r)}catch(n){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const a=t===_t.ERROR;this.trigger(_t.ERROR,{type:di.OTHER_ERROR,details:kr.INTERNAL_EXCEPTION,fatal:a,event:t,error:n}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(_t.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(r=>r.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(r=>r.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const i=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(_t.ERROR,{type:di.OTHER_ERROR,details:kr.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const r="media"in t,n=r?t.media:t,a=r?t:{media:n};this._media=n,this.trigger(_t.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(_t.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(_t.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const r=this.media,n=this._url,a=this._url=NIe.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${a}`),r&&n&&(n!==a||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(_t.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,r){this.logger.log(`startLoad(${t+(r?", ":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[$a.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[$a.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[$a.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,r=t==null?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),r&&this.startLoad(r))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=Ter()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const r=!!t;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){jXs(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:r}}=this;if(!t)return 0;const n=t.length;for(let a=0;a=r)return a;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:r,maxHdcpLevel:n}=this;let a;if(r===-1&&t!=null&&t.length?a=t.length-1:a=r,n)for(let i=a;i--;){const l=t[i].attrs["HDCP-LEVEL"];if(l&&l<=n)return i}return a}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var r;return((r=this.audioTrackController)==null?void 0:r.setAudioOption(t))||null}setSubtitleOption(t){var r;return((r=this.subtitleTrackController)==null?void 0:r.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const r=this.audioTrackController;r&&(r.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const r=this.subtitleTrackController;r&&(r.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,r=this.allAudioTracks){const n=c_t(r);return o_t(t,n,navigator.mediaCapabilities)}}l_.defaultConfig=void 0;const ztr=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function RI(s){return!!s&&ztr.test(s)&&!/\.mp4($|\?)/i.test(s)}function Btr(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function $tr(s,t){if(!s)return null;const r=Btr(s);if(r){const n=new URLSearchParams({autoplay:t!=null&&t.autoplay?"true":"false",muted:t!=null&&t.muted?"true":"false",loop:t!=null&&t.loop?"true":"false",preload:"true",responsive:"true",playsinline:"true"});return`https://player.mediadelivery.net/embed/${r.libraryId}/${r.videoId}?${n.toString()}`}return/player\.mediadelivery\.net\/embed\//i.test(s)?s:/iframe\.mediadelivery\.net\/(?:play|embed)\//i.test(s)?s.replace("iframe.mediadelivery.net/play/","player.mediadelivery.net/embed/").replace("iframe.mediadelivery.net/embed/","player.mediadelivery.net/embed/"):s}function Utr(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const l3e=k.forwardRef(function({sourceUrl:t,thumbnailUrl:r,autoPlay:n,muted:a,loop:i,playsInline:l=!0,...o},c){const d=k.useRef(null),[u,m]=k.useState(null),f=k.useMemo(()=>$tr(t,{autoplay:!!n,muted:!!a,loop:!!i}),[t,n,a,i]);k.useEffect(()=>{let y=!1;if(!t){m(null);return}if(!RI(t)){m(t);return}if(!f){m(null);return}return m(null),fetch(f).then(async _=>{if(!_.ok)throw new Error(`Failed to load Bunny embed (${_.status})`);const b=await _.text();return Utr(b)}).then(_=>{y||m(_)}).catch(()=>{y||m(null)}),()=>{y=!0}},[f,t]),k.useEffect(()=>{const y=d.current;if(!y||!u)return;let _=null;const b=()=>{if(!n)return;const N=y.play();N&&N.catch(()=>{})};if(y.muted=!!a,y.loop=!!i,u.endsWith(".m3u8")){if(y.canPlayType("application/vnd.apple.mpegurl")){y.src=u;const N=()=>b();return y.addEventListener("loadedmetadata",N),()=>{y.removeEventListener("loadedmetadata",N),y.removeAttribute("src"),y.load()}}return l_.isSupported()?(_=new l_({enableWorker:!0,lowLatencyMode:!0}),_.loadSource(u),_.attachMedia(y),_.on(l_.Events.MANIFEST_PARSED,b),()=>{_==null||_.destroy(),y.removeAttribute("src"),y.load()}):void 0}y.src=u;const j=()=>b();return y.addEventListener("loadedmetadata",j),()=>{y.removeEventListener("loadedmetadata",j),y.removeAttribute("src"),y.load()}},[n,i,a,u]),k.useEffect(()=>{const y=d.current;if(y){if(y.muted=!!a,y.loop=!!i,n&&u){const _=y.play();_&&_.catch(()=>{});return}y.pause()}},[n,i,a,u]);const x=y=>{if(d.current=y,typeof c=="function"){c(y);return}c&&(c.current=y)};return e.jsx("video",{ref:x,poster:r||void 0,autoPlay:n,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),qtr={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 Vtr(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function RZe(s,t){return!s||s.length===0?!1:s.some(r=>r?r===t?!0:r.endsWith("*")?t.startsWith(r.slice(0,-1)):t.startsWith(r):!1)}function KIe({config:s,appSlug:t="video_greeter",preview:r=!1,embedded:n=!1}){const[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!0),[u,m]=k.useState(!1),[f,x]=k.useState("portrait"),[y,_]=k.useState(!1),[b,j]=k.useState(!1),[N,C]=k.useState({name:"",email:"",phone:""}),[A,E]=k.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),D=k.useRef(null),R=k.useRef(null),F=k.useRef(!1),O=async(Se,Ge)=>{if(!r)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Se,visitor_token:Vtr(),page_url:typeof window<"u"?window.location.href:null,metadata:Ge||{}})}catch{}};k.useEffect(()=>{if(u)return;const Se=typeof window<"u"?window.location.pathname:"/",Ge=s.targeting||{mode:"all"};if(Ge.mode==="include"&&!RZe(Ge.include,Se)||Ge.mode==="exclude"&&RZe(Ge.exclude,Se))return;const We=s.trigger||{type:"immediate"};if(We.type==="immediate"||r){i(!0);return}if(We.type==="delay"){const Ce=(We.value||3)*1e3,qe=setTimeout(()=>i(!0),Ce);return()=>clearTimeout(qe)}if(We.type==="scroll"){const Ce=(We.value||25)/100,qe=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ce&&(i(!0),window.removeEventListener("scroll",qe))};return window.addEventListener("scroll",qe,{passive:!0}),()=>window.removeEventListener("scroll",qe)}if(We.type==="exit_intent"){const Ce=qe=>{qe.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ce),()=>document.removeEventListener("mouseleave",Ce)}},[u,s.targeting,s.trigger,r]),k.useEffect(()=>{a&&!F.current&&(F.current=!0,O("impression"))},[a]),k.useEffect(()=>{if(l&&R.current&&!RI(s.video_url)){R.current.currentTime=0,R.current.muted=!1,d(!1);const Se=R.current.play();Se&&Se.catch(()=>{})}else l&&RI(s.video_url)&&d(!1)},[l,s.video_url]),k.useEffect(()=>{if(!s.thumbnail_url)return;let Se=!1;const Ge=new Image;return Ge.onload=()=>{Se||x(Ge.naturalWidth>Ge.naturalHeight?"landscape":"portrait")},Ge.src=s.thumbnail_url,()=>{Se=!0}},[s.thumbnail_url]),k.useEffect(()=>{const Se=()=>{E({width:window.innerWidth,height:window.innerHeight})};return Se(),window.addEventListener("resize",Se),()=>window.removeEventListener("resize",Se)},[]);const B=()=>{o(!0),O("expand")},K=Se=>{Se.stopPropagation(),m(!0),o(!1)},Z=Se=>{O("cta_click",{cta_id:Se.id,label:Se.label,url:Se.url})},Q=async Se=>{if(Se.preventDefault(),r){_(!0);return}if(!(!N.email||!N.name)){j(!0);try{const{error:Ge}=await U.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:N.name,email:N.email,phone:N.phone||void 0,page_url:window.location.href}});if(Ge)throw Ge;O("lead_capture",{email:N.email}),_(!0)}catch(Ge){console.error("lead submit failed",Ge)}finally{j(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const W=qtr[f][s.size||"md"],te=n?"absolute left-2 bottom-2":r?s.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":s.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",ne=s.shape==="circle"?"rounded-full":"rounded-2xl",ae=r?f==="landscape"?"w-[280px]":"w-[220px]":f==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",ue=f==="landscape"?"aspect-video":"aspect-[9/16]",me=s.agent||{},de=s.lead_form_fields||["name","email","phone"],fe=!!(s.show_socials&&(me.instagram_url||me.facebook_url||me.linkedin_url)),je=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!y?72+de.length*42:0)+(y?40:0)+(fe?34:0),xe=Math.max(300,A.height-32),Ee=Math.max(220,A.width-32),Me=Math.max(150,xe-je),Oe=Math.floor(f==="landscape"?Me*(16/9):Me*(9/16)),Ie=f==="landscape"?Math.max(220,Math.min(420,Ee,Oe)):Math.max(180,Math.min(340,Ee,Oe)),ze=n?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${ae} 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`,Ve=n?{width:`${Ie}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Le=n?"p-3 space-y-2.5":"p-4 space-y-3",$e=n?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",ve=n?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Qe=n?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",we=n?"w-full px-3 py-1.5 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400":"w-full px-3 py-2 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400",nt=n?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return e.jsx("div",{"data-vg-widget":!0,"data-expanded":l?"true":"false",className:`${te} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:ze,style:Ve,children:[e.jsxs("div",{className:`relative bg-black ${ue}`,children:[RI(s.video_url)?e.jsx(l3e,{ref:R,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Se=>{const{videoWidth:Ge,videoHeight:We}=Se.currentTarget;Ge&&We&&x(Ge>We?"landscape":"portrait")},onEnded:()=>O("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:R,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>O("watch_complete"),onLoadedMetadata:Se=>{const{videoWidth:Ge,videoHeight:We}=Se.currentTarget;Ge&&We&&x(Ge>We?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{R.current&&(R.current.muted=!R.current.muted,d(R.current.muted))},className:"absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur",children:c?e.jsx(a7,{className:"w-4 h-4"}):e.jsx(n7,{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($r,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Le,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[me.avatar_url&&e.jsx("img",{src:me.avatar_url,alt:me.name||"",className:$e}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:ve,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:Qe,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Se=>{var Ge;return e.jsxs("a",{href:Se.url,target:(Ge=Se.url)!=null&&Ge.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>Z(Se),className:`flex items-center justify-between gap-2 ${n?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${Se.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:Se.label}),e.jsx(un,{className:"w-3.5 h-3.5 opacity-60"})]},Se.id)})}),s.lead_form_enabled&&!y&&e.jsxs("form",{onSubmit:Q,className:"space-y-2 pt-1",children:[de.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:N.name,onChange:Se=>C({...N,name:Se.target.value}),className:we}),de.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:N.email,onChange:Se=>C({...N,email:Se.target.value}),className:we}),de.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:N.phone,onChange:Se=>C({...N,phone:Se.target.value}),className:we}),e.jsxs("button",{type:"submit",disabled:b,className:nt,children:[e.jsx(hn,{className:"w-3.5 h-3.5"}),b?"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&&(me.instagram_url||me.facebook_url||me.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[me.instagram_url&&e.jsx("a",{href:me.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>O("cta_click",{social:"instagram"}),children:e.jsx(gu,{className:"w-4 h-4"})}),me.facebook_url&&e.jsx("a",{href:me.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>O("cta_click",{social:"facebook"}),children:e.jsx(mh,{className:"w-4 h-4"})}),me.linkedin_url&&e.jsx("a",{href:me.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>O("cta_click",{social:"linkedin"}),children:e.jsx(Yf,{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:B,className:`relative ${ne} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:W.w,height:W.h},"aria-label":"Play video greeting",children:[RI(s.video_url)?e.jsx(l3e,{ref:D,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:Se=>{const{videoWidth:Ge,videoHeight:We}=Se.currentTarget;Ge&&We&&x(Ge>We?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:D,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:Se=>{const{videoWidth:Ge,videoHeight:We}=Se.currentTarget;Ge&&We&&x(Ge>We?"landscape":"portrait")}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),e.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:e.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),e.jsx("button",{onClick:K,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($r,{className:"w-3.5 h-3.5"})})]})})}function YIe({slug:s}){const[t,r]=k.useState(null);return k.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await U.rpc("get_public_video_greeter_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(KIe,{config:t}):null}const Nwt="eip_last_shown",OZe="eip_visitor_token";function Htr(){try{let s=localStorage.getItem(OZe);return s||(s=crypto.randomUUID(),localStorage.setItem(OZe,s)),s}catch{return}}function Gtr(s){try{const t=Number(localStorage.getItem(Nwt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function Wtr(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,n=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?n:!n}function kwt({config:s,preview:t=!1,forceOpen:r=!1}){const[n,a]=k.useState(r),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState({name:"",email:"",phone:""}),m=k.useRef(!1),f=k.useRef(!1),x=async(D,R={})=>{if(!t)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:D,visitor_token:Htr(),page_url:window.location.href,metadata:R})}catch{}};k.useEffect(()=>{if(t||!Wtr(s.targeting)||!Gtr(s.frequency_days))return;const D=/Mobi|Android/i.test(navigator.userAgent),R={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,F=Z=>{if(!m.current){m.current=!0,a(!0);try{localStorage.setItem(Nwt,String(Date.now()))}catch{}x("impression",{reason:Z})}},O=Z=>{Z.clientY<=R&&F("mouse_leave")},B=()=>{s.enable_mobile_back&&D&&F("back_button")};if(s.enable_mobile_back&&D){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",B)}else document.addEventListener("mouseleave",O);let K;return s.enable_time_fallback&&(K=window.setTimeout(()=>F("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",O),window.removeEventListener("popstate",B),K&&window.clearTimeout(K)}},[s,t]),k.useEffect(()=>{n&&!f.current&&!t&&!m.current&&(f.current=!0)},[n,t]);const y=()=>{a(!1),t||x("close")},_=async D=>{if(D.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:R}=await U.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(R)throw R;x("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(R){console.error("exit intent submit failed",R)}finally{c(!1)}}};if(!n)return null;const b=s.form_fields||["name","email"],j=s.agent||{},N=[j.first_name,j.last_name].filter(Boolean).join(" "),C=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:D=>D.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${A}, ${Qje(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($r,{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:[C&&e.jsx("img",{src:C,alt:N||"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(Ir,{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:[b.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:D=>u({...d,name:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),b.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:D=>u({...d,email:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),b.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:D=>u({...d,phone:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A}}),e.jsx("button",{type:"submit",disabled:o,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${A}, ${Qje(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:()=>x("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}, ${Qje(A,-20)})`},children:s.cta_label}),N&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",N]})]})]})})}function Qje(s,t){try{const r=parseInt(s.slice(1),16),n=t<0?0:255,a=Math.abs(t)/100,i=r>>16,l=r>>8&255,o=r&255,c=Math.round((n-i)*a)+i,d=Math.round((n-l)*a)+l,u=Math.round((n-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+u).toString(16).slice(1)}catch{return s}}function ZIe({slug:s}){const[t,r]=k.useState(null);return k.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await U.rpc("get_public_exit_intent_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(kwt,{config:t}):null}const FZe="lm_dismissed",zZe="lm_visitor_token";function Ktr(){try{let s=localStorage.getItem(zZe);return s||(s=crypto.randomUUID(),localStorage.setItem(zZe,s)),s}catch{return}}function Ytr(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,n=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?n:!n}function XIe({config:s,preview:t=!1}){const[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,m]=k.useState({name:"",email:"",phone:""}),f=k.useRef(!1),x=async(C,A={})=>{if(!t)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:C,visitor_token:Ktr(),page_url:window.location.href,metadata:A})}catch{}};k.useEffect(()=>{if(t){n(!0);return}if(!Ytr(s.targeting))return;try{if(sessionStorage.getItem(FZe))return}catch{}const C=()=>{f.current||(f.current=!0,n(!0),x("impression"))};if(s.trigger_type==="immediate")C();else if(s.trigger_type==="delay"){const A=window.setTimeout(C,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)&&C()};return window.addEventListener("scroll",A,{passive:!0}),()=>window.removeEventListener("scroll",A)}},[s,t]);const y=()=>{n(!1);try{sessionStorage.setItem(FZe,"1")}catch{}t||x("close")},_=async C=>{if(C.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:A}=await U.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:u.name,email:u.email,phone:u.phone||void 0,page_url:window.location.href}});if(A)throw A;x("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(!r)return null;const b=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, ${b}, ${_O(b,-20)})`},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[e.jsx(Di,{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),x("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:b},children:s.download_label}),e.jsx("button",{onClick:y,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx($r,{className:"w-4 h-4"})})]})}),a&&N()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),x("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, ${b}, ${_O(b,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:e.jsx(vm,{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:C=>{C.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($r,{className:"w-3 h-3"})})]}),a&&N()]});return N();function N(){const C=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:D=>D.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${b}, ${_O(b,-25)})`},children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:s.title,className:"w-full h-full object-cover opacity-90"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(En,{className:"w-20 h-20 text-white/40"})}),e.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:b},children:[e.jsx(Di,{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($r,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.description})]}),l?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${b}10`},children:[e.jsx(li,{className:"w-8 h-8 mx-auto",style:{color:b}}),e.jsx("p",{className:"text-sm font-medium",style:{color:b},children:s.success_message}),s.download_url&&e.jsx("a",{href:s.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:b},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:_,className:"space-y-2.5",children:[C.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:u.name,onChange:D=>m({...u,name:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b},required:!0}),C.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:D=>m({...u,email:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b},required:!0}),C.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:D=>m({...u,phone:D.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":b}}),e.jsxs("button",{type:"submit",disabled:c,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${b}, ${_O(b,-20)})`},children:[e.jsx(li,{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:()=>x("cta_click",{url:s.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${b}, ${_O(b,-20)})`},children:s.download_label}),E&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",E]})]})]})})}}function _O(s,t){try{const r=parseInt(s.slice(1),16),n=t<0?0:255,a=Math.abs(t)/100,i=r>>16,l=r>>8&255,o=r&255,c=Math.round((n-i)*a)+i,d=Math.round((n-l)*a)+l,u=Math.round((n-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+u).toString(16).slice(1)}catch{return s}}function QIe({slug:s}){const[t,r]=k.useState(null);return k.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await U.rpc("get_public_lead_magnet_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(XIe,{config:t}):null}function Ztr({children:s,siteConfig:t}){var xe,Ee,Me,Oe,Ie,ze,Ve,Le,$e;const r=vc(),n=qr(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,m]=k.useState([]),[f,x]=k.useState([]),[y,_]=k.useState(null),b=k.useRef(null),j=k.useRef(null),{user:N,profile:C,signOut:A}=Yye();wIe(t,N==null?void 0:N.id),jIe(t,N==null?void 0:N.id);const E=((xe=t.agent)==null?void 0:xe.full_name)||"Agent",D=t.siteTitle||`${E} Real Estate`,R=r.pathname==="/search",F=r.pathname==="/",O=t.leadRegistrationMode!=="disabled";k.useEffect(()=>{(async()=>{const{data:Qe}=await U.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});m(Qe||[])})()},[t.id]),k.useEffect(()=>{(async()=>{const{data:Qe}=await U.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});x(Qe||[])})()},[t.id]),k.useEffect(()=>{const ve=Qe=>{b.current&&!b.current.contains(Qe.target)&&d(!1),j.current&&!j.current.contains(Qe.target)&&_(null)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[]);const B=Gbt(t),K=t==null?void 0:t.bookingUrl,Z=B?f.filter(ve=>{const Qe=String(ve.target_url||"").toLowerCase(),we=String(ve.label||"").toLowerCase();return Qe!=="/search"&&!Qe.startsWith("/search?")&&!we.includes("search")}):f,Q=Z.length>0,W=[{to:"/",label:"Home"},...B?[]:[{to:"/search",label:"Search"}],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],te=Q?[]:W,ne=Z.filter(ve=>!ve.parent_id),ae=ve=>Z.filter(Qe=>Qe.parent_id===ve),ue=F?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",me=t.siteTitle||`${E} - Real Estate`,de=t.siteTagline||`Browse homes and listings with ${E}`,fe=t.ogImageUrl||((Ee=t.agent)==null?void 0:Ee.avatar_url)||"",je=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${R?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(bIe,{siteConfig:t,pagePath:r.pathname}),e.jsx(_Ie,{siteConfig:t}),e.jsxs(Yo,{children:[e.jsx("title",{children:me}),e.jsx("meta",{name:"description",content:de}),e.jsx("meta",{property:"og:title",content:me}),e.jsx("meta",{property:"og:description",content:de}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:je+r.pathname}),fe&&e.jsx("meta",{property:"og:image",content:fe}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:me}),e.jsx("meta",{name:"twitter:description",content:de}),fe&&e.jsx("meta",{name:"twitter:image",content:fe}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${je}${r.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${F?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${ue}`,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(Vn,{to:"/",className:"flex items-center gap-3",children:[((Me=t.agent)==null?void 0:Me.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt: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:D})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[te.map(ve=>e.jsx(Vn,{to:ve.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname===ve.to?F?"bg-white/15 text-white":"bg-gray-100 text-gray-900":F?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:ve.label},ve.to)),Q&&ne.map(ve=>{if(ve.item_type==="dropdown"){const Qe=ae(ve.id);return e.jsxs("div",{ref:j,className:"relative",children:[e.jsxs("button",{onClick:()=>_(y===ve.id?null:ve.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${F?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[ve.label," ",e.jsx(Co,{className:`h-3.5 w-3.5 transition-transform ${y===ve.id?"rotate-180":""}`})]}),y===ve.id&&Qe.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:Qe.map(we=>e.jsx(JV,{item:we,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"},we.id))})]},ve.id)}return e.jsx(JV,{item:ve,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${F?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},ve.id)}),u.length>0&&e.jsxs("div",{ref:b,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname.startsWith("/homes-for-sale-in-")?F?"bg-white/15 text-white":"bg-gray-100 text-gray-900":F?"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(Co,{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(ve=>e.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${ve.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:ve.city_name},ve.city_slug))})]}),N?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(Vn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${F?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(yi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(Vn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${F?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(qi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Oe=C==null?void 0:C.name)==null?void 0:Oe.split(" ")[0])||"Account"})]})]}):O?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${F?"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 ${F?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx($r,{className:"h-5 w-5"}):e.jsx(aS,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${F?"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:[te.map(ve=>e.jsx(Vn,{to:ve.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===ve.to?F?"bg-white/15 text-white":"bg-gray-100 text-gray-900":F?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:ve.label},ve.to)),Q&&ne.map(ve=>{if(ve.item_type==="dropdown"){const Qe=ae(ve.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 ${F?"text-white/40":"text-gray-400"}`,children:ve.label}),Qe.map(we=>e.jsx(JV,{item:we,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${F?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},we.id))]},ve.id)}return e.jsx(JV,{item:ve,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${F?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},ve.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 ${F?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map(ve=>e.jsx(Vn,{to:`/homes-for-sale-in-${ve.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===`/homes-for-sale-in-${ve.city_slug}`?F?"bg-white/15 text-white":"bg-gray-100 text-gray-900":F?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:ve.city_name},ve.city_slug))]}),N?e.jsxs(e.Fragment,{children:[e.jsx(Vn,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${F?"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 ${F?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):O?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 ${F?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!R&&e.jsx("footer",{className:"bg-gray-950 text-gray-400",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((Ie=t.agent)==null?void 0:Ie.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:((ze=t.agent)==null?void 0:ze.title)||"Real Estate Professional"})]})]}),((Ve=t.agent)==null?void 0:Ve.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(Mn,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Le=t.agent)==null?void 0:Le.email)&&e.jsx("p",{className:"text-sm mt-1",children:e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[e.jsx(Ks,{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:[te.map(ve=>e.jsx("li",{children:e.jsx(Vn,{to:ve.to,className:"hover:text-white transition-colors",children:ve.label})},ve.to)),K&&e.jsx("li",{children:e.jsx("a",{href:K,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:B?"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(Vn,{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."]})]})]})]})}),!R&&(($e=t.agent)==null?void 0:$e.avatar_url)&&e.jsx(Xtr,{agent:t.agent,bookingUrl:K}),l&&e.jsx(vIe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(YIe,{slug:t.subdomainSlug}),e.jsx(ZIe,{slug:t.subdomainSlug}),e.jsx(QIe,{slug:t.subdomainSlug})]})}function Xtr({agent:s,bookingUrl:t}){var i;const[r,n]=k.useState(!1),a=qr();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:r?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(Mn,{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(Ks,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),e.jsx("button",{onClick:()=>{n(!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:()=>n(!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($r,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>n(!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 JV({item:s,className:t,onClick:r}){const n=s.target_url||"#";return s.item_type==="external"||s.open_in_new_tab?e.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:t,onClick:r,children:s.label}):e.jsx(Vn,{to:n,className:t,onClick:r,children:s.label})}const BZe={california:"California DRE License",ca:"California DRE License"};function c3e(s){const t=(s||"").trim();if(!t)return"Real Estate License";const r=t.toLowerCase();return BZe[r]?BZe[r]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function $Ze(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function Qtr({children:s,siteConfig:t}){var fe,je,xe,Ee,Me,Oe,Ie;const r=vc(),n=qr(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,m]=k.useState([]),[f,x]=k.useState(!1),y=k.useRef(null),{user:_,profile:b,signOut:j}=Yye();wIe(t,_==null?void 0:_.id),jIe(t,_==null?void 0:_.id);const N=((fe=t.agent)==null?void 0:fe.full_name)||"Agent",C=$Ze(t.agentLicenseNumber),A=$Ze(t.brokerageLicenseNumber),E=t.siteTitle||`${N} Real Estate`,D=t.brokerageLegalName?`${N} | ${t.brokerageLegalName}`:N,R=ze=>{if(!ze)return ze;const Ve=N.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Le=new RegExp(`^\\s*${Ve}\\s*[|\\-–—:]\\s*`,"i");return ze.replace(Le,"").trim()},F=E&&E!==`${N} Real Estate`?E:null,O=F?R(F):null,B=O&&O.toLowerCase()!==N.toLowerCase()?O:null,K=r.pathname==="/search",Z=r.pathname==="/",Q=t.leadRegistrationMode!=="disabled",W="#c9a96e";k.useEffect(()=>{const ze=()=>x(window.scrollY>80);return window.addEventListener("scroll",ze,{passive:!0}),()=>window.removeEventListener("scroll",ze)},[]),k.useEffect(()=>{(async()=>{const{data:Ve}=await U.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});m(Ve||[])})()},[t.id]),k.useEffect(()=>{const ze=Ve=>{y.current&&!y.current.contains(Ve.target)&&d(!1)};return document.addEventListener("mousedown",ze),()=>document.removeEventListener("mousedown",ze)},[]);const te=[{to:"/",label:"Home"},{to:"/search",label:"Search"},{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],ne=t.siteTitle||`${N} - Real Estate`,ae=t.siteTagline||`Browse homes and listings with ${N}`,ue=t.ogImageUrl||((je=t.agent)==null?void 0:je.avatar_url)||"",me=`https://${t.subdomainSlug||""}.thelocalmove.com`,de=Z?f?"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 ${K?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(bIe,{siteConfig:t,pagePath:r.pathname}),e.jsx(_Ie,{siteConfig:t}),e.jsxs(Yo,{children:[e.jsx("title",{children:ne}),e.jsx("meta",{name:"description",content:ae}),e.jsx("meta",{property:"og:title",content:ne}),e.jsx("meta",{property:"og:description",content:ae}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:me+r.pathname}),ue&&e.jsx("meta",{property:"og:image",content:ue}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ne}),e.jsx("meta",{name:"twitter:description",content:ae}),ue&&e.jsx("meta",{name:"twitter:image",content:ue}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${me}${r.pathname}`}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),e.jsxs("header",{className:`${Z?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${de}`,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(Vn,{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:D}),B&&e.jsx("span",{className:"mt-1 text-[11px] tracking-[0.18em] uppercase text-white/70",children:B})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-1",children:[te.map(ze=>e.jsx(Vn,{to:ze.to,className:`px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname===ze.to?"text-white":"text-white/40 hover:text-white"}`,children:ze.label},ze.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 ${r.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(Co,{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(ze=>e.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${ze.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:ze.city_name},ze.city_slug))})]}),_?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(Vn,{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(yi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(Vn,{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(qi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((xe=b==null?void 0:b.name)==null?void 0:xe.split(" ")[0])||"Account"})]})]}):Q?e.jsx("button",{onClick:()=>o(!0),className:"ml-3 px-5 py-2 text-xs tracking-[0.2em] uppercase border border-white/20 text-white/60 hover:bg-white hover:text-black transition-all duration-500",children:"Sign In"}):null]}),e.jsxs("button",{onClick:()=>i(!a),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[e.jsx("div",{className:"flex flex-col items-center gap-0.5",children:a?e.jsx($r,{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:[te.map(ze=>e.jsx(Vn,{to:ze.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${r.pathname===ze.to?"text-white":"text-white/40 hover:text-white"}`,children:ze.label},ze.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(ze=>e.jsx(Vn,{to:`/homes-for-sale-in-${ze.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:ze.city_name},ze.city_slug))]}),_?e.jsxs(e.Fragment,{children:[e.jsx(Vn,{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"})]}):Q?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!K&&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:N}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Ee=t.agent)==null?void 0:Ee.title)||"Real Estate Professional"}),(C||A)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[C&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[c3e(t.licenseState)," #",C]}),A&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",A]})]}),((Me=t.agent)==null?void 0:Me.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(Mn,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Oe=t.agent)==null?void 0:Oe.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(Ks,{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:te.map(ze=>e.jsx("li",{children:e.jsx(Vn,{to:ze.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:ze.label})},ze.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(Vn,{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:[N," · ",t.brokerageLegalName]}),C&&e.jsxs("span",{children:[c3e(t.licenseState)," #",C]}),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()," ",N,". Powered by LevelUp."]})]})]})]})}),!K&&((Ie=t.agent)==null?void 0:Ie.avatar_url)&&e.jsx(Jtr,{agent:t.agent,agentLicense:C,siteConfig:t,accentColor:W}),l&&e.jsx(vIe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:W}),e.jsx(YIe,{slug:t.subdomainSlug}),e.jsx(ZIe,{slug:t.subdomainSlug}),e.jsx(QIe,{slug:t.subdomainSlug})]})}function Jtr({agent:s,agentLicense:t,siteConfig:r,accentColor:n}){var o;const[a,i]=k.useState(!1),l=qr();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:c3e(r.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(Mn,{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(Ks,{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:n},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($r,{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:n},children:"Let's connect →"})]})]})}):null}const wO="#2c1810",Bb="#b8860b";function esr({children:s,siteConfig:t}){var F,O,B;const r=vc();qr();const[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState([]),[m,f]=k.useState(!1),x=k.useRef(null),{user:y,profile:_,signOut:b}=Yye();wIe(t,y==null?void 0:y.id),jIe(t,y==null?void 0:y.id);const j=((F=t.agent)==null?void 0:F.full_name)||"Agent",N=t.siteTitle||`${j} Land & Ranch`,C=r.pathname==="/",A=t.leadRegistrationMode!=="disabled";k.useEffect(()=>{const K=()=>f(window.scrollY>80);return window.addEventListener("scroll",K,{passive:!0}),()=>window.removeEventListener("scroll",K)},[]),k.useEffect(()=>{(async()=>{const{data:Z}=await U.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]),k.useEffect(()=>{const K=Z=>{x.current&&!x.current.contains(Z.target)&&c(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[]);const E=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],D=m||!C?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",R=m||!C?wO:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(Yo,{children:[e.jsx("title",{children:N}),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(bIe,{siteConfig:t}),e.jsx(_Ie,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${D}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[e.jsxs(Vn,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(HI,{className:"w-7 h-7",style:{color:Bb}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:R,fontFamily:"'Playfair Display', Georgia, serif"},children:N})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[E.map(K=>e.jsx(Vn,{to:K.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:r.pathname===K.path?Bb:R},children:K.label},K.path)),d.length>0&&e.jsxs("div",{ref:x,className:"relative",children:[e.jsxs("button",{onClick:()=>c(!o),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:R},children:["Areas ",e.jsx(Co,{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(K=>e.jsx(Vn,{to:`/homes-for-sale-in-${K.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:wO},onClick:()=>c(!1),children:K.city_name},K.city_slug))})]}),y?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(Vn,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:Bb,color:R},children:[e.jsx(qi,{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:Bb},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!n),className:"md:hidden p-2",style:{color:R},children:n?e.jsx($r,{className:"w-6 h-6"}):e.jsx(aS,{className:"w-6 h-6"})})]})}),n&&e.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:e.jsxs("div",{className:"px-4 py-4 space-y-1",children:[E.map(K=>e.jsx(Vn,{to:K.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:r.pathname===K.path?Bb:wO},onClick:()=>a(!1),children:K.label},K.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(K=>e.jsx(Vn,{to:`/homes-for-sale-in-${K.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:wO},onClick:()=>a(!1),children:K.city_name},K.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:Bb},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:wO},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(HI,{className:"w-6 h-6",style:{color:Bb}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:N})]}),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(K=>e.jsx(Vn,{to:K.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:K.label},K.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:[((O=t.agent)==null?void 0:O.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(Mn,{className:"w-4 h-4",style:{color:Bb}}),t.agent.phone]}),((B=t.agent)==null?void 0:B.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(Ks,{className:"w-4 h-4",style:{color:Bb}}),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()," ",N,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:Bb}})]})]})}),i&&e.jsx(vIe,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(YIe,{slug:t.subdomainSlug}),e.jsx(ZIe,{slug:t.subdomainSlug}),e.jsx(QIe,{slug:t.subdomainSlug})]})}function tsr(){const{pathname:s}=vc();return k.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const ssr=k.lazy(()=>vi(()=>import("./LeadSiteHome-DyEh5ETv.js"),__vite__mapDeps([0,1,2,3]))),rsr=k.lazy(()=>vi(()=>import("./LeadSiteLuxuryHome-CYLm3nO3.js"),__vite__mapDeps([4,2,3]))),nsr=k.lazy(()=>vi(()=>import("./LeadSiteLandRanchHome-gZ_LYj5Z.js"),__vite__mapDeps([5,1,2,3]))),asr=k.lazy(()=>vi(()=>import("./LeadSiteSearch-BiwQJhqB.js"),__vite__mapDeps([6,1,7,3,8]))),isr=k.lazy(()=>vi(()=>import("./LeadSiteLuxurySearch-Dgrs2eXR.js"),__vite__mapDeps([9,1,7,3,8]))),osr=k.lazy(()=>vi(()=>import("./LeadSiteListingDetail-BcGvlSS_.js"),__vite__mapDeps([10,11,3,12]))),lsr=k.lazy(()=>vi(()=>import("./LeadSiteLuxuryListingDetail-lVETchFg.js"),__vite__mapDeps([13,11,3,12]))),csr=k.lazy(()=>vi(()=>import("./LeadSiteAbout-BArA5FeP.js"),[])),dsr=k.lazy(()=>vi(()=>import("./LeadSiteLuxuryAbout-Czgccwzb.js"),[])),usr=k.lazy(()=>vi(()=>import("./LeadSiteContact-KbD_qVnA.js"),[])),hsr=k.lazy(()=>vi(()=>import("./LeadSiteLuxuryContact-D1V3ZqOv.js"),[])),msr=k.lazy(()=>vi(()=>import("./LeadSiteConsumerDashboard-DC6MWdgD.js"),[])),UZe=k.lazy(()=>vi(()=>import("./LeadSiteBlog-DVR3aqi7.js"),[])),fsr=k.lazy(()=>vi(()=>import("./LeadSiteCommunity-Dmtj9aiE.js"),[])),psr=k.lazy(()=>vi(()=>import("./LeadSiteSellers-Bmxm6haY.js"),[])),xsr=k.lazy(()=>vi(()=>import("./LeadSiteCityPage-BlUkEbR9.js"),__vite__mapDeps([14,3,8]))),gsr=k.lazy(()=>vi(()=>import("./LeadSiteSubdivisionPage-KALPAyHL.js"),__vite__mapDeps([15,3]))),ysr=k.lazy(()=>vi(()=>import("./LeadSiteCustomPage-Cih_bHBZ.js"),[]));function vsr(){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 bsr(){const{siteConfig:s,themeConfig:t,isLoading:r,error:n}=wZs();if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(n||!s)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});const a=(t==null?void 0:t.themeTier)==="luxury",i=(t==null?void 0:t.themeTier)==="land-ranch",l=i?esr:a?Qtr:Ztr,o=Gbt(s,t),c=i?e.jsx(nsr,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(rsr,{siteConfig:s,themeConfig:t??void 0}):e.jsx(ssr,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(NZs,{siteConfig:s,children:[e.jsx(tsr,{}),e.jsx(l,{siteConfig:s,children:e.jsx(k.Suspense,{fallback:e.jsx(vsr,{}),children:e.jsxs(eme,{children:[e.jsx(xs,{path:"/",element:c}),e.jsx(xs,{path:"/search",element:o?e.jsx(o7,{to:"/contact",replace:!0}):a?e.jsx(isr,{siteConfig:s}):e.jsx(asr,{siteConfig:s})}),e.jsx(xs,{path:"/listing/:mlsNumber",element:o?e.jsx(o7,{to:"/contact",replace:!0}):a?e.jsx(lsr,{siteConfig:s}):e.jsx(osr,{siteConfig:s})}),e.jsx(xs,{path:"/about",element:a?e.jsx(dsr,{siteConfig:s}):e.jsx(csr,{siteConfig:s})}),e.jsx(xs,{path:"/contact",element:a?e.jsx(hsr,{siteConfig:s}):e.jsx(usr,{siteConfig:s})}),e.jsx(xs,{path:"/account",element:e.jsx(msr,{siteConfig:s})}),e.jsx(xs,{path:"/blog",element:e.jsx(UZe,{siteConfig:s,isLuxury:a})}),e.jsx(xs,{path:"/blog/:slug",element:e.jsx(UZe,{siteConfig:s,isLuxury:a})}),e.jsx(xs,{path:"/sell",element:e.jsx(psr,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(xs,{path:"/community",element:e.jsx(fsr,{siteConfig:s,isLuxury:a})}),e.jsx(xs,{path:"/p/:pageSlug",element:e.jsx(ysr,{siteConfig:s})}),e.jsx(xs,{path:"/*",element:e.jsx(_sr,{siteConfig:s,referralMode:o})})]})})})]})}function _sr({siteConfig:s,referralMode:t}){const r=vc(),n=r.pathname.match(/^\/homes-in-(.+)$/);if(n)return e.jsx(gsr,{siteConfig:s,subdivisionSlug:n[1]});const a=r.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(xsr,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}const wsr=({team:s,onSelect:t})=>{const{data:r}=pt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:n}=await U.from("team_members").select("user_id, role").eq("team_id",s.id),a=(n==null?void 0:n.length)||0,i=n==null?void 0:n.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await U.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(ke,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Pt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Dt,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(Ur,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(Xe,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(Dr,{className:"h-3 w-3 mr-1"}),(r==null?void 0:r.count)??"…"]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[(r==null?void 0:r.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Wn,{className:"h-6 w-6",children:[e.jsx(Xa,{src:r.leaderProfile.avatar_url||""}),e.jsx(Kn,{className:"text-xs",children:(r.leaderProfile.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Gf,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),r.leaderProfile.name||"Team Leader"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Oh,{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(Xe,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(Xe,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(Xe,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},jsr=()=>{const{user:s,isAdmin:t,isBrokerageManager:r,brokerageId:n,managedBrokerages:a,selectedBrokerageId:i}=Cs(),l=i||(a.length>0?a[0].id:n),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:u,updateTeam:m,deleteTeam:f,addMember:x,removeMember:y,updateMemberRole:_}=aM(o),[b,j]=k.useState(!1),[N,C]=k.useState(null),{data:A}=pt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:R,error:F}=await U.from("brokerages").select("id, name").order("name");if(F)throw F;return R||[]},enabled:t}),{data:E}=pt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:R,error:F}=await U.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(F)throw F;return R||[]},enabled:!!l}),D=async R=>{const F=R.brokerage_id||l||null,O=await u.mutateAsync({name:R.name,brokerage_id:F,description:R.description});if(R.leaderId&&R.leaderId!=="none"&&await x.mutateAsync({team_id:O.id,user_id:R.leaderId,role:"team_leader"}),R.memberIds)for(const B of R.memberIds)await x.mutateAsync({team_id:O.id,user_id:B,role:"team_member"});j(!1)};return!r&&!t?e.jsx(ws,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Dr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Access Denied"}),e.jsx("p",{className:"text-muted-foreground",children:"You need brokerage manager access to manage teams."})]})}):e.jsx(ws,{title:"Teams",description:"Create and manage teams within your brokerage",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Teams"}),e.jsx("p",{className:"text-muted-foreground",children:"Organize your agents into teams with leaders and shared resources."})]}),e.jsxs(q,{onClick:()=>j(!0),children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(bft,{open:b,onOpenChange:j,onCreateTeam:D,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(R=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6",children:[e.jsx(dr,{className:"h-5 w-32 mb-3"}),e.jsx(dr,{className:"h-4 w-48 mb-4"}),e.jsx(dr,{className:"h-8 w-full"})]})},R))}),!d&&c.length===0&&!N&&e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Dr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-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(q,{onClick:()=>j(!0),children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!N&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(R=>e.jsx(wsr,{team:R,onSelect:()=>C(R)},R.id))}),N&&e.jsx(vft,{team:N,brokerageAgents:E||[],onBack:()=>C(null),onUpdate:R=>m.mutateAsync({id:N.id,...R}).then(F=>C(F)),onAddMember:(R,F)=>x.mutateAsync({team_id:N.id,user_id:R,role:F}),onRemoveMember:R=>y.mutateAsync({team_id:N.id,member_id:R}),onUpdateRole:(R,F)=>_.mutateAsync({team_id:N.id,member_id:R,role:F}),onDeleteTeam:()=>f.mutate(N.id),isUpdating:m.isPending,isAddingMember:x.isPending})]})})},Nsr=()=>{const{data:s,isLoading:t}=uv(),{useTeamMembers:r}=aM(),{data:n=[],isLoading:a}=r((s==null?void 0:s.teamId)||"");if(t)return e.jsx(ws,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(dr,{className:"h-8 w-48"}),e.jsx(dr,{className:"h-40 w-full"})]})});if(!s)return e.jsx(ws,{title:"My Team",description:"Your team",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Dr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Team Yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't been assigned to a team. Ask your brokerage manager to add you."})]})})});const i=s.team;return e.jsx(ws,{title:"My Team",description:i.name,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:i.name}),e.jsx(Xe,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(Gf,{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(ta,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(ea,{className:"flex-wrap",children:[e.jsx(rs,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(rs,{value:"contacts",children:[e.jsx(AE,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(rs,{value:"lead-pond",children:[e.jsx(S1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(rs,{value:"shared-assets",children:[e.jsx(Kf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(fs,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(dr,{className:"h-16 w-full"},l))}):n.map(l=>{var o,c,d,u;return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Wn,{className:"h-10 w-10",children:[e.jsx(Xa,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(Kn,{children:(((c=l.profile)==null?void 0:c.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((d=l.profile)==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(u=l.profile)==null?void 0:u.email})]}),l.role==="team_leader"?e.jsxs(Xe,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(Gf,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Xe,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(fs,{value:"contacts",className:"space-y-4",children:e.jsx(VAe,{})}),i.lead_pond_enabled&&e.jsx(fs,{value:"lead-pond",className:"space-y-4",children:e.jsx(HAe,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(fs,{value:"shared-assets",className:"space-y-4",children:e.jsx(yft,{teamId:s.teamId})})]})]})})};function ksr(){const{user:s}=Cs(),t=is(),r=pt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await U.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(j)throw j;return b},enabled:!!s}),n=pt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await U.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(j)throw j;return b},enabled:!!s}),a=pt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await U.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(j)throw j;return b},enabled:!!s}),i=pt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await U.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(j)throw j;return b},enabled:!!s}),l=pt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:j}=await U.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(j)throw j;return b},enabled:!!s}),o=Mt({mutationFn:async()=>{const{data:b,error:j}=await U.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(j)throw j;const N=[{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:C}=await U.from("agent_booking_types").insert(N.map(D=>({...D,user_id:s.id})));if(C)throw C;const A=[1,2,3,4,5].map(D=>({user_id:s.id,day_of_week:D,start_time:"09:00",end_time:"17:00"})),{error:E}=await U.from("agent_availability_slots").insert(A);if(E)throw E;return b},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),he.success("Scheduler set up successfully!")},onError:b=>he.error(b.message)}),c=Mt({mutationFn:async b=>{const{error:j}=await U.from("agent_booking_settings").update(b).eq("user_id",s.id);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),he.success("Settings updated")},onError:b=>he.error(b.message)}),d=Mt({mutationFn:async b=>{const j={...b,user_id:s.id};if(b.id){const{error:N}=await U.from("agent_booking_types").update(j).eq("id",b.id);if(N)throw N}else{const{error:N}=await U.from("agent_booking_types").insert(j);if(N)throw N}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),he.success("Booking type saved")},onError:b=>he.error(b.message)}),u=Mt({mutationFn:async b=>{const{error:j}=await U.from("agent_booking_types").delete().eq("id",b);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),he.success("Booking type deleted")},onError:b=>he.error(b.message)}),m=Mt({mutationFn:async b=>{const j={...b,user_id:s.id};if(b.id){const{error:N}=await U.from("agent_availability_slots").update(j).eq("id",b.id);if(N)throw N}else{const{error:N}=await U.from("agent_availability_slots").insert(j);if(N)throw N}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:b=>he.error(b.message)}),f=Mt({mutationFn:async b=>{const{error:j}=await U.from("agent_availability_slots").delete().eq("id",b);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:b=>he.error(b.message)}),x=Mt({mutationFn:async b=>{const{error:j}=await U.from("agent_blocked_dates").insert({...b,user_id:s.id});if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),he.success("Date blocked")},onError:b=>he.error(b.message)}),y=Mt({mutationFn:async b=>{const{error:j}=await U.from("agent_blocked_dates").delete().eq("id",b);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:b=>he.error(b.message)}),_=Mt({mutationFn:async({id:b,reason:j})=>{const{error:N}=await U.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:j}).eq("id",b);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),he.success("Booking cancelled")},onError:b=>he.error(b.message)});return{settings:r.data,bookingTypes:n.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:r.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:m,deleteAvailability:f,addBlockedDate:x,removeBlockedDate:y,cancelBooking:_}}const qZe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function Ssr({types:s,onSave:t,onDelete:r}){const[n,a]=k.useState(null),[i,l]=k.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1}),l(!0)},c=u=>{a({...u}),l(!0)},d=()=>{n!=null&&n.name&&(t(n),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Booking Types"}),e.jsx(Ur,{children:"The meeting types prospects can book with you"})]}),e.jsxs(q,{onClick:o,size:"sm",children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Pe,{children:s.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No booking types yet. Add one to get started."}):e.jsx("div",{className:"grid gap-3",children:s.map(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:qZe[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(Xe,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.qualification_enabled&&e.jsxs(Xe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(RF,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(jn,{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(q,{variant:"ghost",size:"sm",onClick:()=>c(u),children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>r(u.id),className:"text-destructive hover:text-destructive",children:e.jsx(zr,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsxs(bs,{children:[n!=null&&n.id?"Edit":"New"," Booking Type"]})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Name"}),e.jsx(Ne,{value:n.name||"",onChange:u=>a({...n,name:u.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{value:n.description||"",onChange:u=>a({...n,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(ce,{children:"Duration (minutes)"}),e.jsx(Ne,{type:"number",min:15,max:180,step:15,value:n.duration_minutes||30,onChange:u=>a({...n,duration_minutes:parseInt(u.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:n.color||"#3B82F6",onChange:u=>a({...n,color:u.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(Ne,{value:n.color||"#3B82F6",onChange:u=>a({...n,color:u.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(qZe).map(([u,m])=>e.jsx("button",{onClick:()=>a({...n,icon:u}),className:`w-10 h-10 rounded-lg text-lg flex items-center justify-center border transition-colors ${n.icon===u?"border-primary bg-primary/10":"hover:bg-muted"}`,children:m},u))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Meeting Link Override (optional)"}),e.jsx(Ne,{value:n.meeting_link_override||"",onChange:u=>a({...n,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(ce,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(Rr,{checked:n.qualification_enabled||!1,onCheckedChange:u=>a({...n,qualification_enabled:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Active"}),e.jsx(Rr,{checked:n.is_active??!0,onCheckedChange:u=>a({...n,is_active:u})})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(q,{onClick:d,children:"Save"})]})]})})]})}const VZe=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Csr({slots:s,onSave:t,onDelete:r}){const[n,a]=k.useState(null),[i,l]=k.useState("09:00"),[o,c]=k.useState("17:00"),d=VZe.map((m,f)=>s.filter(x=>x.day_of_week===f)),u=()=>{n!==null&&(t({day_of_week:n,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Ur,{children:"Set your available hours for each day"})]}),e.jsx(Pe,{className:"space-y-2",children:VZe.map((m,f)=>{const x=d[f];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:m})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[x.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):x.map(y=>{var _,b;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(_=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(Ne,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(b=y.end_time)==null?void 0:b.slice(0,5),onBlur:j=>t({id:y.id,end_time:j.target.value})}),e.jsx(Rr,{checked:y.is_active,onCheckedChange:j=>t({id:y.id,is_active:j})}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>r(y.id),children:e.jsx(zr,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},y.id)}),n===f?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:y=>l(y.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(Ne,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:y=>c(y.target.value)}),e.jsx(q,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(f),children:[e.jsx(Ys,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},m)})})]})}const Tsr={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 Esr({bookings:s,onCancel:t}){const r=s.filter(i=>i.status==="confirmed"&&new Date(i.booking_date)>=new Date(new Date().toDateString())),n=s.filter(i=>i.status!=="confirmed"||new Date(i.booking_date){var o,c;return e.jsxs("div",{className:"flex items-start justify-between p-4 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(Xe,{className:`text-xs ${Tsr[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(xu,{className:"h-3.5 w-3.5"}),As(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{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(Ks,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mn,{className:"h-3 w-3"}),i.guest_phone]})]}),i.booking_type&&e.jsx(Xe,{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(q,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(ad,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Upcoming Bookings"}),e.jsxs(Ur,{children:[r.length," upcoming appointment",r.length!==1?"s":""]})]}),e.jsx(Pe,{children:r.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No upcoming bookings"}):e.jsx("div",{className:"space-y-3",children:r.map(i=>a(i,!0))})})]}),n.length>0&&e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Past & Cancelled"})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-3",children:n.slice(0,20).map(i=>a(i))})})]})]})}function Asr({blockedDates:s,onAdd:t,onRemove:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(""),d=()=>{i&&(t({blocked_date:i,reason:o||void 0}),a(!1),l(""),c(""))};return e.jsxs(ke,{children:[e.jsxs(Pt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(yF,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Ur,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(Pe,{children:[n&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(Ne,{type:"date",value:i,onChange:u=>l(u.target.value),className:"w-40"}),e.jsx(Ne,{placeholder:"Reason (optional)",value:o,onChange:u=>c(u.target.value),className:"flex-1"}),e.jsx(q,{size:"sm",onClick:d,children:"Add"}),e.jsx(q,{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:As(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:()=>r(u.id),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx($r,{className:"h-3.5 w-3.5"})})]},u.id))})]})]})}function Msr(){const{settings:s,bookingTypes:t,availability:r,blockedDates:n,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:u,deleteAvailability:m,addBlockedDate:f,removeBlockedDate:x,cancelBooking:y}=ksr(),[_,b]=k.useState("");k.useState(15),_||s!=null&&s.meeting_link;const j=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(ws,{children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):s?e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(xu,{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(q,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(j),he.success("Booking link copied!")},children:[e.jsx(si,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(q,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(un,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(Rr,{id:"scheduler-active",checked:s.is_active,onCheckedChange:N=>o.mutate({is_active:N})})]})]})]}),e.jsxs(ta,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"types",children:"Booking Types"}),e.jsx(rs,{value:"availability",children:"Availability"}),e.jsx(rs,{value:"settings",children:"Settings"}),e.jsxs(rs,{value:"bookings",children:["Bookings",a.filter(N=>N.status==="confirmed").length>0&&e.jsx(Xe,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(N=>N.status==="confirmed").length})]})]}),e.jsx(fs,{value:"types",children:e.jsx(Ssr,{types:t,onSave:N=>c.mutate(N),onDelete:N=>d.mutate(N)})}),e.jsx(fs,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Csr,{slots:r,onSave:N=>u.mutate(N),onDelete:N=>m.mutate(N)}),e.jsx(Asr,{blockedDates:n,onAdd:N=>f.mutate(N),onRemove:N=>x.mutate(N)})]})}),e.jsx(fs,{value:"settings",children:e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(WF,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(Ur,{children:"Configure your booking page defaults"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>{j&&(navigator.clipboard.writeText(j),he.success("Copied!"))},children:e.jsx(si,{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(ce,{htmlFor:"meeting-link",children:[e.jsx(Ul,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(Ne,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:N=>o.mutate({meeting_link:N.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(ce,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:N=>o.mutate({buffer_minutes:parseInt(N.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:N=>o.mutate({min_notice_hours:parseInt(N.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ce,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:N=>o.mutate({max_advance_days:parseInt(N.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]})]})]})}),e.jsx(fs,{value:"bookings",children:e.jsx(Esr,{bookings:a,onCancel:N=>y.mutate({id:N})})})]})]})}):e.jsx(ws,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-8 space-y-8",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center",children:e.jsx(xu,{className:"h-8 w-8 text-primary"})}),e.jsx("h1",{className:"text-3xl font-bold",children:"LevelUp Scheduler"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-md mx-auto",children:"Your own booking page — built for real estate. Prospects book with you, get auto-added to your CRM, and you never miss a lead."})]}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{icon:"🏠",title:"Listing Consultation",desc:"60 min"},{icon:"🔍",title:"Buyer Consultation",desc:"45 min"},{icon:"💰",title:"Home Valuation",desc:"30 min"},{icon:"☕",title:"General Meeting",desc:"30 min"}].map(N=>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:N.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.desc})]})]},N.title))}),e.jsx(cl,{}),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(q,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}const HZe=[{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 Isr(){const{user:s}=Cs(),t=xa(),{toast:r}=Ba(),n=qr(),a=is(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState(null),[m,f]=k.useState({title:"",description:"",page_type:"lead_capture"}),{data:x=[],isLoading:y}=pt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:N,error:C}=await U.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(C)throw C;return N},enabled:!!t}),_=Mt({mutationFn:async()=>{const N=m.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:C}=await U.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),A=m.page_type==="just_listed"||m.page_type==="just_sold",{data:E,error:D}=await U.from("landing_pages").insert({user_id:t,title:m.title,description:m.description||null,page_type:m.page_type,slug:N,hero_headline:A?m.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":m.page_type==="lead_magnet"?"📥 Free Download":m.title,agent_name:(C==null?void 0:C.name)||null,agent_phone:(C==null?void 0:C.phone)||null,agent_email:(C==null?void 0:C.email)||s.email||null,agent_photo_url:(C==null?void 0:C.avatar_url)||null,property_status:A?m.page_type.replace("just_",""):null}).select().single();if(D)throw D;const R=Psr(m.page_type);if(R.length>0){const{error:F}=await U.from("landing_page_fields").insert(R.map((O,B)=>({...O,page_id:E.id,sort_order:B})));if(F)throw F}return E},onSuccess:N=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),f({title:"",description:"",page_type:"lead_capture"}),r({title:"Landing page created!"}),n(`/mission-control/landing-pages/${N.id}`)},onError:N=>r({title:"Error",description:N.message,variant:"destructive"})}),b=Mt({mutationFn:async N=>{const{error:C}=await U.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",N);if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),r({title:"Landing page deleted"})}}),j=N=>`https://pages.relevelup.com/${N}`;return e.jsxs(ws,{title:"Landing Pages",children:[e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Pages"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Create branded lead capture pages for events, consultations, and more"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(q,{variant:"outline",onClick:()=>n("/mission-control/landing-pages/defaults"),children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs(q,{onClick:()=>l(!0),children:[e.jsx(Ys,{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"})}):x.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(En,{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(q,{onClick:()=>l(!0),children:[e.jsx(Ys,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:x.map(N=>{var C;return e.jsx(ke,{className:"hover:shadow-md transition-shadow",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>n(`/mission-control/landing-pages/${N.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:N.title}),e.jsx(Xe,{variant:N.is_published?"default":"secondary",className:"text-[10px]",children:N.is_published?"Published":"Draft"}),e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:((C=HZe.find(A=>A.id===N.page_type))==null?void 0:C.label)||N.page_type})]}),N.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:N.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(Nn,{className:"h-3 w-3"})," ",N.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(En,{className:"h-3 w-3"})," ",N.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[N.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(q,{size:"sm",variant:"outline",onClick:()=>u(j(N.slug)),children:e.jsx(S_,{className:"h-3.5 w-3.5"})}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(j(N.slug)),r({title:"Link copied!"})},children:e.jsx(si,{className:"h-3.5 w-3.5"})}),e.jsx(q,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:j(N.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(un,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx(q,{size:"sm",variant:"ghost",children:e.jsx(Fy,{className:"h-4 w-4"})})}),e.jsxs(Sd,{align:"end",children:[e.jsxs(ti,{onClick:()=>n(`/mission-control/landing-pages/${N.id}`),children:[e.jsx(Ua,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(ti,{onClick:()=>c(N.id),className:"text-destructive",children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},N.id)})})]}),e.jsx(vs,{open:i,onOpenChange:l,children:e.jsxs(ys,{children:[e.jsx(_s,{children:e.jsx(bs,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Page Title"}),e.jsx(Ne,{value:m.title,onChange:N=>f(C=>({...C,title:N.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Description (optional)"}),e.jsx(pr,{value:m.description,onChange:N=>f(C=>({...C,description:N.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Page Template"}),e.jsxs(Ds,{value:m.page_type,onValueChange:N=>f(C=>({...C,page_type:N})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:HZe.map(N=>e.jsx(lt,{value:N.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:N.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:N.description})]})},N.id))})]})]})]}),e.jsxs(fn,{children:[e.jsx(q,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(q,{onClick:()=>_.mutate(),disabled:!m.title.trim()||_.isPending,children:_.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(el,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs($o,{children:[e.jsxs(Uo,{children:[e.jsx(Vo,{children:"Delete Landing Page?"}),e.jsx(Ho,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(qo,{children:[e.jsx(Go,{children:"Cancel"}),e.jsx(Oo,{onClick:()=>o&&b.mutate(o),children:"Delete"})]})]})}),e.jsx(vs,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(ys,{className:"max-w-sm",children:[e.jsx(_s,{children:e.jsx(bs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(d$,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),r({title:"URL copied!"}))},children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function Psr(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 Lsr(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function Dsr({pageId:s}){const{data:t=[],isLoading:r}=pt({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await U.from("landing_page_events").select("event_type, session_id, utm_source, utm_medium, utm_campaign, referrer, device, created_at").eq("page_id",s).gte("created_at",l).order("created_at",{ascending:!1}).limit(1e3);if(c)throw c;return o||[]}}),{data:n=[]}=pt({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await U.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=k.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,m=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 b=y.device||"unknown";m.set(b,(m.get(b)||0)+1)}const f=[];for(let y=13;y>=0;y--){const _=new Date;_.setHours(0,0,0,0),_.setDate(_.getDate()-y);const b=new Date(_);b.setDate(_.getDate()+1);const j=_.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),N=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:n.length,conversion:Lsr(n.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:[...m.entries()].sort((y,_)=>_[1]-y[1]),days:f,maxBar:x}},[t,n]);if(r)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(dr,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:Nn},{label:"Unique visitors",value:a.sessions,icon:Dr},{label:"Submissions",value:a.submissions,icon:hn},{label:"Conversion rate",value:a.conversion,icon:Wo}];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(ke,{children:e.jsxs(Pe,{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(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Last 14 days"})}),e.jsxs(Pe,{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(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Bc,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(Pe,{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(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Top referrers"})}),e.jsx(Pe,{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(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Devices"})}),e.jsx(Pe,{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 Rsr=[{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 Osr=0;const GZe=()=>`f_${Date.now()}_${++Osr}`;function Fsr({field:s,index:t,updateField:r,removeField:n}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=w0e({id:s.clientId}),u={transform:zS.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(ke,{ref:l,style:u,children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{type:"button",...a,...i,className:"mt-1 p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted cursor-grab active:cursor-grabbing touch-none","aria-label":"Drag to reorder",children:e.jsx(Vu,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Field Type"}),e.jsxs(Ds,{value:s.field_type,onValueChange:m=>r(t,{field_type:m}),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsx(Ls,{children:Rsr.map(m=>e.jsx(lt,{value:m.value,children:m.label},m.value))})]})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Label"}),e.jsx(Ne,{value:s.label,onChange:m=>r(t,{label:m.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Placeholder"}),e.jsx(Ne,{value:s.placeholder||"",onChange:m=>r(t,{placeholder:m.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(ce,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(Ne,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:m=>r(t,{options:JSON.stringify(m.target.value.split(",").map(f=>f.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{checked:s.is_required,onCheckedChange:m=>r(t,{is_required:m})}),e.jsx(ce,{className:"text-xs",children:"Required"})]})]}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>n(t),children:e.jsx(zr,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function zsr(){const{pageId:s}=xo(),t=qr(),{user:r}=Cs(),n=xa(),{toast:a}=Ba(),i=is(),[l,o]=k.useState(null),[c,d]=k.useState(!1),{data:u,isLoading:m}=pt({queryKey:["landing-page",s],queryFn:async()=>{const{data:de,error:fe}=await U.from("landing_pages").select("*").eq("id",s).single();if(fe)throw fe;return de},enabled:!!s}),{data:f=[],isLoading:x}=pt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:de,error:fe}=await U.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(fe)throw fe;return de},enabled:!!s}),{data:y=[]}=pt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:de,error:fe}=await U.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(fe)throw fe;return de},enabled:!!s}),{data:_=[]}=pt({queryKey:["my-listings-for-pages",n],queryFn:async()=>{const{data:de,error:fe}=await U.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",n).order("created_at",{ascending:!1});if(fe)throw fe;return de},enabled:!!r&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:b=[]}=pt({queryKey:["drips-for-landing",n],queryFn:async()=>{const{data:de}=await U.from("drip_campaigns").select("id, name").eq("owner_user_id",n).eq("is_active",!0).order("name");return de||[]},enabled:!!n}),{data:j}=pt({queryKey:["agent-landing-defaults",n],queryFn:async()=>{const{data:de}=await U.from("agent_landing_page_defaults").select("*").eq("user_id",n).maybeSingle();return de},enabled:!!n}),[N,C]=k.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"],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]=k.useState([]);k.useEffect(()=>{var de,fe,je,xe,Ee,Me,Oe,Ie,ze;u&&C({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:((de=u.settings)==null?void 0:de.redirect_url)||"",settings_auto_responder_subject:((fe=u.settings)==null?void 0:fe.auto_responder_subject)||"",settings_auto_responder_body:((je=u.settings)==null?void 0:je.auto_responder_body)||"",settings_drip_campaign_id:((xe=u.settings)==null?void 0:xe.drip_campaign_id)||null,settings_disable_auto_responder:!!((Ee=u.settings)!=null&&Ee.disable_auto_responder),settings_disable_drip:!!((Me=u.settings)!=null&&Me.disable_drip),settings_event_starts_at:((Oe=u.settings)==null?void 0:Oe.event_starts_at)||"",settings_event_location_name:((Ie=u.settings)==null?void 0:Ie.event_location_name)||"",settings_event_address:((ze=u.settings)==null?void 0:ze.event_address)||""})},[u]),k.useEffect(()=>{f.length>0&&E(f.map(de=>({id:de.id,clientId:de.id||GZe(),field_type:de.field_type,label:de.label,placeholder:de.placeholder,is_required:de.is_required,options:typeof de.options=="string"?de.options:de.options?JSON.stringify(de.options):null,sort_order:de.sort_order})))},[f]);const D=Mt({mutationFn:async()=>{const{error:de}=await U.from("landing_pages").update({title:N.title,hero_headline:N.hero_headline,hero_subtext:N.hero_subtext||null,hero_image_url:N.hero_image_url,logo_url:N.logo_url,primary_color:N.primary_color,accent_color:N.accent_color,agent_name:N.agent_name||null,agent_phone:N.agent_phone||null,agent_email:N.agent_email||null,agent_photo_url:N.agent_photo_url,success_message:N.success_message,is_published:N.is_published,description:N.description||null,lead_magnet_file_url:N.lead_magnet_file_url,lead_magnet_file_name:N.lead_magnet_file_name,lead_magnet_external_url:N.lead_magnet_external_url,listing_id:N.listing_id,property_address:N.property_address||null,property_price:N.property_price||null,property_beds:N.property_beds||null,property_baths:N.property_baths||null,property_sqft:N.property_sqft||null,property_description:N.property_description||null,property_photos:N.property_photos,property_status:N.property_status,theme_style:N.theme_style,eyebrow:N.eyebrow||null,headline_accent:N.headline_accent||null,heading_font:N.heading_font,trust_pills:N.trust_pills,settings:{...(u==null?void 0:u.settings)||{},redirect_url:N.settings_redirect_url||null,auto_responder_subject:N.settings_auto_responder_subject||null,auto_responder_body:N.settings_auto_responder_body||null,drip_campaign_id:N.settings_drip_campaign_id||null,disable_auto_responder:!!N.settings_disable_auto_responder,disable_drip:!!N.settings_disable_drip,event_starts_at:N.settings_event_starts_at||null,event_location_name:N.settings_event_location_name||null,event_address:N.settings_event_address||null},updated_at:new Date().toISOString()}).eq("id",s);if(de)throw de;if(await U.from("landing_page_fields").delete().eq("page_id",s),A.length>0){const{error:fe}=await U.from("landing_page_fields").insert(A.map((je,xe)=>({page_id:s,field_type:je.field_type,label:je.label,placeholder:je.placeholder||null,is_required:je.is_required,options:je.options?JSON.parse(je.options):null,sort_order:xe})));if(fe)throw fe}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:de=>a({title:"Error",description:de.message,variant:"destructive"})}),R=async(de,fe)=>{const je=de.name.split(".").pop(),xe=`landing-pages/${r.id}/${fe}-${Date.now()}.${je}`,{error:Ee}=await U.storage.from("recruit-landing").upload(xe,de);if(Ee)throw Ee;const{data:{publicUrl:Me}}=U.storage.from("recruit-landing").getPublicUrl(xe);return Me},F=async(de,fe)=>{var xe;const je=(xe=de.target.files)==null?void 0:xe[0];if(je){o(fe);try{const Ee=await R(je,fe);C(Me=>({...Me,[fe]:Ee})),a({title:"Image uploaded!"})}catch(Ee){a({title:"Upload failed",description:Ee.message,variant:"destructive"})}finally{o(null)}}},O=async de=>{var je;const fe=(je=de.target.files)==null?void 0:je[0];if(fe){o("lead_magnet");try{const xe=await R(fe,"lead-magnet");C(Ee=>({...Ee,lead_magnet_file_url:xe,lead_magnet_file_name:fe.name})),a({title:"File uploaded!"})}catch(xe){a({title:"Upload failed",description:xe.message,variant:"destructive"})}finally{o(null)}}},B=async de=>{const fe=de.target.files;if(!(!fe||fe.length===0)){o("property_photos");try{const je=[];for(const xe of Array.from(fe)){const Ee=await R(xe,"property-photo");je.push(Ee)}C(xe=>({...xe,property_photos:[...xe.property_photos,...je]})),a({title:`${je.length} photo(s) uploaded!`})}catch(je){a({title:"Upload failed",description:je.message,variant:"destructive"})}finally{o(null)}}},K=async de=>{const fe=_.find(xe=>xe.id===de);if(!fe)return;const{data:je}=await U.from("listing_photos").select("photo_url").eq("listing_id",de).order("sort_order");C(xe=>({...xe,listing_id:de,property_address:fe.property_address||`${fe.city}, ${fe.state}`,property_price:fe.price?`$${fe.price.toLocaleString()}`:"",property_beds:fe.bedrooms?String(fe.bedrooms):"",property_baths:fe.bathrooms?String(fe.bathrooms):"",property_sqft:fe.square_footage?fe.square_footage.toLocaleString():"",property_description:fe.description||"",property_photos:(je==null?void 0:je.map(Ee=>Ee.photo_url))||xe.property_photos})),a({title:"Listing data imported!"})},Z=()=>{E(de=>[...de,{clientId:GZe(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:de.length}])},Q=(de,fe)=>{E(je=>je.map((xe,Ee)=>Ee===de?{...xe,...fe}:xe))},W=de=>{E(fe=>fe.filter((je,xe)=>xe!==de))},te=m0e(NL(B8,{activationConstraint:{distance:6}}),NL(x0e,{coordinateGetter:qft})),ne=de=>{const{active:fe,over:je}=de;!je||fe.id===je.id||E(xe=>{const Ee=xe.findIndex(Oe=>Oe.clientId===fe.id),Me=xe.findIndex(Oe=>Oe.clientId===je.id);return Ee<0||Me<0?xe:b0e(xe,Ee,Me).map((Oe,Ie)=>({...Oe,sort_order:Ie}))})},ae=u?`https://pages.relevelup.com/${u.slug}`:"",ue=(u==null?void 0:u.page_type)==="lead_magnet",me=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return m||x?e.jsx(ws,{title:"Loading...",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):u?e.jsxs(ws,{title:N.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(q,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(Aa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:N.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Xe,{variant:N.is_published?"default":"secondary",className:"text-[10px]",children:N.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Nn,{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(Dr,{className:"h-3 w-3"})," ",y.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[N.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(q,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(S_,{className:"h-3.5 w-3.5"})}),e.jsxs(q,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(ae),a({title:"Link copied!"})},children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx(q,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ae,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(q,{onClick:()=>D.mutate(),disabled:D.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),D.isPending?"Saving...":"Save"]})]})]}),e.jsxs(ta,{defaultValue:"design",children:[e.jsxs(ea,{children:[e.jsx(rs,{value:"design",children:"Design"}),ue&&e.jsx(rs,{value:"lead_magnet",children:"Lead Magnet"}),me&&e.jsx(rs,{value:"property",children:"Property Details"}),e.jsxs(rs,{value:"fields",children:["Form Fields (",A.length,")"]}),e.jsxs(rs,{value:"submissions",children:["Submissions (",y.length,")"]}),e.jsx(rs,{value:"automation",children:"Automation"}),e.jsx(rs,{value:"analytics",children:"Analytics"}),e.jsx(rs,{value:"settings",children:"Settings"})]}),e.jsxs(fs,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Page Details"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Page Title (internal)"}),e.jsx(Ne,{value:N.title,onChange:de=>C(fe=>({...fe,title:de.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Description (internal)"}),e.jsx(Ne,{value:N.description,onChange:de=>C(fe=>({...fe,description:de.target.value}))})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(Xe,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Theme Style"}),e.jsxs(Ds,{value:N.theme_style,onValueChange:de=>C(fe=>({...fe,theme_style:de})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(lt,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Headline Font"}),e.jsxs(Ds,{value:N.heading_font,onValueChange:de=>C(fe=>({...fe,heading_font:de})),children:[e.jsx(Ps,{children:e.jsx(Fs,{})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(lt,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(lt,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(lt,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(Ne,{value:N.trust_pills.join(", "),onChange:de=>C(fe=>({...fe,trust_pills:de.target.value.split(",").map(je=>je.trim()).filter(Boolean)})),placeholder:"No obligation, 100% free, 60 seconds or less"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Premium theme uses a cinematic full-screen hero, italic accent word, glass-effect form, and trust pills — magazine-style."})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Pe,{className:"space-y-4",children:[N.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(ce,{children:"Eyebrow (small label above headline)"}),e.jsx(Ne,{value:N.eyebrow,onChange:de=>C(fe=>({...fe,eyebrow:de.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Headline"}),e.jsx(Ne,{value:N.hero_headline,onChange:de=>C(fe=>({...fe,hero_headline:de.target.value})),placeholder:"What Is Your Home"})]}),N.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(ce,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(Ne,{value:N.headline_accent,onChange:de=>C(fe=>({...fe,headline_accent:de.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Subtext"}),e.jsx(pr,{value:N.hero_subtext,onChange:de=>C(fe=>({...fe,hero_subtext:de.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(ce,{children:["Background Image ",N.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:[N.hero_image_url&&e.jsx("img",{src:N.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(q,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(ka,{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:de=>F(de,"hero_image_url")})]}),N.hero_image_url&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>C(de=>({...de,hero_image_url:null})),children:e.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Branding"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[N.logo_url&&e.jsx("img",{src:N.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(q,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:de=>F(de,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[N.agent_photo_url&&e.jsx("img",{src:N.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(q,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:de=>F(de,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:N.primary_color,onChange:de=>C(fe=>({...fe,primary_color:de.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Ne,{value:N.primary_color,onChange:de=>C(fe=>({...fe,primary_color:de.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:N.accent_color,onChange:de=>C(fe=>({...fe,accent_color:de.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Ne,{value:N.accent_color,onChange:de=>C(fe=>({...fe,accent_color:de.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Pe,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Name"}),e.jsx(Ne,{value:N.agent_name,onChange:de=>C(fe=>({...fe,agent_name:de.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Phone"}),e.jsx(Ne,{value:N.agent_phone,onChange:de=>C(fe=>({...fe,agent_phone:de.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Email"}),e.jsx(Ne,{value:N.agent_email,onChange:de=>C(fe=>({...fe,agent_email:de.target.value}))})]})]})})]})]}),ue&&e.jsx(fs,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(li,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a file or provide an external URL. Visitors will receive the download link after submitting the form."}),e.jsxs("div",{children:[e.jsx(ce,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[N.lead_magnet_file_name&&e.jsxs(Xe,{variant:"outline",className:"gap-1",children:[e.jsx(li,{className:"h-3 w-3"})," ",N.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(q,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:O})]}),N.lead_magnet_file_url&&e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>C(de=>({...de,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(zr,{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(ce,{className:"flex items-center gap-1",children:[e.jsx(Ul,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(Ne,{value:N.lead_magnet_external_url||"",onChange:de=>C(fe=>({...fe,lead_magnet_external_url:de.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"})]})]})]})}),me&&e.jsxs(fs,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Pn,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(Ds,{value:N.listing_id||"",onValueChange:de=>K(de),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Select a listing to import..."})}),e.jsx(Ls,{children:_.map(de=>{var fe;return e.jsxs(lt,{value:de.id,children:[de.property_address||`${de.city}, ${de.state}`," — $",(fe=de.price)==null?void 0:fe.toLocaleString()]},de.id)})})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Property Information"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Property Address"}),e.jsx(Ne,{value:N.property_address,onChange:de=>C(fe=>({...fe,property_address:de.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(ce,{children:"Price"}),e.jsx(Ne,{value:N.property_price,onChange:de=>C(fe=>({...fe,property_price:de.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Beds"}),e.jsx(Ne,{value:N.property_beds,onChange:de=>C(fe=>({...fe,property_beds:de.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Baths"}),e.jsx(Ne,{value:N.property_baths,onChange:de=>C(fe=>({...fe,property_baths:de.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Sq Ft"}),e.jsx(Ne,{value:N.property_sqft,onChange:de=>C(fe=>({...fe,property_sqft:de.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(ce,{children:"Description"}),e.jsx(pr,{value:N.property_description,onChange:de=>C(fe=>({...fe,property_description:de.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Property Photos"})}),e.jsxs(Pe,{className:"space-y-4",children:[N.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:N.property_photos.map((de,fe)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:de,alt:`Property ${fe+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx(q,{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(je=>({...je,property_photos:je.property_photos.filter((xe,Ee)=>Ee!==fe)})),children:e.jsx(zr,{className:"h-3 w-3"})})]},fe))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(q,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(ka,{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:B})]})]})]})]}),e.jsxs(fs,{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(q,{size:"sm",onClick:Z,children:[e.jsx(Ys,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),A.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(v0e,{sensors:te,collisionDetection:f0e,onDragEnd:ne,children:e.jsx(_0e,{items:A.map(de=>de.clientId),strategy:Ogs,children:e.jsx("div",{className:"space-y-3",children:A.map((de,fe)=>e.jsx(Fsr,{field:de,index:fe,updateField:Q,removeField:W},de.clientId))})})})]}),e.jsx(fs,{value:"submissions",className:"mt-4",children:y.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:y.map(de=>e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:de.contact_name||"Anonymous"}),de.synced_to_crm&&e.jsx(Xe,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[de.contact_email&&e.jsx("span",{className:"mr-3",children:de.contact_email}),de.contact_phone&&e.jsx("span",{children:de.contact_phone})]}),de.answers&&typeof de.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(de.answers).map(([fe,je])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[fe,":"]})," ",e.jsx("span",{children:String(je)})]},fe))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(de.created_at).toLocaleDateString()})]})})},de.id))})}),e.jsxs(fs,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{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(Pe,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(ce,{children:"Starts at"}),e.jsx(Ne,{type:"datetime-local",value:N.settings_event_starts_at,onChange:de=>C(fe=>({...fe,settings_event_starts_at:de.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Venue / location name"}),e.jsx(Ne,{placeholder:"e.g. The Grand Hotel",value:N.settings_event_location_name,onChange:de=>C(fe=>({...fe,settings_event_location_name:de.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{children:"Address (for map link)"}),e.jsx(Ne,{placeholder:"123 Main St, City, ST",value:N.settings_event_address,onChange:de=>C(fe=>({...fe,settings_event_address:de.target.value}))})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{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(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Send auto-reply for this page"}),e.jsx(Rr,{checked:!N.settings_disable_auto_responder,onCheckedChange:de=>C(fe=>({...fe,settings_disable_auto_responder:!de}))})]}),!N.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Subject (override)"}),e.jsx(Ne,{value:N.settings_auto_responder_subject,onChange:de=>C(fe=>({...fe,settings_auto_responder_subject:de.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(ce,{children:"Body (override)"}),e.jsx(pr,{rows:8,value:N.settings_auto_responder_body,onChange:de=>C(fe=>({...fe,settings_auto_responder_body:de.target.value})),placeholder:(j==null?void 0:j.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{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(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ce,{children:"Enroll new leads in a drip"}),e.jsx(Rr,{checked:!N.settings_disable_drip,onCheckedChange:de=>C(fe=>({...fe,settings_disable_drip:!de}))})]}),!N.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(ce,{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:N.settings_drip_campaign_id||"",onChange:de=>C(fe=>({...fe,settings_drip_campaign_id:de.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),b.map(de=>e.jsx("option",{value:de.id,children:de.name},de.id))]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(Pe,{children:[e.jsx(Ne,{value:N.settings_redirect_url,onChange:de=>C(fe=>({...fe,settings_redirect_url:de.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(fs,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(Dsr,{pageId:s})}),e.jsxs(fs,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Publishing"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(Rr,{checked:N.is_published,onCheckedChange:de=>C(fe=>({...fe,is_published:de}))})]}),N.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:ae})]})]})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{className:"text-base",children:"Thank You Message"})}),e.jsx(Pe,{children:e.jsx(pr,{value:N.success_message,onChange:de=>C(fe=>({...fe,success_message:de.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{className:"max-w-sm",children:[e.jsx(_s,{children:e.jsx(bs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(d$,{value:ae,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:ae})]})]})})]}):e.jsx(ws,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),e.jsx(q,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}const Bsr={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},$sr=`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 Usr(){const s=xa(),{toast:t}=Ba(),r=qr(),n=is(),[a,i]=k.useState(Bsr),{data:l}=pt({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await U.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=pt({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await U.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});k.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=Mt({mutationFn:async()=>{const{error:d}=await U.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{n.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(ws,{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(q,{variant:"ghost",size:"sm",onClick:()=>r("/mission-control/landing-pages"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," Back to pages"]}),e.jsxs(q,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(Ml,{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(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Instant auto-reply to the lead"}),e.jsxs(Ur,{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(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Subject"}),e.jsx(Ne,{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(ce,{children:"Message body"}),e.jsx(pr,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:$sr}),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(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Default Smart Drip"}),e.jsx(Ur,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(Pe,{children:e.jsxs(Ds,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(Ps,{children:e.jsx(Fs,{placeholder:"Pick a drip…"})}),e.jsxs(Ls,{children:[e.jsx(lt,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(lt,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(ke,{children:[e.jsx(Pt,{children:e.jsx(Dt,{children:"Defaults for every page"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ce,{children:"Default booking / calendar link"}),e.jsx(Ne,{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(ce,{children:"Default redirect after submit (optional)"}),e.jsx(Ne,{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(ce,{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(Rr,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Pt,{children:[e.jsx(Dt,{children:"Text me when a lead submits"}),e.jsx(Ur,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(ce,{className:"text-base",children:"SMS me new leads"}),e.jsx(Rr,{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(ce,{children:"Phone number for alerts"}),e.jsx(Ne,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function qsr(){return pt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await U.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function Jye(){const{user:s}=Cs();return pt({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await U.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(r)throw r;return t||[]},enabled:!!(s!=null&&s.id)})}function eve(){const{user:s}=Cs(),t=is();return Mt({mutationFn:async({app_slug:r,enabled:n})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await U.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:r,enabled:n},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),he.success(n.enabled?"App installed":"App turned off")},onError:r=>he.error(r.message||"Failed to update app")})}const Vsr={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"}},Hsr={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 Gsr(){const s=qr(),{data:t=[],isLoading:r}=qsr(),{data:n=[]}=Jye(),{hasLeadSite:a,siteUrl:i,isLoading:l}=hf(),o=eve(),[c,d]=k.useState(!1),u=f=>{var x;return((x=n.find(y=>y.app_slug===f))==null?void 0:x.enabled)??!1},m=f=>n.some(x=>x.app_slug===f);return e.jsxs(ws,{title:"Website Apps",description:"Conversion-boosting widgets for your website",children:[e.jsxs("div",{className:"max-w-6xl mx-auto p-6 lg:p-8 space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl bg-gradient-to-br from-indigo-600 via-fuchsia-600 to-rose-500 p-8 lg:p-10 shadow-xl",children:[e.jsx("div",{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-white/10 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-16 w-80 h-80 rounded-full bg-fuchsia-300/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/15 backdrop-blur-sm text-white text-xs font-semibold uppercase tracking-wider mb-4",children:[e.jsx(zh,{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(Ir,{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(q,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(Ff,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(ke,{className:`p-5 border-2 ${a?"border-emerald-200 bg-emerald-50/50":"border-dashed border-muted"}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 ${a?"bg-emerald-500 text-white":"bg-muted text-muted-foreground"}`,children:e.jsx(Ql,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 1 — The Local Move Websites"}),a&&e.jsxs(Xe,{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(un,{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(un,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(ke,{className:"p-5 border-2 border-indigo-200 bg-indigo-50/40",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gradient-to-br from-indigo-500 to-fuchsia-600 text-white flex items-center justify-center flex-shrink-0",children:e.jsx(Rj,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 2 — Your existing website"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Already have a site (Wix, Squarespace, WordPress, custom)? Paste a one-line snippet and the widget appears anywhere."}),e.jsx("p",{className:"text-[11px] text-indigo-700 mt-2 font-medium",children:'Open any app below → "Install on my website" tab to copy your code.'})]})]})})]}),r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading apps..."}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(f=>{const x=_xe[f.icon||"Sparkles"]||Ir,y=u(f.slug),_=m(f.slug),b=f.status==="coming_soon",j=Vsr[f.slug]||Hsr;return e.jsxs(ke,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${j.ring} hover:ring-2 transition-all hover:shadow-xl ${b?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${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(x,{className:"w-7 h-7"})}),b?e.jsx(Xe,{variant:"secondary",children:"Coming soon"}):y?e.jsxs(Xe,{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(Xe,{variant:"outline",children:"Paused"}):e.jsx(Xe,{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:f.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:f.description})]}),!b&&e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rr,{checked:y,onCheckedChange:N=>o.mutate({app_slug:f.slug,enabled:N})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:y?"On":"Off"})]}),e.jsxs(q,{size:"sm",className:`bg-gradient-to-r ${j.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${f.slug}`),children:[e.jsx(Bo,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(ci,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},f.id)})})]}),e.jsx(vs,{open:c,onOpenChange:d,children:e.jsxs(ys,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(_s,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(bs,{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 Jje={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 Wsr(){const{user:s}=Cs();return pt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return Jje;const{data:t,error:r}=await U.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t?{...Jje,...t}:Jje},enabled:!!(s!=null&&s.id)})}function Ksr(){const{user:s}=Cs(),t=is();return Mt({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:n}=await U.from("video_greeter_configs").upsert({user_id:s.id,...r},{onConflict:"user_id"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),he.success("Saved")},onError:r=>he.error(r.message||"Failed to save")})}function Ysr({label:s,value:t,onChange:r,thumbnailUrl:n,placeholder:a="https://...",hint:i}){const l=k.useRef(null),[o,c]=k.useState(!1),d=async u=>{var f;const m=(f=u.target.files)==null?void 0:f[0];if(m){if(!m.type.startsWith("video/")){he.error("Please select a video file");return}if(m.size>50*1024*1024){he.error("Video must be under 50MB");return}c(!0);try{const x=m.name.split(".").pop()||"mp4",y=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${x}`,{error:_}=await U.storage.from("agent-uploads").upload(y,m,{upsert:!0});if(_)throw _;const{data:{publicUrl:b}}=U.storage.from("agent-uploads").getPublicUrl(y);r(b),he.success("Video uploaded!")}catch(x){he.error(x.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(ce,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:t,onChange:u=>r(u.target.value),placeholder:a,className:"flex-1"}),e.jsxs(q,{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(ls,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ka,{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})/),m=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 ${m?"max-w-xl aspect-video":"max-w-sm aspect-[9/16]"}`,children:m?e.jsx("iframe",{src:`https://www.youtube.com/embed/${m}`,className:"w-full h-full",title:"Video preview",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0}):RI(t)?e.jsx(l3e,{sourceUrl:t,thumbnailUrl:n,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-contain"}):e.jsx("video",{src:t,className:"w-full h-full object-contain",controls:!0,muted:!0,preload:"metadata"})}),e.jsx(q,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>r(""),children:e.jsx($r,{className:"h-3 w-3"})})]})})()]})}const Zsr=[{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 Xsr({onVideoReady:s}){const[t,r]=k.useState(!1),[n,a]=k.useState("script"),[i,l]=k.useState(""),[o,c]=k.useState(!0),[d,u]=k.useState(!1),[m,f]=k.useState(0),[x,y]=k.useState(0),_=V2(),b=()=>{a("script"),l(""),f(0),y(0),c(!0)},j=C=>{!C&&(n==="uploading"||n==="processing")||(r(C),C||b())},N=k.useCallback(async(C,A)=>{a("uploading");try{const E="Video Greeter",{videoId:D,libraryId:R}=await dM(E),{uploadUrl:F,apiKey:O}=await uM(D),B=new XMLHttpRequest;B.upload.onprogress=me=>{me.lengthComputable&&f(me.loaded/me.total*100)},await new Promise((me,de)=>{B.onload=()=>B.status>=200&&B.status<300?me():de(new Error("Upload failed")),B.onerror=()=>de(new Error("Upload failed")),B.open("PUT",F),B.setRequestHeader("AccessKey",O),B.send(C)}),a("processing");let K=0;const Z=Date.now(),Q=9e4,W=`https://iframe.mediadelivery.net/embed/${R}/${D}`,te=`https://iframe.mediadelivery.net/play/${R}/${D}`;for(;K<4;){if(await new Promise(de=>setTimeout(de,3e3)),Date.now()-Z>Q){const de=C.size/1048576,fe=await _.mutateAsync({bunny_video_id:D,playback_url:te,file_size_mb:de,title:E,status:"processing",touch_type:"video"});s({videoId:(fe==null?void 0:fe.id)||D,playbackUrl:W,thumbnailUrl:null}),he.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{r(!1),b()},1500);return}const me=await W_(D);if(K=me.status,y(me.encodeProgress||0),K===5||K===6)throw new Error("Video processing failed")}const ne=await W_(D),ae=(ne.storageSize||C.size)/(1024*1024),ue=await _.mutateAsync({bunny_video_id:D,playback_url:ne.directPlayUrl||W,thumbnail_url:ne.thumbnailUrl,preview_url:ne.previewUrl||null,duration_seconds:ne.length||A,file_size_mb:ae,title:E,status:"ready",touch_type:"video"});s({videoId:(ue==null?void 0:ue.id)||D,playbackUrl:ne.directPlayUrl||W,thumbnailUrl:ne.thumbnailUrl||null}),he.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{r(!1),b()},1500)}catch(E){console.error(E),he.error("Failed to process video. Please try again."),a("record")}},[_,s]);return e.jsxs(vs,{open:t,onOpenChange:j,children:[e.jsx(Yi,{asChild:!0,children:e.jsxs(q,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(bn,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(ys,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(_s,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),n==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(ui,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:Zsr.map(C=>e.jsxs(ke,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(C.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:C.title}),e.jsx(Xe,{variant:"outline",className:"text-[10px] shrink-0",children:C.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:C.description})]},C.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(pr,{rows:5,value:i,onChange:C=>l(C.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(q,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs(q,{onClick:()=>a("record"),children:[e.jsx(En,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),n==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(pM,{maxDurationSeconds:60,onRecordingComplete:N,onRecordingStateChange:u,onError:C=>he.error(C),teleprompterContent:o&&i?e.jsx(cIe,{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(q,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs(q,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(En,{className:"h-4 w-4 mr-1.5"})," Show teleprompter"]})]})]}),n==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(ls,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ki,{value:m,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(m),"%"]})]}),n==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(ls,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ki,{value:x,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(x),"%"]})]}),n==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Ti,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function Qsr(){var A;const s=qr(),{user:t}=Cs(),{leadSite:r}=hf(),{data:n}=Wsr(),a=Ksr(),{data:i=[]}=Jye(),l=eve(),[o,c]=k.useState(null),[d,u]=k.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(k.useEffect(()=>{n&&!o&&c(n)},[n,o]),k.useEffect(()=>{t!=null&&t.id&&U.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:E})=>{const D=E||[];u({impressions:D.filter(R=>R.event_type==="impression").length,expands:D.filter(R=>R.event_type==="expand").length,ctaClicks:D.filter(R=>R.event_type==="cta_click").length,leads:D.filter(R=>R.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(ws,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const m=((A=i.find(E=>E.app_slug==="video_greeter"))==null?void 0:A.enabled)??!1,f=E=>c({...o,...E}),x=E=>f({ctas:E}),y=()=>x([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),_=E=>x((o.ctas||[]).filter(D=>D.id!==E)),b=(E,D)=>x((o.ctas||[]).map(R=>R.id===E?{...R,...D}:R)),j=()=>a.mutate(o),N=(r==null?void 0:r.subdomain_slug)||(t==null?void 0:t.id)||"",C=`